Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

if statement - Comparing numbers give the wrong result in Python

If I enter any value less than 24, it does print the "You will be old..." statement. If I enter any value greater than 24 (ONLY up to 99), it prints the "you are old" statement.

The problem is if you enter a value of 100 or greater, it prints the "You will be old before you know it." statement.

print ('What is your name?')
myName = input ()
print ('Hello, ' + myName)
print ('How old are you?, ' + myName)
myAge = input ()
if myAge > ('24'):
     print('You are old, ' + myName)
else:
     print('You will be old before you know it.')
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You're testing a string value myAge against another string value '24', as opposed to integer values.

if myAge > ('24'):
     print('You are old, ' + myName)

Should be

if int(myAge) > 24:
    print('You are old, {}'.format(myName))

In Python, you can greater-than / less-than against strings, but it doesn't work how you might think. So if you want to test the value of the integer representation of the string, use int(the_string)

>>> "2" > "1"
True
>>> "02" > "1"
False
>>> int("02") > int("1")
True

You may have also noticed that I changed print('You are old, ' + myName) to print('You are old, {}'.format(myName)) -- You should become accustomed to this style of string formatting, as opposed to doing string concatenation with + -- You can read more about it in the docs. But it really doesn't have anything to do with your core problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...