2

我正在尝试编写一个程序(使用 Python 3.3.2),它要求输入数字然后显示一个故事:

http://postimg.org/image/ayd5n7suv/

但相反,它输出:

Traceback (most recent call last):
  File "C:\Bladibla.py", line 40, in <module>
    remaining_sweets = (int(sweets) - int(swducks)*int(ducks - 1))*int(children)
TypeError: unsupported operand type(s) for -: 'str' and 'int'

但我看不到那条线上有任何错误。为什么会这样?:

remaining_sweets = (int(sweets) - int(swducks)*int(ducks - 1))*int(children)

这是所有代码:

#Asks for number of children
children = input("How many children are there?: ")
if int(children) > 100:
    print("That number is unimaginable! Please use a smaller number.")
    children = input("How many children are there?: ")
if int(children) < 0:
    print("That number is unimaginable! Please use a larger number.")
    children = input("How many children are there?: ")

#Asks for number of sweets
sweets = input("How many sweets do they have each?: ")
if int(sweets) > 100:
    print("If they ate that number of sweets, they would die! Please use a smaller number.")
    sweets = input("How many sweets do they have each?: ")
if int(sweets) < 0:
    print("How can they have a minus number of sweets? They can't vomit the sweets!!!! Please use a larger number.")
    sweets = input("How many sweets do they have each?: ")

#Asks for number of ducks
ducks = input("How many ducks were there?: ")
if int(ducks) > 200 :
    print("That's too many ducks! Please use a smaller number!")
    ducks = input("How many ducks were there?: ")
if int(ducks) < 0:
    print("How can there be a minus number of ducks?!! Please use a larger number")
    ducks = input("How many ducks were there?: ")

#Asks for number of sweets gave to each duck
swducks = input("How many sweets did each child give to each duck?: ")
if int(swducks) > 200 :
    print("That's too many sweets given to the ducks! Please use a smaller number!")
    swducks = input("How many sweets did each child give to each duck?: ")
if int(swducks) < 0:
    print("How can there be a minus number of sweets given to the ducks?!! Please use a larger number")
    swducks = input("How many sweets did each child give to each duck?: ")

#Outputs the 'thrilling' story
print("Please wait...")
print("There were " + children + " children each with a bag containg " + sweets + " sweets. They walked past " + ducks + " ducks. Each child gave " + swducks + " sweets to each of the ducks and ate one themselves. They decided to put the rest into a pile.")
remaining_sweets = (int(sweets) - int(swducks)*int(ducks - 1))*int(children)
print("They counted the pile and found it contained " + str(remaining_sweets) + " sweets.")

提前致谢

4

1 回答 1

2

ducks是一个字符串,所以ducks - 1失败。

int在减去 1 之前,您必须将其转换为第一个:

remaining_sweets = (int(sweets) - int(swducks)*int(ducks) - 1)*int(children)
于 2013-09-26T17:32:31.030 回答