为什么我的函数跳过If语句?

时间:2015-07-03 10:11:02

标签: python if-statement function

它接受输入ok,但不会继续if语句。我可以不在函数参数中定义变量吗?

def maximum(one = int(input("Enter first Number: ")),
            two = int(input("Enter second Number: "))):  
    if one > two:  
        return one  

    else:  
        return two


maximum()

3 个答案:

答案 0 :(得分:1)

你可以定义变量"在参数列表中。问题是表达式只在声明函数时被评估一次。

举一个例子,在这个交互式(IPython!)会话中,我宣布了两个函数。请注意"做某事"只打印一次,就像我宣布test()

一样
In [86]: def something():
   ....:     print "Doing something"
   ....:     return 10
   ....: 

In [87]: def test(x=something()):
   ....:     print "x is %s" % x
   ....:     
Doing something

In [88]: test()
x is 10

In [89]: test()
x is 10

由于上述原因,以下模式对于Python中的默认参数很常见,尝试在函数中使用它。

def foo(arg=None):
    if arg is None:
        arg = "default value" # In your case int(input(...))

答案 1 :(得分:0)

不要以这种方式使用默认参数的值。他们在创建函数期间只评估过一次。因此,您的函数将始终接收与第一次接收数据相同的输入。

答案 2 :(得分:0)

参数的默认值在执行它们所属的def语句时进行评估(即仅在定义函数时执行它们。)

当调用它们所属的函数时,不会重新计算它们。

示例 -

>>> def hello(one = print("Hello")):
...     print("Bye")
...
Hello
>>> hello()
Bye
>>>