Functions in python for beginners part - 2
Introduction
And this is the continuation of function in python part - 1
Using return
Let's see some examples that use a return statement. return allows a function to return a result that can then be stored as a variable, or used in whatever manner a user wants.
Example 3: Addition function
def add_num(num1,num2):
return num1 + num2
print(add_num(4,5))
OUTPUT
9
# Can also save as variable due to return
result = add_num(4,5)
print(result)
OUTPUT
9
What happens if we input two strings?
print(add_num('one', 'two'))
OUTPUT
'onetwo'
Note that because we don't declare variable types in Python, this function could be used to add numbers or sequences together! We'll later learn about adding in checks to make sure a user puts in the correct arguments into a function.
Let's also start using break
, continue
, and pass
statements in our code. We introduced these during the while
lecture.
Finally, let's go over a full example of creating a function to check if a number is prime (a common interview exercise).
We know a number is prime if that number is only evenly divisible by 1 and itself. Let's write our first version of the function to check all the numbers from 1 to N and perform modulo checks.
def is_prime(num):
'''
Naive method of checking for primes.
'''
for n in range(2,num):
if num % n == 0:
print(num,'is not prime')
break
else: # If never mod zero, then prime
print(num,'is prime!')
print(is_prime(16))
OUTPUT
16 is not prime
print(is_prime(17))
OUTPUT
17 is prime!
Note how the else lines up under for and not if. This is because we want the for loop to exhaust all possibilities in the range before printing our number is prime.
Also, note how we break the code after the first print statement. As soon as we determine that a number is not prime we break out of the for loop.
We can actually improve this function by only checking to the square root of the target number, and by disregarding all even numbers after checking for 2. We'll also switch to returning a boolean value to get an example of using return statements:
import math
def is_prime2(num):
'''
Better method of checking for primes.
'''
if num % 2 == 0 and num > 2:
return False
for i in range(3, int(math.sqrt(num)) + 1, 2):
if num % i == 0:
return False
return True
print(is_prime2(18))
OUTPUT
False
Why don't we have any break statements? It should be noted that as soon as a function returns something, it shuts down. A function can deliver multiple print statements, but it will only obey one return.
Great! You should now have a basic understanding of creating your own functions to save yourself from repeatedly writing code!
Post a Comment
Post a Comment
if you have any doubts, please let me know