I am new to Python and am trying to make this interactive guessing game using Python 3. At ANY point in the game, if user just presses "Enter" without any input, it crashes to "ValueError: invalid literal for int() with base 10: ''" What do I add here?
Just to reiterate, I am new to programming. I am trying to code this entirely only using concepts I have learned so far, so everything is fairly basic.
# 'h' is highest value in range. 'a' is randomly generated value in the range. 'u' is user input
import random
h = 10
a = random.randint(1,h)
u = int(input("Please choose a number between 1 and %d. You can exit the game by pressing 0 anytime: " %(h)))
while u != a:
if 0 < u < a:
print("Please guess higher.")
u = int(input())
elif a < u < h:
print("Please guess lower.")
u = int(input())
elif u > h:
u = int(input("Whoa! Out of range, please choose within 1 and %d!" %(h)))
elif u == 0:
print("Thanks for playing. Bye!!")
break
# I was hoping to get the below response when user just presses "enter" key, without input
else:
print("You have to enter a number.")
u = int(input())
if u == a:
print("Well done! You got it right.")
Your issue is that you're automatically converting the result of the input() call to an int, so if the user presses enter without actually entering a number, then your code will try to convert that empty string to an int, hence the error ValueError: invalid literal for int() with base 10: ''. You could add a check to make sure that the user actually enters some input before converting it to an int directly, something like this:
u = input()
while u == '':
u = input('Please enter a number')
u = int(u)
However, this doesn't stop users from entering an invalid number, such as 'a' and causing a similar error, so a better solution to catch both of these issues could be:
u = ''
while type(u) != int:
try:
u = int(input("Please choose a number between 1 and %d. You can exit the game by pressing 0 anytime: " %(h)))
except ValueError:
pass
The try except catches that error that you were seeing earlier where the user enters something that doesn't resemble a number and the while loop repeats until the user enters a valid number
That is happening because u = int(input()) always tries to convert whatever it was given into an integer. An empty string can not be converted to an integer -> you are getting this mistake. Now, python has try/except/else/finally clause exactly for this type of scenario.
What I recon you should do is something like that
while True: #loop forever
try:
u = int(input("Please, enter a number: ")) #this tries to accept your input and convert it to integer
except ValueError: #executes if there is an error in try
print("That isn't a valid integer, please try again")
else:
print("u =",u)
break #break the loop if there was no mistakes in try clause
Related
I am trying to create a function that would take a user inputted number and determine if the number is an integer or a floating-point depending on what the mode is set to. I am very new to python and learning the language and I am getting an invalid syntax error and I don't know what to do. So far I am making the integer tester first. Here is the code:
def getNumber(IntF, FloatA, Msg, rsp):
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
Rsp = int(input("What number would like to test as an interger?"))
A = rsp
if rsp == "A":
while True:
try:
userInput = int(input("What number would like to test as an interger"))
except ValueError as ve:
print("Not an integer! Try again.")
continue
else:
return userInput
break
The problem with the code you shared is :
The syntax error you mentioned is probably because the except clause has to be at the same indentation level as try, and same for if and else of the same if/else clause. All the code in the function should be indented 1 level too. Python requires all this to identify blocks of code.
You don't need to give 4 arguments to the getNumber() function if you're not using them. This isn't really a problem, but you'll have to pass it some 4 values each time you call it (for example getNumber(1,2,3,4) etc...) to avoid missing argument errors; and these won't matter because you're not doing anything with the given values inside the function - so it's a little wasted effort. I rewrote it in the example below so that you aren't dealing with more variables than you need - it makes the code clearer/simpler.
You also don't need break after a return statement because the return will exit the enitre function block, including the loop.
Try this and see if it makes sense - I've changed a lot of the code :
def getNumber():
while True:
try:
userInput = int(input("What number would like to test as an integer ? "))
return userInput
except ValueError as ve:
print("Not an integer! Try again.")
continue
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
chosen_option = input()
if chosen_option == 'A':
integer_received = getNumber()
print(integer_received, "was an int !")
else:
print("You did not choose 'A' or 'B'")
To determine whether a number is a float or integer, you can use this approach
float is nothing but the integer with floating-point(.).
to determine this we first need to convert it to string and find does it contain a point or not.
number = input("Enter a numbeer\n")
if number.find(".") == -1:
# find will return -1 when the value is not in string
print("it is integer")
else:
print("it is float")
Hello Fellow Developer's and Eng's:
How can I handle these two type's of input 1) when user enter "-0" and 2) When user enter minus symbol "-", within my while loop for adding nonnegative integers.
The program developed functions in the overall design, which is to add non negative integers, but it has a flaw when a user input -0 or -(minus) sign. I want to print('you have entered a negative int or a negative/minus - symbol') when these entries are made by the user.
Currently, the program continues without adding when user submit -0 in the input and there is ValueError when user just submit - symbol.
Please provide feedback.
entry = 0
sum = 0
# Request input from the user
print('This is nonnegative integer addition program. \n',)
while entry >= 0:
entry=int(input('Please enter numbers to add: '))
if entry >=0:
sum+=entry
elif entry<0 or str(entry[0])=='-' or str(entry)=='-0': # -0 nor (first index -(minus) does not work
print('You have entered a negative integer or symbol:', \
entry, ', therefore you have been exited out of the program')
print('total integer input sum =',sum)
As mentioned in the other answer. You convert your value to an int and you can no longer access the characters. I've made the program store the user_input and check that.
entry = 0
sum = 0
# Request input from the user
print('This is nonnegative integer addition program. \n',)
while entry >= 0:
user_input = input('Please enter numbers to add: ')
if '-' in user_input:
print(
'You have entered a negative integer or symbol:',
user_input,
', therefore you have been exited out of the program'
)
break
entry = int(user_input)
sum+=entry
print('total integer input sum =',sum)
In this version I store the input string as user_input and check it for a '-' symbol. I use '-' in instead of user_input[0]=='-' because input that starts with a space can still work with int.
Another thing to note, your if/elif was over specified.
if entry >=0:
sum+=entry
elif entry<0 or str(entry[0])=='-' or str(entry)=='-0':
break
In your second clause entry is guaranteed to be less than zero. So the str(entry[0]) never gets called. Thankfully because it was an error. Your if statement is equivalent to.
if entry>=0:
...
else:
...
Lastly a small point. When you have a set of brackets like in your print statment. You don't need a \ to indicate a line continuation.
print(
"one",
"two"
)
Python recognizes the open (. If you wanted to continue a string you would need it.
print("one \
two")
When you are storing the input as int entry=int(input('Please enter numbers to add: ')) the entry value is 0 because on int the is no -0 so if you want to check if the user input -0 you need to keep it as str.
You can try
entry = 0
sum = 0
print('This is nonnegative integer addition program. \n',)
while int(entry) >= 0:
entry=input('Please enter numbers to add: ')
if entry[0] !='-':
if int(entry) >= 0:
sum+=int(entry)
elif entry[0]=='-' or entry=='-0':
print('You have entered a negative integer or symbol:', \
entry, ', therefore you have been exited out of the program')
entry = -1
print('total integer input sum =',sum)
I want to ask a user for a number(among other things) and if they input anything other than an int, it should tell them to try again.
I'm still getting use to python syntax, what's the best way to do this?
excerpt below of what I tried:
try:
num = int(i)
except ValueError:
while type(num) != int:
num = input("Please input an actual number or q to quit: ")
while True:
num = input("Input a number. ")
if num.isdigit()==False:
print("Try again.")
else:
break
This should work unless if there's a negative value entered in which case you need to make a check if the first character is a - sign.
This program works fine in python2, but prints error after inputing '1' at the prompt when running it in python3. I'm wondering if there is still a way to accept user input within an if statement or if I'd have to go about this differently. My program below:
#!/usr/bin/python3
select_one = input('Please enter a number from the menu below:
\n1.Convert Celcius to Farenheit \n2. Convert Farenheit to Celcius\n>\t')
if select_one == 1:
c = input('Please enter the temperature\n>\t')
f = c*(9.0/5.0)+32
print(f, 'F', sep='')
elif select_one == 2:
f = input('Please enter the temperature\n>\t')
c = f*(5.0/9.0)-32
print(c, 'C', sep='')
else:
print('Error')
By default the input() takes value as string in python 3.. so you might want to change input as
select_one =int( input('Please enter a number from the menu below: \n1.Convert Celcius to Farenheit \n2. Convert Farenheit to Celcius\n>\t'))
The other answers will get you partway, but a nicer way to handle input in your script would be something like this:
def input_type(prompt, outputType):
while TrueL
try:
return outputType(input(prompt))
except ValueError:
print("Invalid input. Required type is {}".format(outputType.__name__))
You can then replace your first call to input with input_type(<your prompt>, int) and the second two with input_type(<your prompt>, float) without changing the rest of your code.
As a side note - your conversion from fahrenheit to celsius isn't quite right. You might want to test it by converting from celsius to fahrenheit and back again.
You are accidentally relying on the fact that in Python 2, input() would parse the input, not just return it as a string. So "1" (str) becomes 1 (int). But in Python 3, input() does what raw_input() used to do, so the returned value is always a string.
To fix it, change this:
if select_one == 1:
To this:
if select_one == "1":
This is from Ken Lambert's "Fundamentals of Python":
{
sum=0
while True:
data = input('enter a number or just enter to quit: ')
if data == "":
break
number = float(data)
sum += number
print("the sum is", sum)
}
error message:
data = input('enter a number or just enter to quit: ')
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
Process finished with exit code 1
Use raw_input rather than input. The description of input begins with:
Equivalent to eval(raw_input(prompt))
You're getting an error because eval("") reports a syntax error, because there's no expression there; it gets EOF immediately.
On the other hand, the description of raw_input says:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Since you want the string that the user typed, rather than the evaluation of an expression, this is the function you should use.
The error you provided is because you used input, which tries to execute the text from stdin as python code https://docs.python.org/2/library/functions.html#input. I've provided some fixes below.
sum=0
while True:
data = raw_input('enter a number or just enter to quit: ')
if len(data) < 1:
break
number = float(data)
sum += number
print("the sum is %f" % sum)
I found that you have a syntax problem with your code. If you want to to put data in a variable you should use that:
variable = raw_input("Please enter ____")
Therefore you should replace line 4 to:
data = raw_input('enter a number or just enter to quit: ')