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().”’

Asked By: Neo TheOne

||

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
Answered By: Firegifguy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.