我的python脚本有什么问题?不打印变量

Dou*_*Fir 2 python

完成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
Run Code Online (Sandbox Code Playgroud)

该脚本确实按预期要求输入,但不打印结果?

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$ 
Run Code Online (Sandbox Code Playgroud)

为什么不打印4?

iCo*_*dez 6

这里有两个问题:

  1. 你永远不会调用myFirstFunction.这可以通过将其放在脚本的末尾来完成:

    myFirstFunction(apples, oranges)
    
    Run Code Online (Sandbox Code Playgroud)
  2. raw_input总是返回一个字符串对象.因此,在将内部相乘之前,需要将输入转换为整数myFirstFunction.您可以将它们放入以下位置int:

    apples = int(raw_input("How many apples do you have?"))
    oranges = int(raw_input("How many oranges do you have?"))
    
    Run Code Online (Sandbox Code Playgroud)

以下是您脚本的固定版本:

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)
Run Code Online (Sandbox Code Playgroud)

演示:

How many apples do you have?2
How many oranges do you have?2
4
Run Code Online (Sandbox Code Playgroud)