This question already has answers here:
How can I convert a string to an int in Python?
(8 answers)
How do I parse a string to a float or int?
(32 answers)
Closed 8 years ago.
I wanted to make a simple program on my raspberry pi that will let a LED flash as many times as the number you type in. My program is working, but is a bit repetitive:
times = raw_input('Enter a number: ')
if times == '1':
times = 1
elif times == '2':
times = 2
elif times == '3':
times = 3
elif times == '4':
times = 4
elif times == '5':
times = 5
This would take a lot of programming to handle a larger inputs like 145.
Does anybody know a smarter and faster way of doing it?
PS: Code is finished;
# I know i need to import GPIO and stuff, this is just an example.
import time
while True:
try:
times = int(raw_input('Enter a number: '))
break
except ValueError:
print "Enter a number!"
print 'Ok, there you go:'
while times > -1:
if times > 0:
print 'hi'
times = times-1
time.sleep(1)
continue
elif times == 0:
print 'That was it.'
time.sleep(2)
print 'Prepare to stop.'
time.sleep(3)
print '3'
time.sleep(1)
print '2'
time.sleep(1)
print '1'
time.sleep(1)
print 'BYE'
break
Thank you.
times = int(raw_input('Enter a number: '))
If someone enters in something other than an integer, it will throw an exception. If that's not what you want, you could catch the exception and handle it yourself, like this:
try:
times = int(raw_input('Enter a number: '))
except ValueError:
print "An integer is required."
If you want to keep asking for input until someone enters a valid input, put the above in a while loop:
while True:
try:
times = int(raw_input('Enter a number: '))
break
except ValueError:
print "An integer is required."
Wrap your input in int or float depending on the data type you are expecting.
times = int(raw_input('Enter a number: '))
print type(times)
Outputs:
Enter a number: 10
<type 'int'>
If a user inputs something other than a number, it will throw a ValueError (for example, inputing asdf results in:)
ValueError: invalid literal for int() with base 10: 'asdf'
You can cast the input as an integer and catch the exception if it isn't:
try:
times = int(raw_input('Enter a number: '))
# do something with the int
except ValueError:
# not an int
print 'Not an integer'
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
I start learning python, and in an exercise it asks to create a program that only postive intger number will be accepted.
This is what I have written:
while True:
number = input('Type an integer positive number: ')
try:
number = int(number)
break
except ValueError:
print ('Value not accepted')
break
How can I add in my block the >0 check ?
You could throw an exception using raise.
while True:
number = input('Type an integer positive number: ')
try:
number = int(number)
if number < 0 :
raise ValueError
except ValueError:
print ('Value not accepted')
break
Output
Type an integer positive number: 3
Type an integer positive number: 4
Type an integer positive number: -4
Value not accepted
I'm guessing you wanna keep your exception handling as it is so my suggestion would be:
while True:
number = input('Type an integer positive number: ')
try:
number = int(number)
if number <= 0:
raise ValueError('Negative number or zero entered.')
break
except ValueError as ve:
print(ve)
break
I hope this helps you to finish your task and you continue to have fun learning Python. I'm also new to this but Python is so much fun! :)
use continus to let user input again.
while True:
number = input('Type an integer positive number: ')
try:
number = int(number)
if number < 0:
continue
else:
break
except ValueError:
print('Value not accepted')
break
You should try to check if is bigger than 0 before the first break.
while True:
number = input('Type an integer positive number: ')
try:
number = int(number)
if number > 0:
break
except ValueError:
print ('Value not accepted')
break
I'm trying to work out the average of numbers that the user will input. If the user inputs nothing (as in, no value at all) I want to then calculate the average of all numbers that have been input by the user upto that point. Summing those inputs and finding the average is working well, but I'm getting value errors when trying to break the loop when the user inputs nothing. For the if statement I've tried
if number == ''
First attempt that didn't work, also tried if number == int("")
if len(number) == 0
This only works for strings
if Value Error throws up same error
Full code below
sum = 0
while True :
number = int(input('Please enter the number: '))
sum += number
if number == '' :
break
print(sum//number)
Error I'm getting is
number = int(input('Please enter the number: '))
ValueError: invalid literal for int() with base 10:>
Any help much appreciated!
EDIT: Now getting closer thanks to the suggestions in that I can get past the problems of no value input but my calculation of average isn't working out.
Trying this code calculates fine but I'm adding the first input twice before I move to the next input
total = 0
amount = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
total = number + number
amount += 1
except:
break
total += number
print(total/amount)
Now I just want to figure out how I can start the addition from the second input instead of the first.
sum = 0
while True :
number = input('Please enter the number: '))
if number == '' :
break
sum += int(number)
print(sum//number)
try like this
the issue is using int() python try to convert input value to int. So, when its not integer value, python cant convert it. so it raise error. Also you can use Try catch with error and do the break.
You will always get input as a string, and if the input is not a int then you cant convert it to an int. Try:
sum = 0
while True :
number = input('Please enter the number: ')
if number == '' :
break
sum += int(number)
print(sum//number)
All of the answers dont work since the print statement referse to a string.
sum = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
except:
break
sum += number
print(sum//number)
including a user_input will use the last int as devisor.
My answer also makes sure the script does not crash when a string is entered.
The user has to always input something (enter is a character too) for it to end or you will have to give him a time limit.
You can convert character into int after you see it isn't a character or
use try & except.
sum = 0
i = 0
while True :
try:
number = int(input('Please enter the number: '))
except ValueError:
break
i += 1
sum += number
try:
print(sum/number)
except NameError:
print("User didn't input any number")
If you try to convert a character into int it will show ValueError.
So if this Error occurs you can break from the loop.
Also, you are trying to get the average value.
So if a user inputs nothing you get NameError so you can print an Error message.
I am new to the python and My program is a simple addition program where it can add any number input by user(int or float) and the loop stops on entering q. Now my problem is that I keep getting "ValueError", every time I enter some numbers and then enter q to stop.
I have used eval() function to determine the datatype of the input data entered. and i have got my addition inside an infinite while loop that breaks on entering q.
This is my code:
sum,sum_i,c=0,0,0
sum_f=0.0
print("Enter q/Q to stop entering numbers.")
while True:
a=input("Enter number: ")
try:
t= eval(a)
print(type(t))
except (NameError, ValueError):
pass
if(type(t)==int):
sum_i=sum_i+int(a)
c=c+1
elif(type(t)==float):
sum_f=sum_f+float(a)
c=c+1
elif (type(t)==str):
if (a=='q'or a=='Q'):
break
else:
print("Invalid data entered. Please enter a number to add or q/Q to quit. ")
sum= sum_i+ sum_f
print("You have entered ",c," numbers and their sum is: ",sum)
My output is supposed to provide the sum of the numbers entered on entering q, but this is what i get:
Enter q/Q to stop entering numbers.
Enter number: 3
<class 'int'>
Enter number: 5.5
<class 'float'>
Enter number: 12
<class 'int'>
Enter number: q
Traceback (most recent call last):
File "/home/netvarth/py test/sum.py", line 14, in <module>
sum_i=sum_i+int(a)
ValueError: invalid literal for int() with base 10: 'q'
Here is a refactoring using nested try/except which solves the problem somewhat more succinctly and Pythonically.
#!/usr/bin/env python3
nums = list()
while True:
# Usability tweak: Trim surrounding whitespace
a = input("Enter number: ").strip()
try:
t = int(a)
except ValueError:
try:
t = float(a)
except ValueError:
if a in ('q', 'Q'):
break
print("Invalid data entered. Please enter a number or q/Q to quit.")
continue
nums.append(t)
print("You have entered {0} numbers and their sum is {1}".format(
len(nums), sum(nums)))
two things: first to check for a type of something it is more pythonian to use
isinstance(t, int)
but the second thing is where your code fails.
If you evaluate a literal you will get most likely a name error since the variable is not defined anywhere. However if you enter 'c' for example you get something weird entirely. Since the variable c is defined you won't get a name error but it will still fail when casting the literal 'c' to int.
you could use a regular expression to check if the input is a number or not
for example like so.
if re.match('(\d+(\.\d+)?)', a):
try:
t = eval(a)
print(type(t))
except (NameError, ValueError):
pass
elif a == 'q' or a == 'Q':
break
else:
continue
if isinstance(t, int):
sum_i = sum_i + int(a)
c = c + 1
elif isinstance(t, float):
sum_f = sum_f + float(a)
c = c + 1
else:
print("Invalid data entered. Please enter a number to add or q/Q to quit. ")
Your problem is in using eval. If it cannot parse a string as a variable, it should fail, but in your case you already have a t floating around in the namespace. t keeps its old identity as, say, an int, but then you try to add a (a string) to a number.
This code should work:
sum,sum_i,c=0,0,0
sum_f=0.0
print("Enter q/Q to stop entering numbers.")
while True:
a=input("Enter number: ")
try:
t = int(a)
sum_i=sum_i+int(a)
c=c+1
print(type(t))
continue
except ValueError:
pass
try:
t = float(a)
sum_f=sum_f+int(a)
c=c+1
print(type(t))
continue
except ValueError:
pass
try:
if (a=='q'or a=='Q'):
break
else:
print("Invalid data entered. Please enter a number to add or q/Q to quit. ")
continue
except ValueError:
pass
sum= sum_i+ sum_f
print("You have entered ",c," numbers and their sum is: ",sum)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I'm trying to write a code where the program keeps getting the user input in integers and adds it to an empty array. As soon as the user enters "42", the loop stops and prints all the collected values so far.
Ex:
Input:
1
2
3
78
96
42
Output:
1 2 3 78 96
Here is my code (which isn't working as expected):
num = []
while True:
in_num = input("Enter number")
if in_num == 42:
for i in num:
print (i)
break
else:
num.append(in_num)
Here is one solution, which also catches errors when integers are not entered as inputs:
num = []
while True:
try:
in_num = int(input("Enter number"))
if in_num == 42:
for i in num:
print(i)
break
except ValueError:
print('Enter a valid number!')
continue
else:
num.append(in_num)
I think your issue is with the if condition: Input builtin function returns a string and you are comparing it with an integer.
in_num = None
num = []
while True:
in_num = input("Enter number: ")
if in_num == "42": #or you could use int(in_num)
for i in num:
print(i)
break
else:
num.append(in_num)
The problem is, that input is giving you a string and you check in line 5 for an int.
You have to replace it to if in_num == "42" or directly convert your input("Enter number") to an int using int(input("Enter number"))
Ok so I'm really new to programming. My program asks the user to enter a '3 digit number'... and I need to determine the length of the number (make sure it is no less and no more than 3 digits) at the same time I test to make sure it is an integer. This is what I have:
while True:
try:
number = int(input("Please enter a (3 digit) number: "))
except:
print('try again')
else:
break
any help is appreciated! :)
You could try something like this in your try/except clause. Modify as necessary.
number_string = input("Please enter a (3 digit) number: ")
number_int = int(number_string)
number_length = len(number_string)
if number_length == 3:
break
You could also use an assert to raise an exception if the length of the number is not 3.
try:
assert number_length == 3
except AssertionError:
print("Number Length not exactly 3")
input() returns you a string. So you can first check the length of that number, and length is not 3 then you can ask the user again. If the length is 3 then you can use that string as a number by int(). len() gives you the length of the string.
while True:
num = input('Enter a 3 digit number.')
if len(num) != 3:
print('Try again')
else:
num = int(num)
break
Keep the input in a variable before casting it into an int to check its length:
my_input = input("Please enter a (3 digit) number: ")
if len(my_input) != 3:
raise ValueError()
number = int(my_input)
Note that except: alone is a bad practice. You should target your exceptions.
while True:
inp = raw_input("Enter : ")
length = len(inp)
if(length!=3):
raise ValueError
num = int(inp)
In case you are using Python 2.x refrain from using input. Always use raw_input.
If you are using Python 3.x it is fine.
Read Here
This should do it:
while True:
try:
string = input("Please enter a (3 digit) number: ")
number = int(string)
if len(string) != 3 or any(not c.isdigit() for c in string):
raise ValueError()
except ValueError:
print('try again')
else:
break