In this project I am checking the number is even or odd with the help of user input. The problem I am stuck on is that when the user types a str character the whole project blows up. I want to write a program where even if the user typed a string the program won't blow up would print("Please type a number") a message like that.
type num = int(input("Enter a number: "))
if num % 2 == 0:
print(str(num) + ' is an even number')
else:
print(str(num) + ' is an odd number')
I tried try and except and even functions but I couldn't provide a logic to run the program.
Not sure why you are using typeat the beginning, but this may help you:
while True:
try:
num = int(input('Enter a number: '))
break
except ValueError:
print('Please type a number.')
continue
if num % 2 == 0:
print(str(num) + ' is an even number')
else:
print(str(num) + ' is an odd number')
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
My goal is creating a factorial program in python that asks infinite user input to find factorial of the number user type, until I would like to quit the program. But there is probably discrepancy between the lines of the code to works for exit the program and integer numbers below it.
1) I tried to solve this to not write int(input) I wrote just
input('Enter a number. Type exit to stop:> ')
both above or below the while True statement but it didn't work.
2) I also want to use lower() function to quit the program but when I use it, the discrepancy happens again because I ask user input for an integer but when I turn it to a normal input and type it the above while True statement, problem occurs.
3) Also I want to user input as a number with using that isdigit() function tried to use like this but it didn't work well:
factorial = 1
user_input = input('Enter a number: ')
while user_input.lower() != 'exit':
while not user_input.isdigit():
print('This is not a number. Please try again:> ')
user_input = int(input('Try again:> '))
user_input = int(input('Enter a new number: '))
.
.
.
and this, too didn't work
My actual code is this:
while True:
factorial = 1
user_input = int(input('Enter a number. Type exit to stop:> '))
if user_input == 'exit':
print('You are quitting the program')
break
elif user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, user_input + 1):
factorial = factorial * i
print("The factorial of", user_input, "is", factorial)
The program works like this:
Enter a number. Type exit to stop:> 4
The factorial of 4 is 24
Enter a number. Type exit to stop:> 5
The factorial of 5 is 120
Enter a number. Type exit to stop:> 6
The factorial of 6 is 720
and when I type 'exit' to quit from program I am receiving this kind of error:
Traceback (most recent call last):
File "E:/Kodlar/Python/Taslak projeler/taslak177.py", line 5, in <module>
user_input = int(input('Enter a number. Type exit to stop:> '))
ValueError: invalid literal for int() with base 10: 'exit'
As you can see, code blocks work instead of quitting the program with user input. How can I fix this?
Can anyone help? Thanks already!
Edit: I reorganized the code and it works perfectly fine. Thanks for your all responses!
while True:
user_input = input("Enter a number:> ")
if user_input == "exit":
print('You are quitting the program...')
break
else:
try:
factorial = 1
user_input = int(user_input)
if user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, user_input + 1):
factorial = factorial * i
print(f'The factorial of {user_input} is {factorial}')
except ValueError:
print("Please provide a valid number")
You should check if the input is exit before converting it to int and if so, break the loop.
Try this instead:
while True:
user_input = input("Enter a number:")
if user_input == "exit":
print('You are quitting the program')
break
else:
try:
user_number = int(user_input)
if user_number < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_number == 0:
print("The factorial of 0 is 1")
else:
# calc factorial here
except ValueError:
print("Please provide a valid number")
Your program get int inputs,
user_input = int(input('Enter a new number: '))
try this instead, get string input
user_input = input('Enter a new number: ')
and convert it into int later
user_input = int(user_input)
Because you are casting the user's response (a string) into an int in both cases.
user_input = int(input('Enter a new number: '))
and later
user_input = int(input('Enter a number. Type exit to stop:> '))
Perhaps try a little tweak:
while True:
factorial = 1
user_input = input('Enter a number. Type exit to stop:> ')
if user_input.lower().strip() == 'exit':
print('You are quitting the program')
break
elif user_input.isnumeric() and user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input.isnumeric() and user_input == 0:
print("The factorial of 0 is 1")
elif user_input.isnumeric():
for i in range(1, user_input + 1):
factorial = factorial * i
print("The factorial of", user_input, "is", factorial)
else:
print("Please enter an integer or 'exit'")
You could also wrap another if so you don't duplicate the isnumeric() tests
For some reason my code won't return False EVER and I cant figure it out?
I think the issue is with how my between function is written but it makes sense to me. Also I am struggling to get my restart function to work. If somebody could help me with those 2 areas I would be extremely grateful.
def between(a,b,c):
if a>b and b<c:
Rnum =True
else:
Rnum=False
def main(): #main function need in all programs for automated testing
print ("This program will ask the user for 3 numbers and determine if
the second number lies betweenthe first and the third")
print()
while True:
numone=input('Please enter the first number - the low number:')
if numone.isdigit():
numone=int(numone)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numtwo=input('Please enter the second number - the test number: ')
if numtwo.isdigit():
numtwo=int(numtwo)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numthree=input('Please enter the third number - the high number:')
if numthree.isdigit():
numthree=int(numthree)
break
else:
print('Invalid response. Please enter a whole number.')
sprint()
number =between(numone,numtwo,numthree)
print('The statement ' + str(numone) + ' lies between ' + str(numtwo) + ' and ' + str(numthree) + ' is True.'"\n")
#Restart question
while True:
restart = input('Would you like to play again (Y/N)? ')
if restart == 'Y' or restart == 'y':
print('Restarting!' + ('\n' * 2))
break
if restart == 'N' or restart == 'n':
print('Thank you for playing.' + ('\n' *2))
break
else:
print("Invalid response. Please answer with a 'Y' or 'N'")
if restart == 'N' or restart == 'n':
break
else:
continue
if __name__ == '__main__' :
main() #excucte main function
The logic of your between function was slightly wrong (I've rename the variables to make it slightly clearer). In addition, you were not returning the value of the function so it was basically doing nothing. You were also always printing "True".
I have modified your code to return the result of the between function. I have made the result of this function a variable called true_or_false which is then printed at the end of each game.
In order to get your code to loop, all you need is another while loop which you can break out of if the user does not want to continue.
def between(low,test,high):
if low < test < high:
return True
else:
return False
def main(): #main function need in all programs for automated testing
print ("This program will ask the user for 3 numbers and determine if\nthe second number lies betweenthe first and the third")
while True:
while True:
numone=input('\nPlease enter the first number - the low number:')
if numone.isdigit():
numone=int(numone)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numtwo=input('Please enter the second number - the test number: ')
if numtwo.isdigit():
numtwo=int(numtwo)
break
else:
print('Invalid response. Please enter a whole number.')
while True:
numthree=input('Please enter the third number - the high number:')
if numthree.isdigit():
numthree=int(numthree)
break
else:
print('Invalid response. Please enter a whole number.')
true_or_false =between(numone,numtwo,numthree)
print('The statement ' + str(numtwo) + ' lies between ' + str(numone) + ' and ' + str(numthree) + ' is ' + str(true_or_false) + "\n")
restart = ""
while restart.upper() != "Y":
restart = input('Would you like to play again (Y/N)? ')
if restart.upper() == "Y":
print('Restarting!')
elif restart.upper() == "N":
print ('Thank you for playing.')
sys.exit()
else:
print("Invalid response. Please answer with a 'Y' or 'N'")
if __name__ == '__main__' :
main() #excucte main function
You have small mistake, either in the problem definition or in the example code. Anyways if you modify it a bit:
def between(a,b,c): if b>a and b<c: return 'True'
else: return 'False'
print('The statement ' + str(numtwo) + ' lies between '
+ str(numone) + ' and ' + str(numthree) + ' is ' +
between(a,b,c) +"\n")
Using this code:
import random
import query
import sys
while True:
try:
number = int(input('Choose a number between 0 and 10:'))
except ValueError:
print("That is not a number.")
continue
if number > 10:
print('Your number is too large.')
continue
elif number < 0:
print('Your number is too small.')
continue
break
result = random.randint(0, 10)
print("You're number: " + str(number))
print("Our number: " + str(result))
if number == result:
print('Congratulations!')
else:
print('Close, but no cigar.')
while True:
try:
answer = query.query_yes_no('Do you wish to contunue?')
if answer == "yes":
while True:
try:
number = int(input('Choose a number between 0 and 10:'))
except ValueError:
print("That is not a number.")
continue
if number > 10:
print('Your number is too large.')
continue
elif number < 0:
print('Your number is too small.')
continue
break
print("You're number: " + str(number))
print("Our number: " + str(result))
if number == result:
print('Congratulations!')
continue
else:
print('Close, but no cigar.')
continue
elif answer == "no":
print('Goodbye.')
break
break
break
exit()
I keep getting a SyntaxError: unexpected EOF while parsing. It says it is on line 60. I have tried removing the exit() and the breaks but that doesn't work. I'm sure it is something simple as I am still new to Python. Any help would be greatly appreciated!
You need to include another except for the first try inside your infinite while loop. That's why, it may be giving a syntax error.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
import random
print("hello, what is your name?")
GG = input()
print("well, " + GG + ", I am thinking of a number between 0 and 20")
number = random.randint(0,20)
try:
for taken in range(1,7):
print("Take a guess.")
guess = int(input())
if guess < number:
print("your guess is too low.")
elif guess > number:
print("your guess is too high.")
else:
break
except ValueError:
print("please enter a valid number")
if guess == number:
print("good job, "+ GG + " you guessed my number in " + str(taken) + " guesses")
else:
print("nope,the number i was thinking of was " + str(number))
If I want everytime when the player types an invalid input and the "Take a guess" game continues, how can I do?
Design
I think that you should separate, as far as possible, the two issues of looping on the responses and getting a validated response, and you can achieve this by writing a function that handles the problem of validating the user input.
Such a function needs to know how to prompt the user and what to tell the user if their input is invalid, so we must provide two arguments to the function, but we provide also reasonable defaults for the arguments...
To look at the correctness of the input, we use a try: ... except: ... clause, if the body of try raises an error, except looks at the error and if it is a particular one (for us, ValueError) the body of the except is executed.
The body of the except ends with a call to the function that we are defining, because this is another way of looping, if you consider what is happening... and in this case it is a simpler way of looping.
Implementation
That said, with the understanding of what we need in our function, we write it:
def get_integer(prompt='Enter an integer: ',
err_prompt='Not an integer, please try again.'):
answer = input(prompt)
try:
number = int(answer)
return number
except ValueError:
print(err_prompt)
return get_integer(prompt, err_prompt)
Testing
And now a bit of testing,
In [19]: get_integer()
Enter an integer: 1
Out[19]: 1
In [20]: get_integer()
Enter an integer: a
Not an integer, please try again.
Enter an integer: 1
Out[20]: 1
In [21]: get_integer(prompt='Un numero intero, per favore: ')
Un numero intero, per favore: 23.2
Not an integer, please try again.
Un numero intero, per favore: 22
Out[21]: 22
In [22]: get_integer(err_prompt='Naaaah!')
Enter an integer: q
Naaaah!
Enter an integer: 11
Out[22]: 11
In [23]:
Putting it all together
I've used your implementation, because for sure it is good enough, but I've changed a little the capitalization of the strings, no more try ... except as this is hidden in get_integer() and the introduction of an else clause to the for loop that is executed on normal termination, so that your user is informed of the reason why the program is stopping.
import random
def get_integer(prompt='Enter an integer: ',
err_prompt='Not an integer, please try again.'):
answer = input(prompt)
try:
return int(answer)
except ValueError:
print(err_prompt)
return get_integer(prompt, err_prompt)
print("Hello, what is your name?")
GG = input()
print("Well, " + GG + ", I am thinking of a number between 0 and 20...")
number = random.randint(0,20)
for taken in range(1,7):
print("Take a guess.")
guess = get_integer()
if guess < number:
print("Your guess is too low.")
elif guess > number:
print("Your guess is too high.")
else:
print("Your guess is exact!")
break
else:
print("Too many attempts. You lose!")
Wrap your input in some kind of while loop.
def checkIsValid(value):
#some validity checking function here.
for taken in range(1,7):
print("Take a guess.")
guess = input()
isValid = checkIsValid(guess)
while (not isValid):
print("Invalid input")
guess = input()
isValid = checkIsValid(guess)
guess = int(guess)
#continue with the valid value.
'''
Created on 2016-3-24
#author: GuangFa
'''
import random
def get_name():
"""
Get name from the input.
:Usage:
get_name()
"""
print("hello,what is your name?")
name=raw_input()
return name
def get_number():
"""
Get number from the input.Return the number until the input is a valid number
:Usage:
get_number()
"""
is_number=False
while not is_number:
try:
number=input('please enter a valid number:')
except Exception ,e:
is_number=False
else:
is_number=True
return number
def guess():
"""
Guess the number.The system generates a random number,
Only 7 chances to guess the number.
:Usage:
guess()
"""
name=get_name()
print("well,%s, I am thinking of a number between 0 and 20"%name)
number = random.randint(0,20)
for taken in range(1,7):
print("Take a guess.")
guess=get_number()
if number==guess:
print ("good job, %s you guessed my number in %s guesses"%(name,str(taken)) )
break
if guess < number:
print("your guess is too low.")
elif guess > number:
print("your guess is too high.")
if taken==6:
print "nope,the number i was thinking of was " + str(number)
guess()
I've looked up several of these questions and can't seem to apply it to my code correctly. I'm definitely new to Python and developed a number guessing game for practice. The last error handling I need is to make sure that anything typed that is not an integer, will return an error message. I was hoping to use an "if" statement like I have for other conditions, but will work with what I can get. Thanks!
(this is just a snippet. i didn't include the entire program)
def gamestart():
print(rndnumber)
for GuessAmount in range (1,11):
ActualGuess = int(input("Guess number " + str(GuessAmount) + ": "))
if ActualGuess < rndnumber:
print("HIGHER!")
if ActualGuess > rndnumber:
print("LOWER!")
if ActualGuess != rndnumber:
GuessAmount == GuessAmount + 1
if ActualGuess == rndnumber:
print("You Win!")
gameend()
print("")
print("Sorry, but you ran out of guesses.")
print("")
gameend()
Use try/except:
while True:
guess = input("Guess number " + str(GuessAmount) + ": ")
try:
guess_int = int(guess)
break
except ValueError:
print "please enter only integers"
Now you have your (converted to integer) input in guess_int.
If it was impossible to convert the input to integer, user gets warning and enters number once again.