Answer to Question #310160 in Python for sung jin woo

Question #310160

Can you use if statements or while loops within a function? Illustrate with an example.


1
Expert's answer
2022-03-15T12:46:03-0400

Yes, it is possible. There are two examples of functions. The first one uses a while loop, while the second uses the if statement:


def num_digits(n):
    """Calculate number of digits in an integer n
    """
    num = 0
    while n != 0:
        n //= 10
        num += 1
    return num


def check_num(n):
    """Check whether a number is odd or even and print the result
    """
    if n%2 == 0:
        print(n, 'is an even number')
    else:
        print(n, 'is an odd number')

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS