完成Python教程。我创建了一个简单的脚本(myFirstFunction),它不会执行预期的操作。 我期望一行输出只是两个变量相乘:
apples = raw_input("How many apples do you have?")
oranges = raw_input("How many oranges do you have?")
def myFirstFunction(apples, oranges):
total_fruit = apples * oranges
print total_fruit
脚本确实按预期要求输入,但不打印结果?
myName-MacBook:pythonhard me$ python ex19b.py
How many apples do you have?2
How many oranges do you have?2
myNames-MacBook:pythonhard me$
为什么不打印4?
答案 0 :(得分:6)
这里有两个问题:
您永远不会致电myFirstFunction
。这可以通过将其放在脚本的末尾来完成:
myFirstFunction(apples, oranges)
raw_input
始终返回一个字符串对象。因此,在将myFirstFunction
内的值相乘之前,需要将输入转换为整数。您可以将它们放在int
:
apples = int(raw_input("How many apples do you have?"))
oranges = int(raw_input("How many oranges do you have?"))
以下是您脚本的固定版本:
apples = int(raw_input("How many apples do you have?"))
oranges = int(raw_input("How many oranges do you have?"))
def myFirstFunction(apples, oranges):
total_fruit = apples * oranges
print total_fruit
myFirstFunction(apples, oranges)
演示:
How many apples do you have?2
How many oranges do you have?2
4
答案 1 :(得分:2)
你需要a)调用函数& b)将输入转换为整数,因为raw_input
的结果是一个字符串。
def myFirstFunction(apples, oranges):
total_fruit = int(apples) * int(oranges)
print total_fruit
apples = raw_input("How many apples do you have?")
oranges = raw_input("How many oranges do you have?")
myFirstFunction(apples, oranges)
答案 2 :(得分:2)
你应该
return total_fruit
在函数中,然后调用myFirstFunction并打印结果:
def myFirstFunction(apples, oranges):
total_fruit = apples * oranges
return total_fruit
apples = raw_input("How many apples do you have?")
oranges = raw_input("How many oranges do you have?")
print myFirstFunction(apples, oranges)
或只是调用myFirstFunction(当没有返回时):
myFirstFunction(apples, oranges)