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

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

问题描述

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



如果我输入任何小于24的值,它会打印出你将老了......的声明。如果我输入任何大于24的值(最多99个),它会打印你老了的声明。



问题是如果输入值100或者更大,它​​打印出在你知道它之前你会老去。声明。

  print('你的名字是什么?')
myName = input()
print ('你好,'+ myName)
打印('你多大了?,'+ myName)
myAge = input()
如果myAge> ('24'):
打印('你老了,'+ myName)
else:
print('你知道之前你会老了。')


解决方案

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

 如果myAge> ('24'):
打印('你老了,'+ myName)

应该是

 如果int(myAge)> 24:
打印('你老了,{}'。格式(myName))

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

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

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


sorry if this is a terrible question, but I am really new to programming. I am attempting a short little test program.

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天全站免登陆