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"))
Related
How can we check if a user enters the value 0 multiple times in a row?
I have tried below code- here I have tried to define multiple value in list, but if the user enters 000000000 or more, I have to define till 000000000 in list is there any other way to achieve this
list = [0,00,000,0000]
num = int(input("Enter a number: "))
if num in list:
print("Zero")
elif :
print(" None ")
You need to take the input as a string. And you can check if the user has entered a string that will have all zeros in it as follows
def all_zeros(string):
return all(ch == '0' for ch in string)
This worked for me
num = input("Enter: ")
if num.count('0') > 0 and num.startswith('0'):
print("0")
else:
print("none")
Since you asked in this way
How can we check if a user enters the value 0 multiple times in a row?
But, other answers were checking whether more than one 0's are present in the string or not. I assume you want to check continuous zero's only,
num = input("Enter Number: ") # returns string
if "00" in num: #checking substring
print("Found continuous zeros")
else:
print("Entered no continous zeros!")
value = int(num) # convert it to int if needed
It doesn't matter how many zeros in the string, all these [00,000,0000,00000...] belong to the same category.
Output:
>>> num = input("Enter Number: ")
Enter Number: 0008
>>> num
'0008'
>>> "00" in num
True
>>>
num = input("Enter: ")
if num.count("0") > 1 and int(num) == 0:
print("0")
else:
print("none")
don't change num to int it will remove all the trailing zeroes
This question already has answers here:
How do I parse a string to a float or int?
(32 answers)
Closed 2 years ago.
I want to differentiate between the data types "string"&"int", if the input is "int" it will be appended, if not it will ask for correction
**no_inputs = 5
l =[]
while no_inputs >0:
user_input = int(input("Please enter a number : "))
if isinstance(user_input, int):
l.append(user_input)
no_inputs -= 1
elif isinstance(user_input, str):
print("Please enter a number only ")
print(l)**
int() raises ValueError if input is not a number. Catch this exception to print user that input is not a number.
no_inputs = 5
l =[]
while no_inputs >0:
try:
user_input = int(input("Please enter a number : "))
no_inputs -= 1
except ValueError as e:
print("Please enter a number only ")
print(l)
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I am trying to write a function to get 2 int values from a user until their sum is 21, Simple!!
The aim is to keep prompting the user to pass 2 int values until the condition is met. I am not sure where the code breaks as it stops when either conditions is met, both if true or false.
def check_for_21(n1,n2):
result = 0
while True:
while result != 21:
try:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
except:
if n1+n2 == 21:
print("You got it! ")
else:
break
break
This is what you are looking for you had multiple logical errors! However, the idea was there but wrongly formatted. In this program, it runs continuously until you enter two numbers and their sum is 21
def check_for_21():
while True:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
break
check_for_21()
Try this. This will meet your requirment.
a = 5
while (a<6):
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 == 21:
print("You got it ")
break
else:
print("You did not get to 21! ")
Take the input, check for result, if you get 21, break the loop.
def check_for_21(n1,n2):
result = 0
while True:
try:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
break
except:
pass
Below is the test result of the code that worked for me:
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
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'