Functions and modules in Python
Functions are packages of code that are relatively independent and reusable.
1. Modules and functions in the standard library
function | explain |
---|---|
abs | Returns the absolute value of a number. For example, abs(-1.3) will return 1.3. |
bin | Convert an integer to a binary string starting with '0b'. For example, bin(123) will return '0b1111011'. |
chr | Convert Unicode encoding into corresponding characters, for example: chr(8364) will return '€'. |
hex | Convert an integer to a hexadecimal string starting with '0x'. For example, hex(123) will return '0x7b'. |
input | Read a line from the input and return the read string. |
len | Gets the length of strings, lists, and so on. |
max | Returns the maximum value of multiple parameters or an iteratable object (which will be described later). For example, max(12, 95, 37) will return 95. |
min | Returns the minimum value of multiple parameters or an iteratable object (which will be described later). For example, min(12, 95, 37) will return 12. |
oct | Convert an integer to an octal string starting with '0o'. For example, oct(123) will return '0o173'. |
open | Open a file and return the file object (described later). |
ord | Convert the character to the corresponding Unicode encoding, for example: ord('€') will return 8364. |
pow | Exponentiation operation, for example: pow(2, 3) will return 8; pow(2, 0.5) will return 1.4142135623730951. |
Printout. | |
range | Constructing a range sequence, for example, range(100) will produce an integer sequence from 0 to 99. |
round | Round the value to the specified precision. For example, round(1.23456, 4) will return 1.2346. |
sum | Sum the items in a sequence from left to right. For example, sum(range(1, 101)) will return 5050. |
type | Returns the type of the object. For example, type(10) returns int; type('hello ') returns str. |
2. Global and local variables
Global variable: a variable that is not written in any function Local variable: a variable defined within a function python The program searches for a variable according to LEGB Search in order: Local(Local scope)-->Embeded(Nested scope)--> Global(Global scope)-->Built-in(Built in scope) global-->Declare to use a global variable or define a local variable to put it into the global scope nonlocal-->Declare variables that use nested scopes (no local variables)
3. Example - dice game
The player shakes two dice. If 7 or 11 points are shaken for the first time, the player wins; If you shake out 2 points, 3 points and 12 points, the dealer wins; If you shake out other points, the game continues and the player shakes the dice again; If the player shakes the points for the first time, the player wins; If the player shakes out 7 points, the dealer wins; If the player shakes out other points, the game continues, and the player shakes the dice again until the winner is determined.
Before the game starts, the player has an initial fund of 1000 yuan. The player can bet. If he wins, he will get the bet amount, and if he loses, he will deduct the bet amount. The condition for the end of the game is that the player loses all his money.
import random def roll_dice(num): """ Dice :param num: Number of dice :return:Shake out points """ total=0 for _ in range(num): total+=random.randrange(1,7) return total def win(): """ Player wins :return: """ global money print('Player victory') money += zhuma def lose(): global money print('Dealer victory') money -= zhuma money = 1000 while money > 0: print(f'The player's total assets are{money}element.') zhuma = 0 while zhuma <= 0 or zhuma > money: try: zhuma = int(input('Please bet: ')) except ValueError: pass first_point=roll_dice(2) print(f'The player shakes out{first_point}Point.') if first_point in (7, 11): win() elif first_point in (2, 3, 12): lose() else: while True: curr_point=roll_dice(2) print(f'The player shakes out{curr_point}spot') if curr_point==first_point: win() break elif curr_point==7: lose() break print('Player is bankrupt')
4. Example - random number selection of two-color ball
Red balls 01-33, select 6 balls that are not repeated, and arrange them from small to large
Blue ball 01-16, choose a ball and follow the red ball
import random def generate(): """ Generate a set of lottery numbers :return: """ red_ball = [i for i in range(1, 34)] blue_ball = [i for i in range(1, 17)] # No return sampling select_balls = random.sample(red_ball, 6) select_balls.sort() select_balls += random.sample(blue_ball, k=1) return select_balls def display(balls): """ Displays a set of lottery numbers :param balls: List of balls corresponding to lottery numbers :return: """ for ball in balls: print(f'{ball:0>2d}', end=' ') print() n=int(input('Notes on machine selection:')) for _ in range(n): display(generate())
5. Example - random verification code
Write a function to generate a random verification code of a specified length (composed of numbers and English letters).
After writing, 10 groups of random verification codes are generated by calling this function
import random import string def get_captcha_code(length: int=4) ->str:# : int = 4) - > STR type label """ Generate random verification code :param length: Length of verification code :return: Random verification code string """ selected_chars=random.choices(string.digits+string.ascii_letters,k=length) return ''.join(selected_chars) for _ in range(10): print(get_captcha_code())
6. Example - output prime numbers in the range of 2-100
def is_prime(num): """ Judge whether a positive integer is a prime number :param num: positive integer :return: If it is a prime number, return True,Otherwise return False """ for i in range(2,int(num**0.5)+1): if num % i==0: return False return num!=1 and True for n in range(2,100): if is_prime(n): print(n,end=' ')
7. Example - find range, mean, variance, standard deviation and median
def ptp(data): """Range (full range)""" return max(data)-min(data) def average(data): """Find the mean""" return sum(data)/len(data) def variance(data): """Find variance""" x_bar = average(data) total=0 for num in data: total+=(num-x_bar)**2 return total / (len(data)-1) def standard_deviation(data): """Find standard deviation""" return variance(data)**0.5 def median(data): """Find the median""" temp=sorted(data) size=len(temp) if size % 2 != 0: return temp[size//2] else: return average(temp[size//2-1:size//2+1])
8. Summary
-
Generally, it returns the naming of Boolean values: preceded by is
-
The ultimate principle of programming: high cohesion, low coupling. > high cohesion low coupling
The most important principle of designing functions: the principle of single responsibility (a function only does one thing well) – high cohesion -
The sort () function will disrupt the original order, while the sorted () function will not disrupt the order and returns
-
Resolve naming conflicts:
The from, import and as keywords in Python are specifically used to handle package and module import operations, and as can be used to take aliases.
(1) If you want to use the defined functions in other modules, you can first import the module through import, and then call the function through "module name. Function name ()";
(2) Another way is to import functions directly from the module – > 'from module import function name' – > call functions directly through the function name