user_input = int(input("Please enter a multiplier!"))
if user_input == int:
for multiplier in range (1,12,1): #this is where i'm kinda stuck
print multiplier, " x ", user_input, " = ", multiplier * user_input
elif user_input == str:
print "Please enter a quantitative numerical value as a multiplier, and try again, thanks!"
这就是我在做的事情: user_input = float(输入("请输入乘数!")) 乘以范围(1,13,1): 打印乘数," x",user_input," =",乘数* user_input
这是输出 1 x 9.9 = 9.9 2 x 9.9 = 19.8 3 x 9.9 = 29.7 4 x 9.9 = 39.6 5 x 9.9 = 49.5 6 x 9.9 = 59.4 7 x 9.9 = 69.3 8 x 9.9 = 79.2 9 x 9.9 = 89.1 10 x 9.9 = 99.0 11 x 9.9 = 108.9 12 x 9.9 = 118.8
#Yet if the user inputs a string (a letter) how should I convert it?
答案 0 :(得分:0)
您可以使用type
或insinstance
模块的builtin
执行此操作,例如,
if type(user_input) is int:
# your code
type
返回obect的类型。或者使用insinstance
,
if isinstance(user_input, int):
# your code
如果对象是类的实例或它的子类,则 isinstance
返回True
。
现在,在您的代码中,您已经在第一行中投射了user_input
和int
。因此,无需检查user_input
是int
还是str
。如果您输入的数字不是数字,程序也会引发错误。