Python简单数字比较 [英] Python simple number comparison
问题描述
问题:
计算机随机生成一个数字。用户输入一个数字,计算机会告诉你是否太高或太低。
我的解决方案:
code> import random
computer = random.randint(1,500)
def guessNumber():
user = raw_input('> )
while user!= computer:
如果用户>计算机:
print你的数字太大
user = raw_input('>')
else:
printNaa!too small。Try a bit higher number
user = raw_input('>')
print现在的数字是相等的
$ b b
不幸的是,我的代码从不运行通过if语句,甚至有它总是打印你的数字太大,即使我输入'1'为用户。
raw_input()
返回一个字符串值。首先将其转为整数:
user = int(raw_input('>'))
由于Python 2会在字符串之前对数字进行排序,因此, user&计算机
测试将始终返回True,无论输入什么:
> ''> 0
True
Python 3改正此问题:
>>> ''> 0
回溯(最近一次调用):
在< module>中的文件< stdin>
TypeError:unorderable types:str()>请注意,如果用户没有输入有效的数字, int()
会抛出 ValueError
: >>>> int('42')
42
>>>> int('fortytwo')
回溯(最近最后一次调用):
在< module>中的文件< stdin&
ValueError:无效的文字int()with base 10:'fortytwo'
想要明确处理:
def askForNumber():
while True:
try:
return int(raw_input('>'))
(ValueError除外):
print不是数字,请重试
def guessNumber :
user = askForNumber()
while user!= computer:
如果用户>计算机:
print您的号码太大
user = askForNumber()
else:
printNaa!too small。Try a bit higher number
user = askForNumber()
print现在数字相等
The problem:
The computer randomly generates a number. The user inputs a number, and the computer will tell you if you are too high, or too low. Then you will get to keep guessing until you guess the number.
My solution:
import random
computer = random.randint(1, 500)
def guessNumber():
user = raw_input('> ')
while user != computer:
if user > computer:
print "Your number is too big"
user = raw_input('> ')
else:
print "Naa! too small. Try a bit higher number"
user = raw_input('> ')
print "Now the numbers are equal"
Unfortunately, my code never run pass the if statement and even with that that it always prints "Your number is too big" even if I enter '1' for user.
解决方案 raw_input()
returns a string value. Turn it into an integer first:
user = int(raw_input('> '))
Since Python 2 sorts numbers before strings, always, your user > computer
test will always return True, no matter what was entered:
>>> '' > 0
True
Python 3 rectifies this:
>>> '' > 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
Note that if the user does not enter a valid number, int()
will throw a ValueError
:
>>> int('42')
42
>>> int('fortytwo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'fortytwo'
You may want to explicitly handle that:
def askForNumber():
while True:
try:
return int(raw_input('> '))
except ValueError:
print "Not a number, please try again"
def guessNumber():
user = askForNumber()
while user != computer:
if user > computer:
print "Your number is too big"
user = askForNumber()
else:
print "Naa! too small. Try a bit higher number"
user = askForNumber()
print "Now the numbers are equal"
这篇关于Python简单数字比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!