This code is not running the else statement - python-3.x

When I input any number that is neither a multiple of 2 nor 5, the output is still the one I set for the first if statement
num = int(input("Enter a number: "))
if num%2 or num%5:
print(num)
else:
print("Not a multiple")

You should mention the '==0' portion in if statement.
I have made the changes.
num = int(input("Enter a number: "))
if (num%2 or num%5)==0:#I have changed the if statement here
print(num)
else:
print("Not a multiple")

try this it will keep asking forever
while True:
num = int(input("Enter a number: "))
if (num%2 == 0 or num%5 == 0):
print(num)
else:
print("Not a multiple")

# what is is checking for
num = int(input("Enter a number: "))
if num%2 == 2 or num%5 == 2:
print(num)
else:
print("Not a multiple")
num = int(input("Enter a number: "))
if num%2 == 0 or num%5 == 0:
print(num)
else:
print("Not a multiple")

Related

Code Not Compiling- Unable to figure out Issue

I have been stumped on this for days now and I can seem to figure out what the problem is. I am able to run all of it fine except when I select option 1 on the console menu. I will be able to make through the first inputs and then I get an error every time. Also for some reason when another option is selected, it does not jump to that option, it just starts going the password generator code instead. Any help would be appreciated. Still fairly new to all this.
import math
import sys
import random
import datetime
import string
import secrets
from datetime import date
while 1:
print("\nWelcome to the application that will solve your everday problems!")
print("\nPlease Select an Option from the List Below:")
print("1: To Generate a New Secure Password ")
print("2: To Calculate and Format a Percentage ")
print("3: To Receive the amount of days until Jul 4th, 2025 ")
print("4: To Calculate the Leg of Triangle by using the Law of Cosines ")
print("5: To Calculate the Volume of a Right Circular Cylinder ")
print("6: To Exit the Program ")
choice = int(input("Please enter your Selected Option: "))
if choice == 6:
print("\nThank you for coming, Have a Great Day!")
break
elif choice == 1:
def input_length(message):
while True:
try: #check if input is integer
length = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
if length < 5: #check if password's length is greater then 5
print("Too short password!")
continue
else:
return length
def input_yes_no(message):
while True:
option = input(message).lower()
if option not in ('y', 'n'): #check if user entered y/n (or Y/N)
print("Enter y or n !")
else:
return option
def get_options():
while True:
use_upper_case = input_yes_no("Use upper case? [y/n]: ")
use_lower_case = input_yes_no("Use lower case? [y/n]: ")
use_numbers = input_yes_no("Use numbers? [y/n]: ")
use_special_characters = input_yes_no("Use special characters? [y/n]: ")
options = (use_upper_case, use_lower_case, use_numbers, use_special_characters)
if all(option == 'n' for option in options): #check if all options are 'n'
print("Choose some options!")
elif all(option == 'n' for option in options[:-1]) and options[-1] == 'y':
print("Password can not contain only special characters")
return options
def generate_alphabet(use_upper_case, use_lower_case, use_numbers, use_special_characters):
alphabet = ''
if use_upper_case == 'y' and use_lower_case == 'y':
alphabet = string.ascii_letters
elif use_upper_case == 'y' and use_lower_case == 'n':
alphabet = string.ascii_uppercase
elif use_upper_case == 'n' and use_lower_case == 'y':
alphabet = string.ascii_lowercase
if use_numbers == 'y':
alphabet += string.digits
if use_special_characters == 'y':
alphabet += string.punctuation
def generate_password(alphabet, password_length, options):
use_upper_case = options[0]
use_lower_case = options[1]
use_numbers = options[2]
use_special_characters = options[3]
while True:
password = ''.join(secrets.choice(alphabet) for i in range(password_length))
if use_upper_case == 'y':
if not any(c.isupper() for c in password):
continue
if use_lower_case == 'y':
if not any(c.islower() for c in password):
continue
if use_numbers == 'y':
if not sum(c.isdigit() for c in password) >= 2:
continue
if use_special_characters == 'y':
if not any(c in string.punctuation for c in password):
continue
break
def main():
password_length = input_length("Enter the length of the password: ")
options = get_options()
alphabet = generate_alphabet(*options)
password = generate_password(alphabet, password_length, options)
print("Your password is: ", password)
if __name__ == "__main__":
main()
elif choice == 2:
Num = float(input("Please Enter the Numerator: "))
Denom = float(input("Please Enter the Denomenator: "))
Deci = int(input("Please Enter the Number of Decimal Places You Would Like: "))
Val = Num/Denom*100
Val = round(Val, Deci)
print("\nThe Percentage of the numbers you entered is", Val, "%")
elif choice == 3:
Today = datetime.date.today()
Future = date(2025, 7, 25)
Diff = Future - Today
print("\nTotal numbers of days till July 4th, 2025 is:", Diff.days)
elif choice == 4:
A = int(input("Please Enter angle A: "))
B = int(input("Please enter angle B: "))
Angle = int(input("Please Enter the Angle of the Triangle: "))
c = A*A + B*B - 2*A*B*math.cos(math.pi/180*Angle)
print("\nThe Leg of the Triangle is:", round(c))
elif choice == 5:
Radius = int(input("Please Enter the Radius of the Cylinder: "))
Height = int(input("Please Enter the Height of the Cylinder: "))
Volume = (math.pi*Radius*Radius)*Height
print("\nThe Volume of the Cylinder is:", Volume)

try & if statement in while loop

I would like to build a function in which if the entered integer is between 1 and 10, return the result.
Here is my code:
while True:
try:
num = int(input("Enter a number (1-10): "))
except ValueError:
print("Wrong input")
else:
if 1 <= num <= 10:
break
else:
print("Wrong input")
continue
When you enter an integer, the break does not function properly and it seems to go into a definite loop. Is it wrong to incorporate if statement into else?
Instead of break, print num.
isBetweenOneAndTen = True
while isBetweenOneAndTen == True:
try:
num = int(input("Enter a number (1-10): "))
except ValueError:
print("Wrong input")
else:
if 1 <= num <= 9:
print(num)
isBetweenOneAndTen = False
else:
print("Wrong input")
continue

Guessing random number project

I'm a newbie of coding. I'm trying to create a guessing random number game by python. The thing is I get stuck at limited users by 5 turns guessing only. Here is my code so far. Thank you
print("""
WELCOME TO GUESSING NUMBER GAME!!!
You have 5 turns to guess a random number. Good luck!
""")
def play():
import random
random_numnber = random.randint(0, 20)
guess_count = 0
while True:
try:
guess = int(input("Please enter an integer from 1 to 20: "))
guess_count += 1
except ValueError:
print("Invalid Input\n")
continue
else:
break
while random_numnber != guess and guess_count < 5:
if int(guess) < random_numnber and int(guess_count) < 5:
print("Your number is too low\n")
guess = input("Enter an integer from 1 to 20: ")
elif int(guess) > random_numnber and int(guess_count) < 5:
print("Your number is too high\n")
guess = input("Enter an integer from 1 to 20: ")
elif int(guess) == random_numnber and int(guess_count) < 5:
print("Congratulation! You Win!\n")
break
else:
print("You have guessed 5 times and all Wrong. Good luck on next game!")
break
while True:
answer = input("Do you want to play? ")
if answer == 'yes' or answer == 'y':
play()
elif answer == 'no' or answer == 'n':
break
else:
print("I don't understand\n")
This is how I would go about doing this, I have modified your code and omitted some trivial error handling for non-integer inputs, etc.
The trick is that the code section between the # *** comments will be exited automatically if the guess_count value exceeds the maximum_tries, so we can actually remove a lot of the conditionals you were performing in-line which cluttered the real logic we care about.
You can also see that the only way that we can reach the line where we print "All out of guesses" is if the user has not already guessed the correct number.
Finally, since you mentioned you are just starting out I included a main() function as well as the Pythonic block at the end, which is just a special way to tell Python which part of the program you want to start with when you run the script. Happy coding!
def play():
import random
random_number = random.randint(0, 20)
guess_count = 0
maximum_tries = 5
# ***
while guess_count < maximum_tries:
guess = int(input("Please enter an integer from 1 to 20: "))
if guess == random_number:
print("You win!")
return
elif guess < random_number:
print("Too low")
elif guess > random_number:
print("Too high")
guess_count += 1
# ***
print("All out of guesses")
def main():
while True:
answer = input("Do you want to play? (y/n): ")
if answer.startswith('y'):
play()
elif answer.startswith('n'):
print('Goodbye')
break
else:
print('I don\'t understand')
if __name__ == '__main__':
main()
def play():
import random
random_number = random.randint(0, 20)
guess_count = 0
maximum_tries = 5
# ***
while guess_count < maximum_tries:
guess = int(input("Please enter an integer from 1 to 20: "))
if guess == random_number:
print("You win!")
return
elif guess < random_number:
print("Too low")
elif guess > random_number:
print("Too high")
guess_count += 1
# ***
print("All out of guesses")
def main():
while True:
answer = input("Do you want to play? (y/n): ")
if answer.startswith('y'):
play()
elif answer.startswith('n'):
print('Goodbye')
break
else:
print('I don\'t understand')
if __name__ == '__main__':
main()

Python while loop through program not working

import random
replay = 1
while replay == 1:
replay = replay - 1
target = random.randint(1, 100)
guess = int(input("Guess the number 1-100: "))
count = 0
score = 0
while count == 0:
score = score + 1
if guess < target:
print ("The number is higher. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess > target:
print ("The number is lower. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess == target:
print ("You guessed Correctly!")
print ("Your score was:", score)
again = str(input("Play again? (yes or no)"))
if again == "yes" or "YES":
replay = replay + 1
elif again == "no" or "NO":
break
This is my code, except it doesn't do what I want it to do. After you guess the correct number, it doesn't see to properly loop through the game again when you say yes or no. It just goes through the final if statement again.
Why won't it go through the entire program again?
Your code will always be evaluated to true
if again == "yes" or "YES":
Change it to:
if again.lower() == "yes":
Or
if again in ("YES", "yes", "y",..)
When it is true, you need to break from you second loop:
if again.lower() == "yes":
replay = replay + 1
break
When it is false, don't break but exit the program using:
exit()
Since replay is only used to exit your code, you don't need it if you use exit().
Code would then be:
import random
while True:
target = random.randint(1, 100)
guess = int(input("Guess the number 1-100: "))
score = 0
while True:
score = score + 1
if guess < target:
print ("The number is higher. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess > target:
print ("The number is lower. Try again.")
guess = int(input("Guess the number 1-100: "))
elif guess == target:
print ("You guessed Correctly!")
print ("Your score was:", score)
again = str(input("Play again? (yes or no)"))
if again.lower() == "yes":
break
elif again.lower() == "no":
exit()

why does my prime number checker program always say the number is prime?

I have to make a program where the user inputs a number and it checks to see if its prime but no matter what you enter it says its prime. How do I fix this code?
def is_prime(n):
if n < 2: return False
for x in range(2, int(n**0.5) + 1):
if n % x == 0:
return False
return True
def main():
keep_going='y'
while keep_going=='y':
n=int(input("Please enter a number to see if it's prime: "))
is_prime(n)
if True:
print("It's prime")
if False:
print("it's not prime")
keep_going=input("would you like to see if another number is prime? (y/n):")
main()
Do this
while keep_going=='y':
n=int(input("Please enter a number to see if it's prime: "))
if is_prime(n):
print("It's prime")
else:
print("it's not prime")
keep_going=input("would you like to see if another number is prime? (y/n):")
You are not assigning the return value of is_prime(n) anywhere, and you are not testing this return value. if True: is unconditional execution. if False: is unconditional non-execution.
Instead, you want to test is_prime(n):
if is_prime(n):
...
else:
...
or
prime = is_prime(n)
if prime:
...
else:
...
The good news is - your is_prime function is correct, and does return False for non-prime numbers as it should :)
Try this
def is_prime(n):
if n < 2:
return False
elif n % (n // 2) == 0:
return True
else:
return False
def main():
keep_going = 'y'
while keep_going == 'y':
n = int(input("Please enter a number to see if it's prime: "))
if is_prime(n):
print("It's prime")
else:
print("it's not prime")
keep_going = input("would you like to see if another number is prime?(y/n):")
main()

Resources