SoFunction
Updated on 2024-11-18

Comprehensive details on tuples collections strings functions exception handling in Python

tuple

Tuples are immutable sequences
Multitasking environments do not require shackles when operating objects simultaneously;
References to objects stored in the tuple:
1) If the object in the tuple is itself an immutable object, it can no longer reference another object;
2) If the objects in the tuple are mutable objects, the references to the mutable objects are not allowed to change, but the data can change.

在这里插入图片描述

set (mathematics)

Sets are sequences of variable types
Collections don't have value dictionaries, and the stored content is not displayed in order.
The elements of a set cannot be duplicated

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

string (computer science)

Strings are immutable sequences

1. String residency mechanism

Only one copy of the same immutable string is kept, and different values are stored in the string resident pool. python's resident mechanism keeps only one copy of the same string, and when the same string is created later, it does not open up new space, but assigns the address of the string to the newly created variable.
Several cases of resident mechanisms (interaction patterns):
a) String length of 0 or 1 produces a reside
b) Strings that match identifiers (containing letters, numbers, and underscores) that produce resident
c) Strings only reside at compile time, not runtime
d) Integer numbers between [-5, 256] that produce a residing
The intern method in sys forces 2 strings to point to the same object
String optimization by pycharm
Advantages of the residency mechanism:
a) Advantages: When you need the same value of the string, you can use it directly from the string pool to avoid frequent creation and destruction, improve efficiency and save memory, so splicing and modifying the string will affect the performance.
b) When string splicing is required, it is recommended to use the join method of type str instead of +, because the join() method calculates the lengths of all characters before copying them.

2、Commonly used operations

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

function (math.)

1. Advantages of functions:

(1) Reuse code
(2) Hide implementation details
(3) Improved maintainability
(4) Improved readability for easy debugging

2, the creation of the function: def function name ([input parameters])

function body (math.)
[return xxx]

3. Parameter passing for functions:

(1) Parameter passing at function calls:
Positional real parameters: real parameters are passed according to the position of the formal parameter corresponding to the position of the
For example def fuc1 (a, b), when called fuc1 (10, 20)
Keyword real parameter: real parameter passing based on the name of the formal parameter.
For example def fuc1 (a, b), when called fuc1 (b=10, a=20)
(2) In the case of immutable objects, modifications within the function do not affect the values of the real parameters.
In the case of mutable objects, modifications within the function affect the value of the real parameter

4. The return value of the function:

(1) When a function returns multiple values, the result is a tuple.
(2) When a function returns a value, the result is the original value
(3) Omit return when the function has no return value.

5. Definition of the parameters of the function:

(1) The function defines default value parameters:
When a function is defined, a default value is set for the formal parameter, and the real parameter needs to be passed only if it does not match the default value.
Pass only one parameter, undefined parameters have no default value.
Default value parameters Note that they must be placed at the end of other formal parameters that need to be passed real parameters.
(2) Variable number of positional arguments: defined using *, results in a tuple, e.g. def fun1 (*args)
Variable number of keyword parameters: defined using **, results in a dictionary, e.g. def fun1 (**args)
If you want a function to accept different types of real parameters, you must put the formal parameter that accepts any number of real parameters at the end of the function definition. Python matches positional and keyword real parameters first, and then collects all the remaining real parameters in the last formal parameter.

在这里插入图片描述

6. Role area of variables

Local variables: defined and used within a function, local variables are declared using global, and can be turned into global variables.
Global variables: variables defined outside the function, available both inside and outside the function.

7, recursive function: function within the application of the function itself

(1) Components of recursion: recursive calls and recursive termination conditions
(2) Recursive calling process: each recursive call to a function allocates a stack frame on the stack.
Each time a function is executed, the corresponding space is freed.
(3) Advantages and disadvantages of recursion: disadvantages take up more memory, inefficient; advantages of the idea and code is simple.

e.g. class-seeking:
def fuc1(n):
  if n==1:
    return 1
   else:
     return n*fuc1(n)
 print(fuc1(10))

For example, the Fibonacci sequence:
def fib(n):
  if n==1:
    return 1
  elif n==2:
    return 2
  elif :
    return fib(n-1)+fib(n-2)

8. Storing functions in modules

Storing functions in separate files called modules, then importing modules into the main program
(1) Importing an entire module: a module is a file with a .py extension that contains the code to be imported into the program.
import module name
Module Name. Function name ()
(2)Importing specific functions:from module_name import function_0, function_1, function_2
(3) Use as to assign an alias to a function: from module import original function name as new function name.
(4) Use as to assign an alias to a module: import original module name as new module name.
(5) Import all functions in the module: from module import *

9. Guidelines for writing functions:

(1) Names: descriptive, using only lower case letters and underlining
(2) Comments: following the function definition
(3) Formal parameter: when specifying the default value, there should be no space on either side of the equals sign.
(4) Keyword real parameter: no space on either side of the equal sign
(5) Length: Each line of code should preferably be no more than 79 characters; if there are too many formal parameters, you can enter left brackets in the function definition and press the Enter key, and press the Tab key twice on the next line, thus distinguishing the list of formal parameters from the body of the function, which is indented only one level.
(6) Separation: each function is separated by two blank lines.
(7) import: generally all import is placed at the beginning of the file

Bug

1、Common Types of Bugs

A. Unfamiliarity with the point of error leads to
(1) The input is character type by default, and numerical calculations, comparisons, etc. are performed with character type. Solution: Convert to numeric type
(2) The while loop is not realized to define the variable and the variable is not changed.
(3) Mixing of Chinese and English symbols
(4) Assignment at one equals sign, equals at two equals signs
(5) Indentation errors
(6) Forgetting the colon: if statements, loops, else clauses, etc.
(7) String splicing when splicing strings and numbers together
B. Inadequate knowledge leads to
(1) Indexing out of bounds
(2) The append() method is not proficient, append can only add one element at a time, only to lists.
C. Problems caused by unclear thinking
Solution: (1) print printout; (2) use comments to temporarily comment out part of the code
D. Passive pit fall:
There is nothing wrong with the logic of the program code, it is just that the program crashes due to user error or some exceptions.
Example:

a=int(input('Please enter an integer'))
b=int(input('Please enter another integer'))
result=a/b
print(' The result is ',result)
#Error if a is entered as q
#If b is entered as 0, an error is also reported

Solution: python provides an exception handling mechanism that allows you to catch exceptions instantly when they occur, and then digest them internally so that the program continues to run. Example:
1. try except structure

try:# Below is the code where the problem may occur
  a=int(input('Please enter an integer'))
  b=int(input('Please enter another integer'))
  result=a/b
  print(' The result is ',result)
except ZeroDivisionError
  print('Sorry, divisors are not allowed to be zero')
print('End of program')

2, multiple excep structure: the order of catching exceptions in accordance with the order of the first word class after the parent class, in order to avoid missing possible exceptions, you can add BaseException at the end. for example:

try:
  a=int(input('Please enter an integer'))
  b=int(input('Please enter another integer'))
  result=a/b
except ZeroDivisionError:
  print('Sorry, divisors are not allowed to be zero')
except ValueError:
  print('Cannot convert strings to numbers')
except BaseException as e:
  print(e)

3、try except else structure (do not know what error will come out of the case)

try:
  a=int(input('Please enter an integer'))
  b=int(input('Please enter another integer'))
  result=a/b
except BaseException as e:
   print('Something went wrong')
   print(e)
else:
   print(' The result is ',result)

4, try except else finally structure (finally block will be executed regardless of whether an exception occurs, can be used to release the resources requested in the try block)

在这里插入图片描述

try:
  a=int(input('Please enter an integer'))
  b=int(input('Please enter another integer'))
  result=a/b
except BaseException as e:
   print('Something went wrong')
   print(e)
else:
   print(' The result is ',result)
finally:
   print('Thank you for your use')
print('End of program')

2. Common types of abnormalities

在这里插入图片描述

3. python exception handling mechanism

traceback module (prints exception information)

import traceback
try:
  print(1/0)
except:
  traceback.print_exc()

Debugging pycharm development environment

(1) Power failure
The program runs up to here, temporarily hangs and stops execution. At this point, you can observe the running of the program in detail, to facilitate the making of further judgments.
(2) Enter the debugging view
Three ways to access the debug view:
1) Click the button on the toolbar (the little bug)
2) Right-click on the edit area: click: debug module name
3) Shortcut key: shift+F9

programming idea

(1) Two programming ideas

在这里插入图片描述

(2) Class and object creation

(1) Class: a collective term for a group of multiple similar things that can help us quickly understand and determine the nature of things.
2) Object: instance or object, can be a concrete of a class, everything is an object in python.
3) Create:

#Create:
class Student:         #Student is the name of the class, which can be composed of multiple words, requiring the first letter to be capitalized and the rest lowercase
  pass#Without thinking about it
# Composition of the class
#1. Class attributes
  native_pace='Jilin'# Variables written directly in the class are called class attributes
#2. Example methodology
  def eat(self):
    print('The students are eating...')# Defined outside of a class are called functions, those defined within a class are called methods
#3. Static methods
  staticmathod
  def method():
    print('Static methods')
#4. Class methods
  classmethod
  def cm(cls):
    print('Class Methods')

To this point this article on Python on tuples collections strings functions exception handling comprehensive details of the article is introduced to this, more related Python tuple content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!