Functions.
This is the 2nd installment in the Python fundamentals series, and we’ll learn the very basics of Pythin’s functions.
In this post, let’s take a look at Python’s functions. We’ll only go through the very basics of it and at the end of this post, we’ll build a simple calculator.
Simple “Hello User” function:
def say_hi():
print("Hello User")
say_hi()
Output:
Hello User
Bad example:
def say_hi(name, age):
print("Hello User " + name + "" + age)
say_hi("Mike", 35)
say_hi("Steve", 70)
Output:
The sole reason why we got the error is that we directly put the int-type age in the print function. To avoid the error, we need to convert the int variable to a string type.
TypeError: can only concatenate str (not "int") to str
Fixed version:
def say_hi(name, age):
print("Hello User " + name + " " + str(age))
say_hi("Mike", 35)
say_hi("Steve", 70)
Output:
Hello User Mike 35
Hello User Steve 70
Return statement:
def cube(num):
return num*num*num
print(cube(3))
This is 3^3.
27
If statements
Sample 1:
is_male = False
if is_male:
print("You're a male")
else:
print("You're not a male")
Output:
You're not a male
Sample 2:
is_male = False
is_tall = False
if is_male and is_tall:
print("You're a tall male")
else:
print("You're neither a male nor tall")
Output:
You're neither a male nor tall
Sample 3:
is_male = True
is_tall = False
if is_male and is_tall:
print("You're a tall male")
elif is_male and not (is_tall):
print("You're a short male")
elif not (is_male) and is_tall:
print("You're not a male and are tall")
else:
print("You're neither a male nor tall")
Output:
You're a short male
If statements and comparisons:
def max_num(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(max_num(3,1,5))
Output:
5
Calculator:
Finally, let’s build a simple calculator!
num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
num2 = float(input("Enter a number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "/":
print(num1 / num2)
elif op == "*":
print(num1 * num2)
else:
print("Invalid operator")
Output:
Enter a number: 300
Enter a operator: *
Enter a number: 10
3000.0