Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand tuples and collections, strings and functions and exception handling in Python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to understand tuples and collections, strings and functions and exception handling in Python. The content of the article is of high quality, so the editor will share it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Tuple

Tuples are immutable sequences

In a multitasking environment, you don't need shackles to manipulate objects at the same time.

Reference to the time object stored in the tuple:

2) if the object in the tuple is a mutable object, the reference to the mutable object is not allowed to change, but the data can be changed.

Set

A collection is a sequence of mutable types

The collection does not have an value dictionary, and the stored contents are not displayed in order

The elements of the collection cannot be repeated.

String

Strings are immutable sequences

1. The resident mechanism of strings

Only one copy of the same and immutable string is saved, and different values are stored in the string resident pool. Python's resident mechanism keeps only one copy of the same string. Later, when the same string is created, it does not open up new space, but assigns the address of the string to the newly created variable.

Several situations of the resident mechanism (interactive mode):

A) A resident occurs when the length of the string is 0 or 1

B) A string that conforms to the identifier (including letters, numbers, underscores), resulting in a resident

C) the string resides only at compile time, not at run time

D) an integer number between [- 5256] that produces a resident

The intern method in sys forces two strings to point to the same object

Pycharm optimizes the string

Advantages of the residency mechanism:

A) advantages: when you need a string with the same value, you can use it directly from the string pool to avoid frequent creation and destruction, improve efficiency and save memory, so concatenating strings and modifying strings will affect performance.

B) when string concatenation is needed, it is recommended to use the join method of type str instead of +, because the length of all characters is calculated in join () mode before copying

Function 1. Advantages of the function:

(1) reuse code

(2) hide implementation details

(3) improve maintainability

(4) improve readability and facilitate debugging

2. Function creation: def function name ([input parameters])

Function body

[return xxx]

3. The parameter transfer of the function:

(1) pass the parameters when the function is called:

Position argument: the parameter is transferred according to the position of the parameter, and the position is corresponding.

For example, def fuc1 (aformab), fuc1 when calling (100.20)

Keyword argument: pass the argument according to the name of the parameter

(2) if it is an immutable object, the modification in the function body will not affect the value of the argument.

If it is a mutable object, the modification in the function body will affect the value of the argument.

4. Return value of the function:

(1) when a function returns multiple values, the result is a tuple

(2) when the function returns a value, the result is the original value.

(3) when the function does not return a value, omit return

5. Parameter definition of the function:

(1) function defines default parameters:

When the function is defined, the default value is set for the parameter, and the argument needs to be passed only if it does not match the default value.

Only one parameter is passed, and the undefined parameter has no default value.

The default parameter must be placed at the end of the other parameters that need to be passed.

Variable number of keyword parameters: using * * definition, the result is a dictionary, such as def fun1 (* * args)

If you want a function to accept different types of arguments, you must put the arguments that accept any number of arguments at the end of the function definition. Python first matches the positional argument and the keyword argument, and then collects the remaining arguments into the last parameter.

6. the area of action of the variable

Local variables: defined and used within functions. Local variables are declared using global and can be changed into global variables.

Global variables: variables defined outside the function can be used both inside and outside the function.

7. Recursive function: apply the function itself in the body of the function

(1) components of recursion: recursive invocation and recursive termination conditions

(2) Recursive calling process: every time a function is called recursively, a stack frame is allocated in the stack.

Each time the function is executed, the corresponding space is released.

(3) advantages and disadvantages of recursion: disadvantages take up a lot of memory, low efficiency; advantages, ideas and code are simple.

For example, find the hierarchy: def fuc1 (n): if nameplate 1: return 1 else: return n*fuc1 (n) print (fuc1 (10)), for example, the Fibonacci series: def fib (n): if nymphone 1: return 1 elif naughty class 2: return 2 elif: return fib (NMuk 1) + fib (NMub 2) 8, store the function in the module

Import module name

Module name. Function name ()

(2) Import specific functions: from module_name import function_0, function_1, function_2

(3) use as to assign an alias to the function: from module import original function name as new function name

(4) use as to assign an alias to the 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) name: descriptive, using only lowercase letters and underscores

(2) comments: follow the function definition

(3) formal parameters: do not have spaces on both sides of the equal sign when specifying the default value.

(4) keyword argument: no spaces on both sides of the equal sign

(5) length: each line of code had better not exceed 79 characters; if there are too many formal parameters, you can enter the left parenthesis in the function definition and press the enter key, and press the Tab key twice on the next line, thus distinguishing the formal parameter list from the function body that indents only one layer.

(6) Separation: each function is separated by two blank lines

(7) import: generally, all import are placed at the beginning of the file.

Bug

1. Common types of Bug

A. the unfamiliarity of the error points leads to

(1) the input defaults to character type, which is used for numerical calculation, comparison and so on. Solution: convert to numeric types

(2) the defined variable is not implemented in the while loop, and the variable has not changed.

(3) mixed use of Chinese and English symbols

(4) one equal sign is assigned, and two equal signs are equal to

(5) indent error

(6) forget colons: such as if statements, loop statements, else clauses, etc.

(7) when concatenating strings, put strings and numbers together.

B. Unskilled knowledge leads to

(1) Index out of bounds

(2) the append () method is not proficient, and append can only add one element at a time, only for the list.

C. Problems caused by unclear thinking

Solution: (1) print printout; (2) use comments to temporarily comment out some code

D, passive fall:

There is nothing wrong with the logic of the program code, but the program crashes because of user misactions or some exceptions.

For example:

A=int (input ('please enter an integer')) b=int (input ('please enter another integer') result=a/bprint ('result is', result) # error if an input is Q, error if b input is 0

For example:

1. Try except structure

Under try:#, the code a=int (input ('please enter an integer')) b=int (input ('please enter another integer')) result=a/b print ('result is', result) except ZeroDivisionError print ('sorry, the divisor is not allowed to be 0') print ('end of the program')

2. Multiple excep structures: the order of catching exceptions is in the order of word class followed by parent class. To avoid omitting 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/bexcept ZeroDivisionError: print ('sorry, divisor is not allowed to be 0') except ValueError: print ('cannot convert string to number') except BaseException ase: print (e)

3. Try except else structure (I don't know what will go wrong)

Try: a=int (input ('please enter an integer') b=int (input ('please enter another integer') result=a/bexcept BaseException ase: print ('error') print (e) else: print ('result', result)

4. Try except else finally structure (the finally block is executed regardless of whether an exception occurs or not, and 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/bexcept BaseException ase: print ('error') print (e) else: print ('result is', result) finally: print ('thank you for your use') print ('end of program') 3, python exception handling mechanism

Traceback module (print exception information)

Debugging of import tracebacktry: print (1stroke 0) except: traceback.print_exc () pycharm development environment

(1) Power outage

The program runs here, temporarily suspends and stops execution. At this time, you can observe the operation of the program in detail, and it is convenient to make further judgment.

(2) enter debug view

There are three ways to enter debug view:

1) Click the button on the toolbar (bug)

2) right-click the edit area: click: debug module name

3) Shortcut: shift+F9

Programming thought

(1) two kinds of programming ideas

(2) creation of classes and objects

1) Class: a general term for a group of similar things, which can help us quickly understand and judge the nature of things.

2) object: an instance or object, which can be the concrete of a class. Everything in python is an object.

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. If the rest of the lowercase pass# does not think of the composition of the # class # 1, the class attribute native_pace=' Jilin'# is directly written in the class, called class attribute # 2, instance method def eat (self): print ('students are eating...') # defined outside the class as a function Class defined in the name of method # 3, static method staticmathod def method (): print ('static method') # 4, class method classmethod def cm (cls): print ('class method') on how to understand tuples and collections in Python as well as strings and functions and exception handling is shared here, I hope the above content can be helpful to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report