How to get input where a newline exists in Python [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I want to receive input where there is a newline in Python.
I want to input a number and I have implemented the following code, but I get the following error
Code
string = []
while True:
input_str = int(input(">"))
if input_str == '':
break
else:
string.append(input_str)
Error
ValueError: invalid literal for int() with base 10: ''
line error
>1
>2
>3
>
Traceback (most recent call last):
File "2750.py", line 4, in <module>
input_str = int(input(">"))
ValueError: invalid literal for int() with base 10: ''

try isdigit function of string, see below example:
string = []
while True:
input_str = input(">")
if input_str.isdigit():
input_str = int(input_str)
if input_str == '':
break
else:
string.append(input_str)

I would suggest a try-except approach:
strList = []
while True:
try:
strList.append(int(input('Enter the number > ')))
except ValueError:
print ('Invalid number. Please try again!')
break
print(strList)
OUTPUT:
Enter the number > 1
Enter the number > 2
Enter the number > 3
Enter the number >
Invalid number. Please try again!
[1, 2, 3]

Related

Can't convert string to integer under while loop in python [duplicate]

This question already has answers here:
ValueError: invalid literal for int() with base 10: ''
(15 answers)
Closed 2 years ago.
I'm new to python. In this code, I'm trying to ask for numbers repeatedly. When the user enters 0, the program print the average of the numbers exclude 0. I can get the average from this code. However, there's a ValueError,
y = int(input())
ValueError: invalid literal for int() with base 10: ''
I don't understand why this error happens. Is it because of convert variable type under while loop? Can anyone help? Thanks!!
nums=0
i=0
x = int(input())
while x>0:
y = int(input())
i = i + 1
nums = y + nums
if y == 0:
avg = (nums+x)/(i)
print("The average of those numbers is {:.2f}.".format(avg))
This error occurs when you try to input a string of characters, instead of numbers.
E.g:
if you input '', 'string' - These won't work
but if you input '9', '239412' - This will work
It is likely the line y = int(input()) is receiving a string from the user input .
See this example.
>>> while True:
... y = int(input())
... print "Y=",y
...
12
Y= 12
0
Y= 0
"this"
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'this'
Like #Blade said you should give numbers as input. You can do this:
nums=0
i=0
try:
x = int(input())
while x>0:
try:
y = int(input())
i = i + 1
nums = y + nums
if y == 0:
avg = (nums+x)/(i)
print("The average of those numbers is {:.2f}.".format(avg))
except:
print("Input is not a number")
except:
print("Input is not a number")
You got the Value Error because you entered a space( "") which considered as a string but the input should be an integer int
For calculating the average of two numbers you can use this simple code instead : -
def average(x, y):
" Returns the average of two numbers "
return (x+y)/2
x = int(input("Enter a number:\n"))
y = int(input("Enter another number :\n"))
print(average(x, y))

Can´t convert string to integer in python

I´m getting this error while trying to convert string to integer:
Traceback (most recent call last):
File "main.py", line 9, in <module>
n = int(input())
ValueError: invalid literal for int() with base 10: 'python3 main.py'
This is the code:
n = int(input())
if num>0:
cantPos = cantPos+1
You're probably not realizing that the interpreter is prompting you for input. The input() function takes a string argument which will be the prompt. The common pattern to do here is something like:
n = None
while n is None:
try:
n = int(input('Please enter an integer: '))
except ValueError:
print('That was not an integer!')

How to make a raw input a number? [duplicate]

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'

Python Traceback error in while loop after error handling

I have created a program in Python 3.4.1 that;
asks for a whole number,
verifies that it is a whole number,
throws an error message and asks for the number to be re-input if not a whole number,
once the number is verified adds it to a list,
ends if -1 is input.
mylist = []
def checkint(number):
try:
number = int(number)
except:
print ("Input not accepted, please only enter whole numbers.")
number = input("Enter a whole number. Input -1 to end: ")
checkint(number)
number = input("Enter a whole number. Input -1 to end: ")
checkint(number)
while int(number) != -1:
mylist.append(number)
number = input("Enter a whole number. Input -1 to end: ")
checkint(number)
This all works fine, except in one scenario. If a non-whole number is input e.g. p (which gives an error message) followed by -1 to end the program, I get this message:
Traceback (most recent call last):
File "C:/Users/************/Documents/python/ws3q4.py", line 15, in <module>
while int(number) != -1:
ValueError: invalid literal for int() with base 10: 'p'
I don't understand why this is happening, as the input of p should never get as far as
while int(number) != -1:
Here is a minimal example to illustrate the issue:
>>> def change(x):
x = 2
print x
>>> x = 1
>>> change(x)
2 # x inside change
>>> x
1 # is not the same as x outside
You need to fix the function to return something, and assign that to number in the outer scope:
def checkint(number):
try:
return int(number) # return in base case
except:
print ("Input not accepted, please only enter whole numbers.")
number = input("Enter a whole number. Input -1 to end: ")
return checkint(number) # and recursive case
number = input("Enter a whole number. Input -1 to end: ")
number = checkint(number) # assign result back to number
Also, it is better to do this iteratively rather than recursively - see e.g. Asking the user for input until they give a valid response.

How do I check if raw input is integer in python 2.7?

Is there a method that I can use to check if a raw_input is an integer?
I found this method after researching in the web:
print isinstance(raw_input("number: ")), int)
but when I run it and input 4 for example, I get FALSE.
I'm kind of new to python, any help would be appreciated.
isinstance(raw_input("number: ")), int) always yields False because raw_input return string object as a result.
Use try: int(...) ... except ValueError:
number = raw_input("number: ")
try:
int(number)
except ValueError:
print False
else:
print True
or use str.isdigit:
print raw_input("number: ").isdigit()
NOTE The second one yields False for -4 because it contains non-digits character. Use the second one if you want digits only.
UPDATE As J.F. Sebastian pointed out, str.isdigit is locale-dependent (Windows). It might return True even int() would raise ValueError for the input.
>>> import locale
>>> locale.getpreferredencoding()
'cp1252'
>>> '\xb2'.isdigit() # SUPERSCRIPT TWO
False
>>> locale.setlocale(locale.LC_ALL, 'Danish')
'Danish_Denmark.1252'
>>> '\xb2'.isdigit()
True
>>> int('\xb2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '\xb2'
You can do it this way:
try:
val = int(raw_input("number: "))
except ValueError:
# not an integer
Try this method .isdigit(), see example below.
user_input = raw_input()
if user_input.isdigit():
print "That is a number."
else:
print "That is not a number."
If you require the input to remain digit for further use, you can add something like:
new_variable = int(user_input)
here is my solution
`x =raw_input('Enter a number or a word: ')
y = x.isdigit()
if (y == False):
for i in range(len(x)):
print('I'),
else:
for i in range(int(x)):
print('I'),
`
def checker():
inputt = raw_input("how many u want to check?")
try:
return int(inputt)
except ValueError:
print "Error!, pls enter int!"
return checker()

Categories

Resources