Skip to content
Advertisement

Python Function parameters and arguments

I want to understand functions and arguments better, I’ve read and this is my implementation of what I have read.

I have 3 small functions to illustrate my point.

User input collection, grading function and main.

def score(num1: int):
    print("Please Enter Your Score: ")
    num1 = int(input())
    grade(num1)


def grade(num1: int):
    if int(num1) in range(0,30):
        print("Grade U")
    if int(num1)in range(30,40):
        print("Grade D")
    if int(num1)in range(40,60):
        print("Grade C")
    if int(num1)in range(60,80):
        print("Grade B")
    if int(num1)>79:
        print("Grade A")


def main():
    print("Hi")
    score(1)

If I run the main function without its argument (1), it results in an error looking for the argument. I know that I declared in the function that it has a parameter (as i want this as a return value) but how would I go about calling the score function without its argument??
E.G

def main()
print("hi")
score()

I imagine that functions are called without parameters and the arguments are passed into the parameters from the function definition (via user input)

Can someone provide an example as to how I could do this without needing the dummy variable (1) in the calling of the score function?

Advertisement

Answer

Here’s one way I would do it:

def score():
    print("Please Enter Your Score: ")
    num1 = int(input())
    grade(num1)


def grade(num1: int):
    if 0 <= num1 < 30:
        print("Grade U")
    elif 30 <= num1 < 40:
        print("Grade D")
    elif 40 <= num1 < 60:
        print("Grade C")
    elif 60 <= num1 < 80:
        print("Grade B")
    elif num1 >= 80:
        print("Grade A")


def main():
    print("Hi")
    score()


if __name__ == '__main__':
    main()

If you want to still be able to pass a parameter into the score function, like score(1), then you can instead assign an optional parameter to the function. Then, only read user input if num1 is not passed in to the score function.

def score(num1=None):
    if num1 is None:
        print("Please Enter Your Score: ")
        num1 = int(input())

    grade(num1)

Usage:

def main():
    print("Hi")
    score(1)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement