how to define function with just a optional parameter in python that takes input if not given a argument
Question:
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. 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). I want the function to ask for input if i leave it blank like crt_std().”’
Answers:
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
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. 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). I want the function to ask for input if i leave it blank like 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