简体   繁体   English

如何在 python 中仅使用一个可选参数来定义 function,如果没有给出参数则该参数接受输入

[英]how to define function with just a optional parameter in python that takes input if not given a argument

def crt_std(name=input("Enter the student name: ")): 
    std_dt={
        'name' : name,
        'marks' : []
        }
    return std_dt

def crt_std(name=None): 
    if name=None
        name=input("Enter the student name: ")
    std_dt={
        'name' : name,
        'marks' : []
        }
    return std_dt

'''In both of the functions I tried to create a dictionary with a name & number. '''在这两个函数中,我都尝试创建一个带有名称和数字的字典。 I wanted to use the functions as if I pass a argument in the name parameter it would work, and if I don't then it would ask me for a input.我想使用这些函数,就好像我在 name 参数中传递一个参数一样,它会起作用,如果我不这样做,它会要求我输入。 Ironically both of them failed miserably.具有讽刺意味的是,他们俩都惨遭失败。

Again, I dont want the function to ask for input name if I call it via function argument like crt_std(rockzxm).同样,如果我通过诸如 crt_std(rockzxm) 之类的 function 参数调用它,我不希望 function 询问输入名称。 I want the function to ask for input if i leave it blank like crt_std().我希望 function 要求输入,如果我像 crt_std() 一样将其留空。 ''' '''

It works but you forgot to add a colon and you only wrote one '=' instead of two.它可以工作,但是您忘记添加冒号,并且只写了一个“=”而不是两个。

This works:这有效:

def crt_std(name = None): 
    if name == None:
        name = input("Enter the student name: ")
    std_dt = {
        'name' : name,
        'marks' : []
        }
    return std_dt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM