[Tutor] Input() is not working as expected in Python 3.1
bob gailer
bgailer at gmail.com
Mon Feb 15 16:06:42 CET 2010
Yaraslau Shanhin wrote:
> Hello All,
Hello.
Suggestion for future questions - just include enough to identify the
problem. We don't need to know that this is from a tutorial or what the
exercise is. Also (at least I prefer) plain text without formatting or
color.
Sufficient therefore is:
-------------------------------------------
using Python 3.1:
text = str(input("Type in some text: "))
number = int(input("How many times should it be printed? "))
Traceback (most recent call last):
File "test4.py", line 2, in <module>
number = int(input("How many times should it be printed? "))
ValueError: invalid literal for int() with base 10:
-------------------------------------------
Now carefully read the message "invalid literal for int()". This tells
you the argument to int is not a string representation of an integer.
There is nothing wrong with input()!
Since we don't know what you typed at the input() prompt we can't
diagnose it further. One way to solve problems like these is to capture
and print the output of input():
text = str(input("Type in some text: "))
snumber = input("How many times should it be printed?")
print snumber
A good robust alternative is to try int() and capture / report the failure:
text = str(input("Type in some text: "))
snumber = input("How many times should it be printed?")
try:
number = int(snumber)
except ValueError:
print(number, "is not an integer.")
else:
print (text * number)
--
Bob Gailer
919-636-4239
Chapel Hill NC
More information about the Tutor
mailing list