Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Here I am trying to get an input from the user which is added to a list, then the list must be validated before I run it through another function. I know that I need to change something for the comparative to work: can only be used with integers and the input in the list will be a string. Also there is an error that says "unorderable types: str() > int(). How do I get around this ?
def strInput():
string = []
string = str(input("Please enter numbers from 1-999... "))
if validate(string):
return string
else:
strInput()
def validate(i):
if i > 0 and i <= 999:
return True
else:
strInput()
I suppose you want to collect a list of numbers. The code below will do the trick
def validate(userInput):
return userInput.isdigit() and int(userInput) > 0 and int(userInput) <= 999
def getListOfNumbers():
listOfNumbers = []
while True:
userInput = raw_input("Please enter a number from 1 to 999. Enter 0 to finish input: ")
if userInput == '0':
return listOfNumbers
elif validate(userInput):
listOfNumbers.append(int(userInput))
#optional
else:
continue
myList = getListOfNumbers()
print myList
it should be: either do this:
if int(i) > 0 and int(i) <= 999:
if you in python 3 input takes input as string
or do this:
string = int(input("Please enter numbers from 1-999... "))
I hope it helps
def validate(i):
try:
num = int(i)
except:
return False
return num > 0 and num <= 999
def strInput():
string = str(input("Please enter numbers from 1-999... "))
if validate(string):
return string
else:
return strInput()
strings = []
strings.append(strInput())
strings.append(strInput())
print (strings)
prints out
Please enter numbers from 1-999... 1
Please enter numbers from 1-999... a
Please enter numbers from 1-999... 2
['1', '2']
You just need to convert the string into a integer. Try:
def validate(i):
if i.isdigit() and int(i) > 0 and int(i) <= 999:
return True
else:
strInput()
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 14 days ago.
Improve this question
n = [1,2,3,4,5,6]
while True:
num = (input("enter your choice(from 1 to 6) "))
if num not in str(n) or num.isdigit == "False":
print("enter valid chice ")
os.system('cls')
pr()
else:
break
I want it to loop if the input is string and not in n
n = [1,2,3,4,5,6]
while True:
num = input("enter your choice(from 1 to 6) ")
if not num.isdigit() or int(num) not in n:
print("enter a valid choice ")
else:
break
The issue in the original code was checking isdigit as a string instead of calling the method on num. Also, the condition to check if num is not in n was incorrect. The corrected code checks if num is not a digit and also checks if the integer form of num is not in n.
Your code is convoluted, here's a simpler version:
# use try/except to get an int, or set our var outside the bounds in the while loop
try:
num = int(input("Enter your number (1-6):"))
except ValueError:
num = 0
# while our input isn't in the 1-6 range, ask for a number
while num not in [1,2,3,4,5,6]:
# same as before, if this is not a number, just set it to something that's not in [1-6] so we stay in the while loop
try:
num = int(input("Enter a valid choice please (1-6):"))
except ValueError:
num = 0
# your code here
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Write a function to enter from the keyboard a series of numbers between 1 and 20 and save them in a list.In case of entering an out-of-range value the program will display an error message and ask for a new number.To finish loading you must enter -1.La function does not receive any parameters, and returns the loaded list (or empty, if the user did not enter anything) as the return value.
def funcion():
list = []
num = 0
while num != -1:
num = int(input("Enter a number between 1 and 20: "))
while num > 20 :
num = int(input("Please re-enter the number: "))
list.append(num)
return lista
result = funcion()
print(result)
My question is how I do not show the -1 in the list
It's easier to have an infinite loop and break out of it when the user enters -1:
def funcion():
lista = []
num = 0
while True:
num = int(input("Enter a number between 1 and 20: "))
while num > 20:
num = int(input("Please re-enter the number: "))
if num == -1:
break
else:
lista.append(num)
return lista
result = funcion()
print(result)
The trick is saving the list except the last item like this:
return lista[:-1]
you can read more here:
https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/
The minimal change to your code would just use the list slicing syntax to return all elements of lista apart from the last one:
return lista[:-1]
See [1] below. This is a pythonic way of writing the slightly more intuitive, but more verbose statement:
return lista[:len(lista)-1]
... which in turn is short for the even longer:
return lista[0:len(lista)-1]
You seem to be new to python. I really recommend looking up "list slicing" and "list comprehensions": if you already know a programming language that doesn't have these, once you learn these, you'll wonder how you ever did without them!
[1] http://knowledgehills.com/python/negative-indexing-slicing-stepping-comparing-lists.htm
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"))
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
My code is just this :
x = int(input("Enter a number: "))
y = int(input("Enter a second number: "))
print('The sum of ', x, ' and ', y, ' is ', x+y, '.', sep='')
I get this error when i enter any number :
Enter a number:15
Enter a second number: Traceback (most recent call last):
File "C:/Users/mgt4/PycharmProjects/Beamy/test.py", line 5, in <module>
y = int(input("Enter a second number: "))
ValueError: invalid literal for int() with base 10: ''
I understand that it thinks the second number entered is a space but I don't know why and how i can fix this.
int(input("whatever")) will indeed raise a ValueError if input() returns something that can not be interpreted as an int. As a general rule, you should never trust user inputs (wherever they come from - input(), command line arguments, sys.stdin, text files, HTTP request, whatever) and always sanitize and validate them.
For your use case, you want a wrapper function around the int(input(...)) call:
def asknum(q):
while True:
raw = input(q)
try:
return int(raw.strip())
except ValueError:
print("'{}' is not a valid integer".format(raw)
num1 = asknum("enter an integer")
You could make it a bit more generic by providing a validation function instead:
def ask(q, validate):
while True:
raw = input(q)
try:
return validate(raw.strip())
except ValueError as e:
print(e)
And in this case you can simply use the int type as validation function:
num1 = ask("enter an integer", int)
Try to transform your code more generic:
REPEATS = 2
counter = 1
values = []
while True:
value = raw_input("Enter number {}: ".format(counter))
try:
number = int(value)
except ValueError:
print("Entered value '{}' isn't a number".format(value))
continue
counter += 1
values.append(number)
if counter > REPEATS:
break
print('The sum of values {} is {}'.format(", ".join([str(v) for v in values]), sum(values)))
Where REPEATS will be number of added values.
Example of output:
Enter number 1: 56
Enter number 2: 88
The sum of values 56, 88 is 144
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am trying to insert user input into a list until the user enters '0'. Right now, it won't exit out of the while loop once I enter 0.
Here's my code:
num_array = []
inputnum = raw_input('Please enter a number: ')
num_array.append(inputnum)
while inputnum != 0:
inputnum = raw_input('Please enter a number: ')
num_array.append(inputnum)
for i in range(len(num_array) - 1):
print(num_array[i] + ' + ')
print(num_array[total - 1] + ' = ' + sum(num_array))
Try check:
num_array = []
# raw_input return value as string,int convert it to string.
inputnum = int(raw_input('Please enter a number: '))
num_array.append(inputnum)
# earlier check for string '0' to interger 0 so the condition returned true but now int() converted inputnum to integer.
while inputnum != 0:
inputnum = int(raw_input('Please enter a number: '))
num_array.append(inputnum)
for i in range(len(num_array) - 1):
print("%d +" % num_array[i])
# sum() gave exception because earlier num_array had string type but int() converted all the value to integer.
print("%d = %d" % (num_array[len(num_array) - 1],sum(num_array)))
Try using
while inputnum != '0':
because the raw_input function returns a string, not integer. However, if your input_num needs to be an integer then follow the above solution.