Can you use if statements or while loops within a function? Illustrate with an example.
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')
Comments
Leave a comment