If I'm asking for a user input of numbers which continues as long as an empty string is not entered, if an empty string is entered then the program ends.
My current code is:
n=0
while n != "":
n = int(input("Enter a number: "))
But obviously this isn't exactly what I want. I could remove the int input and leave it as a regular input, but this will allow all types of inputs and i just want numbers.
Do i ago about this a different way?
calling int() on an empty string will cause a ValueError so you can encapsulate everything in a try block:
>>> while True:
try:
n = int(input('NUMBER: '))
except ValueError:
print('Not an integer.')
break
NUMBER: 5
NUMBER: 12
NUMBER: 64
NUMBER:
not a number.
this also has the added benefit of catching anything ELSE that isn't an int.
I would suggest using a try/except here instead.
Also, with using a try/except, you can instead change your loop to using a while True. Then you can use break once an invalid input is found.
Also, your solution is not outputting anything either, so you might want to set up a print statement after you get the input.
Here is an example of how you can put all that together and test that an integer is entered only:
while True:
try:
n = int(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break
If you want to go a step further, and handle numbers with decimals as well, you can try to cast to float instead:
while True:
try:
n = float(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break
Related
I came across a code that keeps asking the user for input until the user finally input an integer.
while True:
try:
n = input('Please enter an integer.')
n = int(n)
break
except ValueError:
print('Input is not an integer. Try again.')
print('Correct input of an integer.')
I tried out the code by entering a string as input and it asks me to try again. I assume it gives me a ValueError when it is executing
n = int(n)
as it can not convert a string to integer. Which the code then jumps to execute the except condition. However, I don't understand why am I still in the while loop after executing the except condition? It doesn't return True or something to continue running the while loop?
Also I entered a float as my input and it again ask me to try again. I do not understand as wouldn't int(n) be able to convert my float input to an integer without any ValueError?
You need to add a break statement after print('Input is not an integer. Try again.') or else it will keep looping back. As for handling floats, you could use int(float(n)) as suggested by tdelaney.
while True:
try:
n = input('Please enter an integer.')
n = int(float(n))
print('Correct input of an integer.')
break
except ValueError:
print('Input is not an integer. Try again.')
break
You can use the trace module to see statement by statement execution of the code:
$ python -m trace -t test.py
--- modulename: test, funcname: <module>
test.py(1): while True:
test.py(2): try:
test.py(3): n = input('Please enter an integer.')
Please enter an integer.notaninteger
test.py(4): n = int(n)
test.py(6): except ValueError:
test.py(7): print('Input is not an integer. Try again.')
Input is not an integer. Try again.
test.py(2): try:
test.py(3): n = input('Please enter an integer.')
Please enter an integer.1.1
test.py(4): n = int(n)
test.py(6): except ValueError:
test.py(7): print('Input is not an integer. Try again.')
Input is not an integer. Try again.
test.py(2): try:
test.py(3): n = input('Please enter an integer.')
Please enter an integer.3
test.py(4): n = int(n)
test.py(5): break
test.py(9): print('Correct input of an integer.')
Correct input of an integer.
In the first two test cases, the exception is run and you end up back at the top of the loop. In the final case, the break is hit which breaks you out of the nearest enclosing loop... the while.
I'm writing a program that takes in a value from the user, in the console, and I'm casting it to an int like so:
num = int(input("Enter a number: "))
I need my program to work with ints only. This works to convert an actual int entered into the console to an int I can use in the program, but if the user enters a float, like 3.1, then it doesn't cast to an int by truncating or rounding up for example.
How do I get the user to input an int rather than a float? Or how do I convert a floating point input to an int?
You can use a try catch block to ensure they only give you an int:
while True:
try:
num = int(input("Enter a number: "))
#do something with num and then break out of the while loop with break
except ValueError:
print("That was not a number, please do not use decimals!")
When ValueError (when it fails to convert to int) is excepted it goes back to asking for a number which once you get your number you can do things with said number or break out of the loop then and use num elsewhere.
You can use a try except to test if a user input is a whole number. Example code:
while True:
try:
value=int(input("Type a number:"))
break
except ValueError:
print("This is not a whole number.")
This code will loop back to the start if a user inputs something that is not an int.
So int() of a string like "3.1" doesnt work of course. But you can cast the input to a float and then to int:
num = int(float(input("Enter a number: ")))
It will always round down. If you want it to round up if >= .5:
num = float(input("Enter a number: "))
num = round(num, 0)
num = int(num)
You can simply use eval python built-in function. num = int(eval(input("Enter a number: "))).
For converting string into python code and evaluating mathimatical expressions, eval function is mostly used. For example, eval("2 + 3") will give you 5. However, if you write "2 + 3", then u will get only '2 + 3' as string value.
Try:
num = int(float(input("Enter number: ")))
and the float will be rounded to int.
You can also add a try...except method to give error to user if the number cannot be converted for any reason:
while True:
try:
num = int(float(input("Enter number: ")))
print(num)
break
except ValueError:
print("This is not a whole number")
use abs() it returns the absolute value of the given number
I'm trying to build a loop in PyCharm to force the user to submit only integers to the program.
But so far, I've only got the input in loop.
What should I do?
You have to cast the input(). In case the user provides a non-integer number, int() will throw a ValueError you you can subsequently handle as below
while True:
try:
num = int(input("Insert an integer number: "))
except ValueError:
print("Sorry, you must enter an integer.")
continue
else:
print(f"The number is: {num}")
break
This is because input always returns a string. What you can do is to try and convert this string into an int, catch the exception raised when this conversion fails, and ask user to try again. For example, like this:
x = None
while x is None:
try:
x = int(input("Enter Number:"))
except ValueError:
print("Oops, this doesn't seem right, try again!")
I am trying to create a program where the user has to input 3 numbers to be displayed by the range function. However, I am trying to assign a numerical value to when an empty input is given to one of the variables. Here is part of my code. For this section of the code, I want to assign a value of zero when the user enters empty input. However, when I try running this section of the program, I get this error: line 5, in
number = int(input_value)
ValueError: invalid literal for int() with base 10: ''
Any suggestions are greatly appreciated!
while True:
input_value = input("Type a number: ")
number = int(input_value)
if input_value.isalpha():
print("Not a number")
break
else:
if input_value is None:
number = int(0)
break
else:
if int(number):
break
print(number)
When a user input is empty, input_value will be "", which python cannot convert to an integer. number = int("") will throw an error.
What you can do is check if the input is equal "" and if it is, set number to 0, else convert it using int().
Better yet, I would wrap number = int(input_value) in a try catch statement:
while True:
input_value = input("Type a number: ")
try:
number = int(input_value)
except:
print("invalid input")
break
So to break the loop, you'd enter something thats not a number. In this case, you'd only be storing the last input value into number, so it's up to you how you want to keep track of all the inputs (probably using a list).
just a thought:
while True:
input_value = input("Type a number: ")
if input_value:
try:
number = int(input_value)
break
except:
continue
print(number)
I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)