try & if statement in while loop - python-3.x

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

Related

Why is my function returning 0 after a try-except clause?

This code works as intended if valid input is received the first time around. If the input received is incorrect, it will prompt you to try again, and when valid input is finally received it will go on to return 0.
def string_num_query():
string_num = 0
try:
string_num = int(input("Enter number of strings (1-6): "))
if string_num < 1 or string_num > 6:
print("Value must be between 1 and 6.")
string_num_query()
except ValueError:
print("User input must be a number.")
string_num_query()
return string_num
I've tried following the flow of it and just can't see where I've gone wrong. Any help is much appreciated!
Your recursive function isn't returning the value of the recursive call, but rather the hard-coded value of string_num each time.
But, you shouldn't be using recursion to implement a possibly infinite loop at all. Use a while loop instead and break out of the loop when the value of num is valid.
def string_num_query():
while True:
string_num = input("Enter number of strings (1-6): ")
try:
num = int(string_num)
except ValueError:
print("User input must be a number")
continue
if 1 <= num <= 6:
break
return num
def string_num_query():
string_num = 0
try:
string_num = int(input("Enter number of strings (1-6): "))
if string_num < 1 or string_num > 6:
print("Value must be between 1 and 6.")
return string_num_query()
except ValueError:
print("User input must be a number.")
return string_num_query()
return string_num

This code is not running the else statement

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")

How to show invalid input

My task is:
Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
I want to ignore any invalid integer and print 'Invalid Output' message after calculating the maximum and minimum number.But it always prints the invalid message right after user input. How am i supposed to solve this?
Thanks in advance.
Code:
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
n = int(num)
except:
print('Invalid input')
if largest is None:
largest=n
elif n>largest:
largest=n
elif smallest is None:
smallest=n
elif n<smallest:
smallest=n
print("Maximum", largest)
print('Minimum', smallest)
You could store that invalid output as a boolean variable
largest = None
smallest = None
is_invalid=False
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
n = int(num)
except:
is_invalid=True
if largest is None:
largest=n
elif n>largest:
largest=n
elif smallest is None:
smallest=n
elif n<smallest:
smallest=n
print("Maximum", largest)
print('Minimum', smallest)
if is_invalid:
print('Invalid Input')
This can be one solution
largest = None
smallest = None
errors = False
while True:
num = input('Please type a number : ')
if num == 'done':
break
try:
number = int(num)
#your logical operations and assignments here
except ValueError:
errors = True
continue
if errors:
print('Invalid input')
else:
print('Your Results')
Hope this helps :)
If you are familiar with lists,you can use list to solve your problem effectively,
here is a modified version of your code which uses list,
num1=[]
while True:
num = input("Enter a number: ")
num1.append(num)
if num == "done":
break
for i in num1:
try:
i = int(i)
except:
print('Invalid input:',i)
num1.remove(i)
print("Maximum", max(num1))
print('Minimum', min(num1))
output:
Enter a number: 34
Enter a number: 57
Enter a number: 89
Enter a number: ds
Enter a number: 34
Enter a number: do
Enter a number: done
Invalid input: ds
Invalid input: do
Maximum 89
Minimum 34
hope this helps,let me know if anything is incorrect.
Try removing the (int) in try block. Because you want only integer input in try block so if does not satisfy the condition of integer input it will execute the except block.
Your code should look like this in try block:
try:
n = num

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