Skip to main content
 首页 » 编程设计

python之类型错误 : unsupported operand type(s) for -: 'str' and 'int' Writing a story

2024年11月01日27lyhabc

我正在尝试编写一个程序(使用 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.") 

提前致谢

请您参考如下方法:

ducks 是一个字符串,因此 ducks - 1 失败。

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

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