比较数字会在Python中产生错误的结果

Ras*_*ian 4 python if-statement

对不起,如果这是一个可怕的问题,但我真的很喜欢编程.我正在尝试一个简短的小测试程序.

如果我输入任何小于24的值,它会打印出"你将老了......"的声明.如果我输入任何大于24的值(仅限最多99),则会打印"你是旧的"语句.

问题是如果你输入一个100或更大的值,它会打印出"在你知道之前你会老去".声明.

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.')
Run Code Online (Sandbox Code Playgroud)

syt*_*ech 6

您正在myAge针对另一个字符串值测试字符串值'24',而不是整数值.

if myAge > ('24'):
     print('You are old, ' + myName)
Run Code Online (Sandbox Code Playgroud)

应该

if int(myAge) > 24:
    print('You are old, {}'.format(myName))
Run Code Online (Sandbox Code Playgroud)

在Python中,你可以比字符串更大/更少,但它不会像你想象的那样工作.因此,如果要测试字符串的整数表示的值,请使用int(the_string)

>>> "2" > "1"
True
>>> "02" > "1"
False
>>> int("02") > int("1")
True
Run Code Online (Sandbox Code Playgroud)

你可能也注意到了,我改print('You are old, ' + myName)print('You are old, {}'.format(myName))-你应该习惯了这种风格的字符串格式化的,而不是做字符串连接用+-你可以阅读更多关于它的文档.但它确实与你的核心问题没有任何关系.