我得到错误代码:
类型错误:“str”和“int”实例之间不支持“>”
目前的状态。
问题是我不知道如何将用户输入期望从字符串格式转换为整数。
number = input ("Please guess what number I'm thinking of. HINT: it's between 1 and 30")
我已经查过如何做到这一点,但找不到我要找的东西,因为我不确定如何正确表达我的问题。
我试过把“int
" after number
之后input
但它不起作用。不知道该把它放在哪里才能让它发挥作用。
默认情况下,输入类型为string
。将其转换为integer
,只需将int
before input
. E.g.
number = int(input("Please guess what number I'm thinking of. HINT: it's between 1 and 30: "))
print(type(number))
输出示例:
Please guess what number I'm thinking of. HINT: it's between 1 and 30: 30
<class 'int'> # it shows that the input type is integer
选择
# any input is string
number = input("Please guess what number I'm thinking of. HINT: it's between 1 and 30: ")
try: # if possible, try to convert the input into integer
number = int(number)
except: # if the input couldn't be converted into integer, then do nothing
pass
print(type(number)) # see the input type after processing
输出示例:
Please guess what number I'm thinking of. HINT: it's between 1 and 30: 25 # the input is a number 25
<class 'int'> # 25 is possible to convert into integer. So, the type is integer
Please guess what number I'm thinking of. HINT: it's between 1 and 30: AAA # the input is a number AAA
<class 'str'> # AAA is impossible to convert into integer. So, the type remains string
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)