My code needs to validate user input to make sure they enter a number and keep looping until they enter a number.
My code:
user_input=input("Enter a number: ")
while user_input != int:
user_input=input("Error: Enter a number: ")
My Output:
Enter a number: d
Error: Enter a number: f
Error: Enter a number: 5
Error: Enter a number: 5
Error: Enter a number: 3
Why doesnt it even accept numbers?
Answer
I think the piece of code below solves your problem in a way that is easily understood.
user_input = input("Enter a number: ")
while not user_input.isnumeric():
user_input = input("Error: Enter a number: ")
Explanation
The code you have didn't work because of while user_input != int.
When you call the input function, and the user provides an input, that input is always a string.
>>> num = input('Enter a number: ') # 5, as a string
>>> num
'5'
Your intent is to check if num is a number. So, to check if a string represents some number, you can use the str.isdigit(), str.isdecimal(), and str.isnumeric() methods. You can read more here.
It's easy to mistakenly believe the following approach is viable, but it can quickly get messy.
while not isinstance(user_input, int):
Remember, the input you receive as a result of calling the input function will be a string. Therefore, the code above will always be True, which is not what you want. Though, the code above could work if you change user_input to be of type int.
>>> num = input('Enter a number: ') # 5, as a string
>>> num
'5'
>>> int(num)
5
>>> isinstance(num, int)
True
But the interpreter would throw an error if num was something else.
>>> num = input('Enter a number: ') # 'A'
>>> int(num)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'A'
This brings us back to the answer, which involves using a string method to check if the string represents some number. I chose to use the str.isnumeric() method because it is the most flexible.
I hope this answers your question. Happy coding!
Related
I'm trying to write a simple program where a variable will store the input type in by a user until the word "done" is seen. After that, the program will print out the maximum and minimum value store in the variable. However, I would like to prevent the variable from storing characters or strings where the user may accidentally type in. What are ways that I can use? Try and except?
a=0
store1=''
store2=''
while store1 !='done':
store1 = input('Enter a number: ')
store2=store2+' '+store1
a =a+1
store3=store2.split()
store4=store3[:a-1]
print('Maximum: %s'%(max(store4)))
print('Minimum: %s'%(min(store4)))
I tried another way and I got this problem. Does anyone know what is wrong?
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
a=0
store1=''
store2=''
while store1 !='done':
store1 = input('Enter a number: ')
b = RepresentsInt(store1)
if(b==True):
store2=store2+' '+store1
# a =a+1
store3=store2.split()
#store4=store3[:a-1]
print(store3)
print('Maximum: %s'%(max(store3)))
print('Minimum: %s'%(min(store3)))
#print(len(store3))
The stored value seems to contain only numbers in string-format. However, when it prints out the max and min values, it doesn't print out the correct max and min as the picture shown below.
Using your current implementation (number of issues), here's how you'd perform the check:
a=0
store1=''
store2=''
while store1 !='done':
store1 = input('Enter a number: ')
if store1 == 'done':
break;
try:
int(store1)
except ValueError:
continue
store2=store2+' '+store1
a =a+1
store3=store2.split()
store4=store3[:a-1]
print('Maximum: %s'%(max(store4)))
print('Minimum: %s'%(min(store4)))
I added in an immediate check for the input value (otherwise it executes the with the 'done' value, causing the Maximum: d output).
For the input checking, the approach is trying to convert the string to an integer and returning to the start of the loop if a ValueError is caught.
Using this looks like:
$ python3 input.py
Enter a number: 1
Enter a number: 2
Enter a number: what
Ivalid input.
Enter a number: 3
Enter a number: 4
Enter a number: done
Maximum: 3
Minimum: 1
So, we still have a problem with actually finding the maximum value. Which begs the question, why all the string manipulation?
Here's a simpler implementation using an array instead:
numbers = []
while True:
input_value = input('Enter a number: ')
if input_value == 'done':
break
try:
int_value = int(input_value)
except ValueError:
print("Ivalid input.")
continue
numbers.append(int_value)
print('Maximum: %s'%(max(numbers)))
print('Minimum: %s'%(min(numbers)))
Usage:
$ python3 input.py
Enter a number: 1
Enter a number: 2
Enter a number: what
Ivalid input.
Enter a number: 3
Enter a number: 4
Enter a number: done
Maximum: 4
Minimum: 1
EDIT: The problem with your second attempt is that you are performing a lexicographic sort, instead of a numerical one. This is due to fact that the array is storing string values.
# sorting strings, lexicographically
>>> [x for x in sorted(['1000', '80', '10'])]
['10', '1000', '80']
# sorting numbers, numerically
>>> [x for x in sorted([1000, 80, 10])]
[10, 80, 1000]
In my fixed example above, the strings are converted to integer values before they get stored in the array, so they end up being sorted numerically.
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":
When I write something like this
a = input("Please enter the number: ")
Please enter the number: 12
type(a)
<class 'str'>
It always thinks as like its a string even tho its a number. Is there any solution to make python choose the variable type correct? What I am searching for is something like this
a = input("Please enter the number: ")
Please enter the number: 12.5
type(a)
<class 'float'>
Is there any command to do this? Except from "eval", to pick the variable type correctly, when its a number as a integer, when it has decimal place as a float, when its bunch of letters its a string. Is there any command to do something like this?
Try converting the input to an integer
a = int(input("Please enter the number: "))
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: ')
I have been practicing the basics now i am try to do a practice task in uni and i can't seem to find where i am going wrong can anyone point me in the right direction and explain to me what i am doing wrong please , thank you
this is the question
Write some Python code that requests 2 numbers and prints the result of applying the operators + - * / eg.
Please enter your first number:5
Please enter your second number:3
5 + 3 = 8
5 – 3 = 2
5 * 3 = 15
5 / 3 = 1.666666667
Test this code with at least ten different values. (Hint:You may need to think about how you manage the types)
and this is my coding
A= input ("Please enter your first number:")
B= input ("please enter your second number:")
A+B
A-B
A*B
A/B
and i get an error message saying
Please enter your first number:5
please enter your second number:3
Traceback (most recent call last):
File "/Users/salv/Documents/PRACTISE PYTHIN.py", line 6, in <module>
A-B
TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>>
Input will return a string object, and the - operator expects two integers. Cast it to an int with int()
i.e.
A = int(input("Please enter your first number:"))
This happens because when python reads some user input, it reads it as a string (of type str), not as a number (of type int in this case).
So what you need to do is to convert the string representation of the number you entered, into a numeric type. This can be done by calling int() on your string as follows:
users_input = input("Enter a number: ")
A = int(users_input)
Consider this:
>>> A = input("Enter a number: ")
Enter a number: 5
>>> A
'5'
Notice the quotes around 5. This indicates that it's a string. You could confirm this with the use of type
>>> type(A)
<class 'str'>
>>> B = int(A)
>>> B
5
Note: no quotes around 5. It's a numeric type. Since it isn't followed by a .0, it's not a float (floating point decimal type). Rather, it is an int (integer type). Again, this can be confirmed with type
>>> type(B)
<class 'int'>