我正在做一些功课,在下面的代码选项中,有四个遇到错误(Python 3.5)。
不能将序列乘以非int类型' float'
def main():
costpp = 20.00
numberOfPeople = input("How many people are coming to wedding?")
print("Please select a number for your choice:")
print("1) Print the invitee list")
print("2) Print the menu")
print("3) Print the text of the invitation")
print("4) Print your cost")
choice = input()
if choice == "1":
printInviteeList()
if choice == "2":
printMenu()
if choice == "3":
print("You are invited to the wedding")
if choice == "4":
printCost (numberOfPeople, costpp)
def printInviteeList():
print("Mia, Olga, Sahar, Rcheal, Ding, Gary, Jenny, Lian, Quan, Jack")
def printMenu():
print("Beef, Lamb, Bread, Egg, Crab, Cake")
def printCost(numberOfPeople, costPerPerson):
totalcost = numberOfPeople*costPerPerson
return totalcost
main()
答案 0 :(得分:3)
input()
返回一个字符串,所以在这一行之后:
numberOfPeople = input("How many people are coming to wedding?")
numberOfPeople
将是一个字符串。假设您输入了100
,numberOfPeople
将成为字符串'100'
。
将字符串乘以浮点数无效 - 这没有意义:
>>> numberOfPeople * 2.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
要解决此问题,请将numberOfPeople
转换为数字类型,在这种情况下使用int
转换为int()
:
numberOfPeople = int(input("How many people are coming to wedding?"))
>>> numberOfPeople * 2.0
200.0
值得注意的是,将字符串乘以int
:
>>> '100' * 2
'100100'
连接字符串 n 次,在本例中为2。