在python中将输入str转换为int

时间:2019-04-27 23:54:51

标签: python math structure typeerror conventions

我得到错误代码:

  

TypeError:“>”在“ str”和“ int”的实例之间不受支持   其当前状态。

问题是我不知道如何将用户输入的期望值从字符串格式转换为整数。

number = input ("Please guess what number I'm thinking of. HINT: it's between 1 and 30")

我一直在寻找方法,但是找不到我想要的东西,因为我不确定如何正确表达我的问题。

我尝试将“ int”放在number之后和input之后,但是它不起作用。不确定将其放置在何处才能正常工作。

1 个答案:

答案 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