We provide effective and economically affordable training courses for R and Python, Click here for more details and course registration !

A function in Python is a group of code statements wrapped together to perform specific tasks. After a function is defined, then it can be called by passing real values to its arguments and get the returning results. A while loop in Python is a group of conditional statements bundled in a statement beginning with keyword ‘while’, and the codes will run forever until the condition returns false. By including a user-defined function inside a while loop in Python, many iterative tasks can be fulfilled. The following code example shows the creation of a function and be called within a while loop:

#to define function combining to names to get a fullname 
def full_name(f_name, l_name):
    """Return a formatted full name."""
    full_name = f_name + ' ' + l_name
    return full_name.upper()

#while loop, and calling function full_name() inside the loop
while True:
    print("\nPlease input your name:")
    print("(enter 'quit' if you want to stop)")
    
    f_name = input("Your First name: ")    
    l_name = input("Your Last name: ")      
    format_name = full_name(f_name, l_name)
    print("\nYour full name is: " + format_name + "!")

But the above while has a shortcoming: it will never stop. Because the statement ‘while True’ will always be true, unless there are some mechanisms inside the loop to make the looping stop.

In the following code example, ‘if’ conditional test and ‘break’ are added. If the user input ‘quit’ at anytime, then the while loop is stopped.

#if-break conditional test added into while loop
while True:
    print("\nPlease input your name:")
    print("(enter 'quit' if you want to stop)")
    
    f_name = input("Your First name: ")
    if f_name == 'quit':
        break
    l_name = input("Your Last name: ")
    if l_name == 'quit':
        break
    format_name = full_name(f_name, l_name)
    print("\nYour full name is: " + format_name + "!")


###User input and program output:
Please input your name:
(enter 'quit' if you want to stop)
Your First name: Wilson
Your Last name: Zh

Your full name is: Wilson Zh!

Please input your name:
(enter 'quit' if you want to stop)
Your First name: Shirley
Your Last name: Yu

Your full name is: Shirley Yu!

Please input your name:
(enter 'quit' if you want to stop)
Your First name: quit

You can also watch video on YouTube to get more illuminating understanding of using while-loop and function in Python.


0 Comments

Leave a Reply

Avatar placeholder