Learn python from scratch - Notes in every corner 2 - functions and Debug

Posted by jasonbullard on Wed, 02 Feb 2022 14:12:29 +0100

1. Function

DRY principle - Don't Repeat Yourself


def math(x):  # Define function name and parameters
    y = 3*x + 5  # Function body
    return y  # return
# Function name: 1 The name should best reflect the function of the function, which is generally combined with lowercase letters, single underscores, numbers, etc
#      2. It cannot have the same name as the built-in function (the built-in function can be used directly without definition)
def math(x):
# Parameters: according to the function, there can be multiple parameters in parentheses or no parameters. The naming rules are the same as the function name
# Specification: brackets are English brackets, and the colon behind them cannot be lost
    y = 3*x + 5
# Function body: the execution process of the function, and the statement reflecting the function of the function should be indented, usually four spaces
    return y
# Return statement: multiple data types can be followed. If the function does not need to return a value, it can be omitted

Common parameter types in functions:
Position parameter, default parameter, variable length parameter

def opening():
    print('There is always a smell that can warm you~')
    print('The late night canteen officially opened!')
    print('Welcome from all over the world to taste!')

opening()

For functions without a return statement, Python will implicitly add return None at the end, that is, return the value of None.

The default parameter must be placed after the position parameter. However, the default parameter does not mean that it cannot be changed

def  menu(appetizer, course, dessert = 'mung bean paste'):
    print('One appetizer:' + appetizer)
    print('One staple food:' + course)
    print('One dessert:' + dessert)

menu('Plum and peanut','Hand-Pulled Noodle Soup with Beef')
#Because 'mung bean paste' has been passed to dessert by default, there is no need to pass it when calling.
def menu(appetizer, course, dessert = 'mung bean paste'):
    print('One appetizer:' + appetizer)
    print('One staple food:' + course)
    print('One dessert:' + dessert)

menu('Plum and peanut','Hand-Pulled Noodle Soup with Beef')
menu('Plum and peanut','Hand-Pulled Noodle Soup with Beef','Tremella soup')
#Corresponding parameter dessert of tremella soup

Variable length parameter: the quantity passed to the parameter is optional and uncertain.
Its format is special. It is an asterisk * plus the parameter name. Its return value is also special. It is a tuple.

def menu(*barbeque):
    return barbeque

order = menu('Roast chicken wings','Eggplant ','Roasted corn')
#These values in parentheses are passed to the parameter barbeque

print(order)  # ('roasted chicken wings',' roasted eggplant ',' roasted corn ')
print(type(order))   # <class 'tuple'>

The tuple is written by putting data in parentheses (). Its usage is similar to that of the list. The main difference is that the elements in the list can be modified at any time, but the elements in the tuple cannot be changed.
Complete parameters of print() function:

print(*objects, sep = ' ', end = '\n', file = sys.stdout, flush = False)

Function can not only input multiple parameters, but also output multiple values at the same time. You need to write the returned value after the return statement and separate it with English commas.

import random 
appetizer = ['Plum and peanut','Cucumber ','Three Kinds of Cold Mixed Vegetables']
def coupon(money):
    if money < 5:
        a = random.choice(appetizer)
        return a
    elif 5 <= money < 10:
        b = random.choice (appetizer)
        return b, 'Loose egg'

result = coupon(6)
# result is a tuple
print(result[0])  # Extract elements from tuples
print(result[1])  # Extract elements from tuples

Another way: we can also define multiple variables at the same time to receive multiple elements in tuples:

dish, egg = coupon (7)
# The two elements of the tuple are assigned to the variables dish and egg respectively
print(dish)
print(egg)

2. Coordination of multiple functions

When multiple functions run at the same time, it involves a very important concept in the function - variable scope:
(1) A variable assigned inside a function can only be used inside the function (local scope). They are called [local variables], such as variable in cost() function_ cost.
icon
(2) Variables assigned outside all functions can be used anywhere in the program (global scope). They are called [global variables], such as rent in the first line.

rent = 3000

def cost():
    utilities = int(input('Please enter the water and electricity cost of this month'))
    food_cost = int(input('Please enter the cost of ingredients for this month'))
    variable_cost = utilities + food_cost
    print('The variable cost of this month is' + str(variable_cost))

def sum_cost():
    sum = rent + variable_cost
    print('The total cost of this month is' + str(sum))

cost()
sum_cost() 
  # There will be an error when running -- NameError: name 'variable_cost' is not defined


terms of settlement:
(1) Trick: put local variables outside the function and become global variables.
(2) Global statement: the global statement is usually written on the first line of the function body. It will tell Python, "I hope variable_cost is a global variable, so please don't create a local variable with this name".

3. Function nesting

The code block behind the def statement just encapsulates the function of the function. If it is not called, the code behind the def statement will never be executed.

index() function:
Used to find the index position of the first occurrence of an element in the list.
Syntax: list Index (obj), obj is the abbreviation of object.

format:
%s means to format an object as a character

Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".
If you use int Instead of a string, use%d instead of%s. 
"My name is %s and i'm %d" % ('john', 12) #My name is john and i'm 12

Guessing game:

# case 8 guessing game

import random

# punches 
punches = ['stone','scissors','cloth']
computer_choice = random.choice(punches)
user_choice = ''
user_choice = input('Please punch: (stone, scissors, cloth)')  # Please enter your choice
while user_choice not in punches:  # When the user enters an error, an error will be prompted and re-enter
    print('Input error, please punch again:')
    user_choice = input()

# Bright fist
print('--Combat process————')
print('There is something wrong with the computer:%s' % computer_choice)
print('What happened to you:%s' % user_choice)

# Victory or defeat
print('--—Results -————')
if user_choice == computer_choice:  # Conditional judgment using if
    print('it ends in a draw!')
# There are three choices for computers. The index positions are: 0 stone, 1 scissors and 2 cloth.
# Suppose you subtract 1 from the computer index position, corresponding to: - 1 cloth, 0 stone, 1 scissors, all win.
elif user_choice == punches[punches.index(computer_choice)-1]:
    print('You win!')
else:
    print('You lost!')

3. Debug

Four situations: carelessness; Unskilled knowledge; Unclear thinking; Passive pit dropping
bug1 careless:

(1) ^ represents the location where the bug occurred.
(2) Syntax error: syntax error
(3) = and==

bug2 - unskilled knowledge:
When you find that you can't remember the knowledge points clearly or can't be sure, you should review or search online in time. Don't force yourself to write code you're not sure about, which is often error prone. If you are not proficient in the usage of append(), check the correct usage online first:

a = []
a.append('A')
a.append('B')
a.append('C')
print(a)

bug3 - unclear thinking:


bug4 - passive pit drop:
(1) "ValueError": "pass in invalid parameter" - solution: type() function
(2) Exception handling mechanism: use the try... except... Statement to catch the exception immediately when it occurs, and then digest it internally.

while True:
    try:
        age = int(input('How old are you?'))
        break
    except ValueError:
        print('What you entered is not a number!')

if age < 18:
    print('You can't drink')
num = [1,2,0,3]
for x in num:
    try:
    #Try the following code
        print (6/x)
        #Divide 6 by the elements in num and print
    except ZeroDivisionError:
    #Unless ZeroDivisionError reports an error, execute the following code:
        print('0 You can't do divisor!')
        #Print "0 cannot be divisor!"

For all error types of Python, please refer to the following address:
https://www.runoob.com/python/python-exceptions.html

Topics: Python