Wang Haihua
🚅 🚋😜 🚑 🚔
Functions are blocks of code that can be used over and over again to perform a specific task.
Functions can be defined to do a task, or produce an output
We have already usd some of Python's built in functions like print(), len(), sorted() etc. There are many more.
We can use these in our own code by providing access to functions defined in libraries, modules and packages. Or, we can create our own functions (user-defined).
They also mean you can implement something complex and re-use it again.
def "function_name"(parameter1,parameter2,..):
"Do something"
return "return something" (depends on functionality)
def hello():
print("Hello Everyone!!")
hello()
Hello Everyone!!
def hello(name):
print("Hello " + name)
hello("Mary")
Hello Mary
def plus_one(a):
return a+1
plus_one(5)
6
x = plus_one(8)
print("X is ", x)
X is 9
def func_in_func(name1):
hello(name1)
func_in_func("Lucy")
Hello Lucy
def func1():
print("Hello World!!")
func1()
print("Google")
func1()
func1()
func1()
func1()
Hello World!! Google Hello World!! Hello World!! Hello World!! Hello World!!
def summ(a,b):
summ = a + b
print(summ)
summ(6.0,7.5)
13.5
t = summ(8,9)
print("T is ", t)
17 T is None
def func(x,y):
summ = x + y
multip = x * y
return (summ,multip)
s, m = func(23,45)
print(s, m)
68 1035
print(func(23,45))
(68, 1035)
print("Sum of the values: " + str(t) + ", Multiplication of the values: " + str(c))
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-17-4c640f2abc2e> in <module> ----> 1 print("Sum of the values: " + str(t) + ", Multiplication of the values: " + str(c)) NameError: name 'c' is not defined
#Let's write a function that it will square the entered number, but will be terminated when you enter the number 5 and give us an error message.
def sqr(x):
if x == 5:
return ("Terminated because you entered 5")
result = x**2
return result
sqr(10)
100
sqr(5)
'Terminated because you entered 5'
d = sqr(5)
print(d)
Terminated because you entered 5
# Let's write a function that tells you whether the entered number is positive, negative or zero.
def func(x):
if x > 0:
return ("Positive")
elif x < 0:
return ("Negative")
else:
return ("Zero")
for i in [-2,5,6,0,-4,-7]:
print(func(i))
Negative Positive Positive Zero Negative Negative
#factorial calculation
#0! = 1
#1!= 1
#2!= 2 * 1 =2
#3! = 3 * 2 * 1 = 6
#6! = 6 * 5* 4 *3 * 2 *1 = 720
def factorial(num):
factorial = 1
if (num == 0 or num == 1):
print("Factorial: ", factorial)
else:
for i in range(num, 0, -1):
factorial = factorial * i
print("Factorial: ", factorial)
# 1 * 5 = 5 = factorial
# 5 * 4 = 20
# 20 * 3 = 60
#60 * 2 = 120
# 120 * 1 = 120
factorial(5)
Factorial: 120
def factorial2(num):
factorial = 1
for i in range(1,num+1):
factorial *= i #factorial = factorial * i
return factorial
factorial2(0)
1
def factorial2(num2):
factorial2 = 1
if (num2 == 0 or num2 == 1):
print("Factorial: ", factorial2)
else:
for i in range(factorial2, num2+1):
factorial2 *= i
print("Factorial: ", factorial2)
factorial2(6)
Factorial: 720
def factorial3(nums):
factorial3 = 1
if (nums == 0 or nums == 1):
return factorial3
else:
for i in range(factorial3, nums+1):
factorial3 *= i
return (factorial3)
x = factorial3(0)
print(x)
1
x
1
def hello2(name, capLetter = False):
if capLetter:
print("Hello " + name.upper())
else:
print("Hello " + name)
hello2("hasan")
Hello hasan
hello2("hasan", capLetter = True)
Hello HASAN
#lambda function
(lambda x: x + 1)(5)
6
my_lambda = lambda x: x + 1
my_lambda(5)
6
full_name = lambda first, last: 'Full name: ' + first.title() + ' ' + last.title()
full_name('guido', 'van rossum')
'Full name: Guido Van Rossum'
def multp(*args):
result = 1
for i in args:
result *= i #result = result * i
print(result)
return result
# *args keeps the data as tuple type.
multp(4,5,6,7,8,9)
4 20 120 840 6720 60480
60480
multp([2,3,5], 2)
[2, 3, 5] [2, 3, 5, 2, 3, 5]
[2, 3, 5, 2, 3, 5]
multp(2,3,4,0)
2 6 24 0
0
[4,5,6] * 3
[4, 5, 6, 4, 5, 6, 4, 5, 6]
def exponentiate(base, exponent):
print("Base: ", base, " Exponent: ", exponent)
return base ** exponent
exponentiate(exponent = 2, base = 5)
Base: 5 Exponent: 2
25
def func_kwargs(**kwargs):
print("Their name is " + kwargs["name"] + " " + kwargs["lname"] + " and they are " + str(kwargs["age"]) + " years old.")
func_kwargs(name = "Hasan", lname = "Istanbul", age=25, gender = "M")
Their name is Hasan Istanbul and they are 25 years old.
At a particular company, employees’ salaries are raised progressively, calculated using the following formula:
salary = salary + salary x (raise percentage)
Raises are predefined as given below, according to the current salary of the worker. For instance, if the worker’s current salary is less than or equal to 1000 TL, then its salary is increased 15%.
Range | Percentage |
---|---|
0 < salary ≤ 1000 | 15% |
1000 < salary ≤ 2000 | 10% |
2000 < salary ≤ 3000 | 5% |
3000 < salary | 2.5% |
Write a program that asks the user to enter his/her salary. Then your program should calculate and print the raised salary of the user.
Some example program runs:
Please enter your salary: 1000
Your raised salary is 1150.0.
Please enter your salary: 2500
Your raised salary is 2625.0.
def salaryCalc(salary):
if salary <= 0:
return("Invalid value")
else:
if 0 < salary <= 1000:
salary = salary + salary * 0.15
elif salary <= 2000:
salary = salary + salary * 0.1
elif salary <= 3000:
salary = salary + salary * 0.05
else:
salary = salary + salary * 0.025
return ("New salary: " + str(salary))
salaryCalc(-5)
'Invalid value'
salaryCalc(800)
'New salary: 920.0'
def salaryCalc2():
salary = float(input("Please enter your current salary: "))
if salary <= 0:
return("Your salary is impossible...")
else:
if 0 < salary <= 1000:
salary = salary + salary * 0.15
elif salary <= 2000:
salary = salary + salary * 0.1
elif salary <= 3000:
salary = salary + salary * 0.05
else:
salary = salary + salary * 0.025
return ("New salary: " + str(salary))
new_salary = salaryCalc2()
print(new_salary)
Please enter your current salary: 2000 New salary: 2200.0
import numpy
import tensorflow as tf
import myModules
myModules.myFunc()
from myModules import *
myFunc()
words = ["artificial","intelligence","machine","learning","python","programming"]
#from random import *
import random as rnd
def randomWord(words):
index = rnd.randint(0, len(words)-1)
return words[index]
len(words)
6
word = randomWord(words)
print(word)
programming
x = 5
print(x)
5
def display():
x = 4
return(x)
display()
4
print(x)
5
my_var = 5
def my_func():
my_var = 2
print("my var is ", my_var, " in the function")
my_func()
print("my var is ", my_var, " globally")
my var is 2 in the function my var is 5 globally
Functions are a block of code that carry out a specific task, and they are called by name. They may contain arguments too.
They may also return something, or not. If they return something, their returned value can be assigned to a variable or used elsewhere.
Methods are somewhat similar to functions, although they are associated with objects/classes. They are used for an object for which it is called, such as a String or List.
Like functions, methods are also called by name
object.methodName(parameter)
s = input("Please enter a name: ")
print(s.upper())
Please enter a name: john JOHN
#it does not return any value
list1 = [1,2,3,4,5,6]
list1.remove(4)
list1
[1, 2, 3, 5, 6]
list1
[1, 2, 3, 5, 6]
list1.index(6)
4
#return the index of the element with the highest value in a given list.
myList = [45,7,23,6,12,78]
maxElement = max(myList)
maxIndex = myList.index(maxElement)
print(maxIndex)
5