[Tutor] Input() is not working as expected in Python 3.1
Grigor Kolev
grigor.kolev at gmail.com
Mon Feb 15 22:02:30 CET 2010
В 10:06 -0500 на 15.02.2010 (пн), bob gailer написа:
> 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)
>
Try this:
>>>text = str(input("Type in some text: "))
Type in some text:"some text"
>>>snumber = int(input("How many times should it be printed?"))
How many times should it be printed?3
>>>print text*snumber
--
Grigor Kolev <grigor.kolev at gmail.com>
More information about the Tutor
mailing list