Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

How do you input integers using input in Python

I'm trying to teach myself how to code in Python and this is my first time posting to Stack Overflow, so please excuse any improprieties in this post. But let's get right to it.

I'm trying to use the input command to return an integer. I've done my research, too, so below are my multiple attempts in Python 3.4 and the results that follow:

Attempt #1

guess_row = int(input("Guess Row: "))

I get back the following:

Traceback (most recent call last):
File "<input>", line 1, in <module> 
ValueError: invalid literal for int() with base 10: 'Guess Row: 2`

Attempt #2

guess_row = float(input("Guess Row: "))

I get back the following:

Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: could not convert string to float: "Guess Row: 2""

Attempt #3

try:
    guess_row=int(input("Guess Row: "))
except ValueError:
    print("Not an integer")

Here, I get back the following:

Guess Row: 2
Not an integer

Although it returns something, I know this is wrong because, for one, the input returns as a string and it also returns the print command.

Point being, I've tried int, float, and try, and so far nothing has worked. Any suggestions? I just want to be able to input an integer and have it returned as one.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your third attempt is correct - but what is happening to guess_row before/after this code? For example, consider the following:

a = "Hello"
try:
    a = int(input("Enter a number: "))
except ValueError:
    print("Not an integer value...")
print(str(a))

If you enter a valid number, the final line will print out the value you entered. If not, an exception will be raised (showing the error message in the except block) and a will remain unchanged, so the final line will print "Hello" instead.

You can refine this so that an invalid number will prompt the user to re-enter the value:

a = None
while a is None:
    try:
        a = int(input("Enter a number: "))
    except ValueError:
        print("Not an integer value...")
print(str(a))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...