输入默认为Python 3.x中的字符串即使输入数字

时间:2016-05-29 14:32:57

标签: python python-3.x

我是一个总菜鸟,所以谢谢你的耐心等待。我在程序中接受整数输入时遇到了麻烦;它们都是弦乐。我通过添加当前已注释掉的type()行来确认这一点。如何让我的程序接受整数输入?感谢。

# TIP CALCULATOR


def main():

    cost = input('Please enter the cost of your meal or service.')
    tip_percentage = input('Please enter what percentage of tip you would like to pay.')
    #print(type(cost))
    #print(type(tip_percentage))
    total = tip_percentage * cost + cost
    return total


final = main()
print(final)

2 个答案:

答案 0 :(得分:0)

您必须将字符串转换为int:

cost = int(input('Please enter the cost of your meal or service.'))

答案 1 :(得分:0)

input()函数从stdin读取输入,该输入实际上是一个文件对象并返回一个字符串。如果要以整数类型输入,可以使用int()函数将字符串数字转换为整数。但请注意,如果用户输入除数字之外的其他内容,则应使用try-except表达式对其进行包装以处理ValueError

try:
    tip_percentage = input('Please enter what percentage of tip you would like to pay.')
except ValueError: 
    tip_percentage = input('Please enter a valid digit')
else:
    # do something with tip_percentage

如果您想在用户输入有效整数之前执行此操作,您可以将前面的代码段放在条件为True的while循环中,并在else部分中打破循环。