比较数字在 Python 中给出错误的结果 [英] Comparing numbers give the wrong result in Python

查看:33
本文介绍了比较数字在 Python 中给出错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我输入任何小于 24 的值,它会打印你会变老..."语句.如果我输入任何大于 24(最多 99)的值,它会打印你老了"语句.

问题是,如果您输入 100 或更大的值,它会打印您会在不知不觉中变老".声明.

print ('你叫什么名字?')我的名字 = 输入 ()打印('你好,' + 我的名字)打印('你多大了?,'+我的名字)我的年龄 = 输入 ()如果我的年龄 >('24'):print('你老了,' + myName)别的:print('不知不觉你就老了.')

解决方案

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

if myAge >('24'):print('你老了,' + myName)

应该

if int(myAge) >24:print('你老了,{}'.format(myName))

在 Python 中,您可以对字符串进行大于/小于,但它并不像您想象的那样工作.所以如果你想测试字符串的整数表示的值,使用int(the_string)

<预><代码>>>>2">1"真的>>>02">1"错误的>>>int("02") >整数(1")真的

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

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.')

解决方案

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.

这篇关于比较数字在 Python 中给出错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆