Class 5 ‐ Functions - Justin-Boyd/Python-Class GitHub Wiki

Introduction to Functions

Why Functions Are Needed

from random import randrange
dice = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
dice_roll = int(input("Times to roll the dice: "))
print("Rolling the dice")
for i in range(dice_roll):
dice_roll_res = randrange(1,7)
dice[dice_roll_res] += 1
print(dice)
  • Functions are necessary to prevent code from becoming difficult to understand.
  • They save the time and effort of having to write the same functional code in different parts of a program.
  • They also make code maintenance more efficient.

What Are Functions?

  • Blocks of code with reusable logic
  • Define functionality in the program.
  • Separate programs into small, readable, and manageable sections.
  • Functions are not parts of other elements in a script.
  • Methods are functions that are parts of other elements in a script.

Function Declaration

def Print_Multiple(message, times):
    for i in range(times):
        print(message)
Print_Multiple("Hello", 2)
Print_Multiple("Hi!")
  • A function must be defined first with the def keyword.
  • After def, the name of the function is provided.
  • The last part is parentheses () for optional parameters and a colon : to define the code block.

Invoking a Function

def greetings():
    name = input(“Enter your name: ”)
    print(“Greetings, {}!”.format(name))
greetings()
  • A defined function will not yet be executed by Python.
  • It must first be invoked before it can be used.
  • Functions can also accept parameters.

Default Values

def print_my_mood(mood="happy"):
    print(mood)
print_my_mood()
print_my_mood("sad")
==========================================================
"C:\Users\johnd\PycharmProjects\Python\venv\Scripts\python.exe"
"C:/Users/johnd/PycharmProjects/Python/PY-05/Default Values.py"
happy
sad
Process finished with exit code 0
  • Function parameters can include default values.
  • If no value is passed, the default value will be used.
  • If a value is passed, the default value will be overridden.

Returning Values

def Calculation(x, y):
    answer = x + y
    return answer
Result = Calculation(2, 4)
  • Functions can pass data at the end of the execution.
  • The return keyword is used to pass the values.
  • return also terminates the execution of a function.

Returning Data

def return_multiple():
    first_name = "John"
    last_name = "Doe"
    return first_name, last_name
print(return_multiple())
=========================================================================
('John', 'Doe')
Process finished with exit code 0
  • A function can return multiple values, a list, or a dictionary.
  • Each type of returned information is placed in separate parentheses.
  • Commas are used to separate the values.

Complete Function Example

from random import randrange
def main():
dice = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
dice_roll_res(dice)
def dice_rolling():
rolls = int(input("Times to roll the dice: "))
print("Rolling the dice")
return rolls
def dice_roll_res(dice):
for i in range(dice_rolling()):
roll_res = randrange(1,7)
dice[roll_res] += 1
print(dice)
main()
  • def defines a function.
  • The function name with parentheses will set the parameters.
  • return ends the execution and returns the result.

None

def first_function():
return
def second_function():
return None
def third_function():
x = 5
print(first_function())
print(second_function())
print(third_function())
=========================================================================
None
None
None
Process finished with exit code 0
  • None is not a value and refers to empty data.
  • It cannot be used in expressions but can be inserted in a variable or compared with them.
  • Every function by default returns a None value.

Code Handling

Scope

def func():
txt = "hi"
print(txt)
func()
print(txt)
=================================================================
hi
Traceback (most recent call last):
File "C:/Users/asafr/PycharmProjects/Michigan Python/PY-05/Scope.py",
line 6, in <module>
print(txt)
NameError: name 'txt' is not defined
Process finished with exit code 1
  • Scope is what defines the visibility of a variable.
  • A variable in a function is accessible only in that function.
  • There are four types of scope: local, enclosed, global, and built-in.

Global Scope


  • Global scope is the main scope of a program.
  • Variables defined in a global scope will be recognized in all other scopes as well.

Global Keyword


  • The global keyword is used to modify a global variable within a function in which a variable of the same name exist.
  • It instructs Python to use the variable from the global scope.

name Variable


  • Every Python file has the name variable.
  • It returns a different result depending on the execution state of a file.
  • The variable can be used to check if a file was imported.

proper Code Management

import random
number = random.randint(0, 5)
def main():
for i in range(number):
print("Hello")
if __name__ == '__main__':
main()
=========================================================================
Hello
Hello
Hello
Process finished with exit code 0
  • import should be at the beginning of a program.
  • Global variables should follow imports.
  • name == ‘main’ should be written at the end of the file.

Recursion

What Is Recursion?

  • Functions that call themselves
  • Provide a way of looping through data.
  • Must be handled carefully to prevent endless execution

Recursion Implementation

count = 0
def recur(count):
if count == 10:
return
print("*" * count)
count += 1
recur(count)
recur(count)
  • Recursion is implemented by having a function call itself repeatedly.
  • It should be handled carefully to prevent endless loops.

Object-Oriented Programming

What Is Object-Oriented Programming?

  • Objects are complex data types that contain attributes and functionalities.
  • They provide the flexibility of creating custom structured data.

Class

  • A class is a blueprint for an object.
  • It defines an object’s properties.
  • When a program is run, a class is the blueprint used to create objects in the system’s memory.

Defining a Class

class Car:
def __init__(self, color, window_number, price):
self.color = color
self.window_number = window_number
self.price = price
  • class is followed by the name of the class and a colon.
  • init allows the attributes of a class to be initialized for an object.
  • Class attributes and methods are accessed using self

Object Creation


  • Call the class by its name with a value corresponding to init
  • Use . to access object attributes.
⚠️ **GitHub.com Fallback** ⚠️