Python用户输入和打印输出

时间:2016-02-18 02:03:13

标签: python

chargePerDay = 30.0
feeEachMile = 0.5
fuelPerGallon = 1.5

print("How many users are there?")
numberOfUsers = input()

for i in range(numberOfUsers):
    print('For user ' + i)

    print("Number of days")
    numberOfDays = input()

    print("Number of miles")
    numberOfMiles = input()

    totalRentalFee = (chargePerDay * float(numberOfDays)) + (feeEachMile * float(numberOfMiles))
    print('Hi user ' + i + ' Your total rental fee is ' + str(totalRentalFee))

当我运行它时,它正在打印 for in in range(numberOfUsers): TypeError:' str' object不能解释为整数

这有什么问题?请帮忙!

4 个答案:

答案 0 :(得分:3)

您输入的内容是字符串,需要将其转换为整数:

numberOfUsers = int(input())
# ... rest of code

答案 1 :(得分:1)

input返回一个字符串。 range想要一个整数。

range(numberOfUsers)更改为range(int(numberOfUsers))

当您尝试使用整数i连接字符串时,下一行中的错误如下所示。在str(i)的调用中使用print

答案 2 :(得分:0)

转换为int

numberOfUsers = int(input())

Python 2' s input()自动评估,而Python 3则删除了2 input()并将其替换为等同于raw_input()的{​​{1}}。字符串。

答案 3 :(得分:0)

您的问题是您使用整数数据对象而不是字符串。要转换它们,请使用以下代码:

chargePerDay = 30.0
feeEachMile = 0.5
fuelPerGallon = 1.5

print("How many users are there?")
numberOfUsers = input()

for i in range(numberOfUsers):
    print('For user ' + str(i))

    print("Number of days")
    numberOfDays = input()

    print("Number of miles")
    numberOfMiles = input()

    totalRentalFee = (chargePerDay * float(numberOfDays)) + (feeEachMile * float(numberOfMiles))
    print('Hi user ' + str(i) + ' Your total rental fee is ' +     str(totalRentalFee))