我得到错误代码:
TypeError:“>”在“ str”和“ int”的实例之间不受支持 其当前状态。
问题是我不知道如何将用户输入的期望值从字符串格式转换为整数。
number = input ("Please guess what number I'm thinking of. HINT: it's between 1 and 30")
我一直在寻找方法,但是找不到我想要的东西,因为我不确定如何正确表达我的问题。
我尝试将“ int
”放在number
之后和input
之后,但是它不起作用。不确定将其放置在何处才能正常工作。
答案 0 :(得分:2)
默认情况下,输入类型为string
。要将其转换为integer
,只需将int
放在input
之前。例如。
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