Python Foundation (suitable for surprise test)

I. Basic data type 1.print output...
1.print output
2. Input
1.String type
2. List
3. Tuple
4. Assembly
5. Dictionary
6.Python data type conversion
7. = = difference from is
1. Mathematical function
2. Random number function
1.Python accesses the value in the string
2. String update
3.Python string operator
4.Python string formatting
5. Common string functions
1.list introduction
2. Update list
3. Delete list elements
4.Python list script operator
5.Python list interception and splicing
6.Python list functions & Methods
1. Introduction
2. Modify and delete tuples
3. Tuple built-in function
1. Dictionary introduction
2. Modify or delete dictionary elements
3. Characteristics of dictionary
4. Dictionary method and function
1.set introduction
2. Basic operation of collection
3. Built in method of collection
1. while loop
2. while circulates else statements
3. for loop
4. range() function
1. Function introduction
2. Anonymous function
I. Basic data type

1.print output

The default output of print is newline. If you want to realize no newline, you need to add end = "" at the end of the variable

2. Input

Input ("\ n \ npress enter to exit.")

II. Standard data type

1.String type

2. List

If the third parameter is negative, it means reverse reading

3. Tuple

string, list, and tuple all belong to sequence.

4. Assembly

Function: Test membership and delete duplicate elements.

You can use braces {} or set() function to create a set. Note: to create an empty set, you must use set() instead of {}, because {} is used to create an empty dictionary.

5. Dictionary

  1. explain
  2. example
dict = {} dict['one'] = "1 - Rookie tutorial" dict[2] = "2 - Rookie tools" tinydict = {'name': 'runoob','code':1, 'site': 'www.runoob.com'} print (dict['one']) # The output key is the value of 'one' print (dict[2]) # The output key is a value of 2 print (tinydict) # Output complete dictionary print (tinydict.keys()) # Output all keys print (tinydict.values()) # Output all values
  1. function

6.Python data type conversion

Conversion function

7. = = difference from is

Three number types and their functions

1. Mathematical function

Among the above functions, only six functions ABS (x) max () min () power () round () sqlr () are built-in, and there is no need to refer to the math.math library

2. Random number function

choice function

Description: randomly select an element from the elements of the sequence, such as random.choice(range(10)), and randomly select an integer from 0 to 9.

Lagrange function

Description: gets a random number from the set within the specified range and incremented by the specified cardinality. The default cardinality is 1

example

random function

Description: randomly generate the next real number, which is in the range of [0,1). 😄

shuffle() function

Description: sorts all elements of a sequence randomly

Four strings and functions

1.Python accesses the value in the string

Start the search from the front, and the index value starts with 0.

The search starts from the back, and the index value starts with - 1 bit.

2. String update

3.Python string operator

The more important and easy to forget here are in not in r/R

4.Python string formatting

The difference between and C language is that% is not used between the output string and the value to be filled in

python string formatting symbol:

5. Common string functions

Python 3 string | rookie tutorial (runoob.com)

See the website for details

Find() function

Description: find() detects whether the string contains and returns the position of the string. If not, it returns - 1

str.find("Hello") # Return value: 0 str.find("W") # Return value: 6. Note here that a space is also a character. There is a space in front of W, so the w position is 6 str.find("R") # Return value: - 1, not included in Hello World. If not, return - 1

index() function

Description: index() checks whether the string contains the specified characters and returns the starting index value. If it does not, an error will be reported, just like the find() method, but an exception will be reported if str is not in the string.

str.index("Hello") # Return value: 0 str.index("o") # Return value: 4 str.index("W") # Return value: 6 str.index("R") # Return value: error message, because R is not included in it. Therefore, it is recommended to use it with caution. If the value does not exist, the program will be finished with an error.

len() function

describe 🔅 len() returns the length of the string, starting with 0

len(str) #Return value: 11

count() function

describe 🔅 count() collects the number of occurrences of the specified character in the string

str.count("o") Return value: 2, o Character in Hello World There are two in the. # You can also specify the count() function to start searching from a certain location. The syntax is: count ("", start, end) str.count('o',5,10) Return value: 1, Reason: after specifying the location, the retrieval will start from index 5 and end with index 10. There is only one between 5 and 10'o' str.count('o',4,len(str)) Return value: 2. The index starts from 4 and ends at the end of the string. len(str)String length

replace() function

describe 🔅 replace() replaces the string

str.replace('hello','HELLO') # Replace lowercase HELLO with uppercase HELLO, which is not possible here str.replace('W','B') # Replace W with B 'Hello Borld' str.replace('l','a') # 'Heaao Worad' all l's become a '

The replacement here is that all the same characters are replaced

split() function

describe 🔅 split() string cutting

str.split('o') #Return ["shell", "W", "rld"] in the form of a list, and the o in hello world is cut off

upper() function

describe 🔅 Convert all characters to uppercase

str.upper() #The return value is HELLO WORLD

lower() function

describe 🔅 Converts all uppercase characters in a string to lowercase

title() function

describe 🔅 The first letter is converted to uppercase, which means that all words start with uppercase and the rest are lowercase (see istitle())

str1 = "hello word" >>> str1.title() 'Hello Word'

ceter() function

describe 🔅 The center() method returns a string centered on the specified width, fillchar is the filled character, and the default is space.

str = "[runoob]" print ("str.center(40, '*') : ", str.center(40, '*')) #Output str.center (40, '*'): ****************** [runoob]**************** str = "Hello Word" >>> str.center(30) #Output 'Hello Word'

join() function

describe 🔅 Insert a specified character after the string to construct a new string

_str="_" list=["I","Love","You"] _str.join(list) # Return value: I_Love_You insert an underscore after each list element #Output 'I_Love_You'

isspace() function

describe 🔅 Check whether the string contains only spaces. If it returns Trun, otherwise it returns False. Generally speaking, it is to judge non empty verification

str=" " strOne="good morning!" str.isspace() # Return to trun strOne.isspace #Return false

isalnum() function

describe 🔅 Check whether it contains only numbers or letters. Purpose: it can be used to judge the password. Generally, the password cannot enter Chinese characters or spaces.

strOne="a123" strTwo="a 456" strOne.isalnum() # Return to trun strTwo.isalnum() # Returns false because it contains spaces

isdigit() function

describe 🔅 Detects whether a character contains only numbers and returns True and False

str='123' strone='a123' str.isdigit() #Return to trun str.isdigit() #Return false

isalpha() function

describe 🔅 Detects whether the string contains only letters

str="abcd" strone="123abacd" str.isalpha() # Return to trun strone.isalpha() # Return false
Four lists

1.list introduction

It is worth mentioning that the left to right index starts from 0 and the index starts from - 1, which is the same as the string index

list can also intercept the required values through the same interception method as the string, such as:

nums = [10, 20, 30, 40, 50, 60, 70, 80, 90] print(nums[0:4]) #[10, 20, 30, 40] output list = ['Google', 'Runoob', "Zhihu", "Taobao", "Wiki"] # Read the second bit print ("list[1]: ", list[1]) # Intercept from the second bit (inclusive) to the penultimate bit (exclusive) print ("list[1:-2]: ", list[1:-2]) #output list[1]: Runoob #output list[1:-2]: ['Runoob', 'Zhihu']

2. Update list

list1+['hello'] #['Google', 'Runoob', 'Taobao', 'hello'] #Adding an element directly after list1 can also realize the added function

3. Delete list elements

4.Python list script operator

The operators of list pairs + and * are similar to strings. The + sign is used to combine lists and the * sign is used to repeat lists.

5.Python list interception and splicing

6.Python list functions & Methods

list(seq) function

Description: the list() method is used to convert tuples or strings into lists.

**Note: * * tuples are very similar to lists, except that the element values of tuples cannot be modified. Tuples are placed in brackets and lists are placed in square brackets.

aTuple = (123, 'Google', 'Runoob', 'Taobao') list1 = list(aTuple) print ("List element : ", list1) str="Hello World" list2=list(str) print ("List element : ", list2) #List elements: [123, 'Google', 'Runoob', 'Taobao'] #List elements: ['h ',' e ',' l ',' l ',' o ',' W ',' o ',' R ',' l ','d']

insert() method

Description: the insert() function is used to insert the specified object into the specified location of the list.

list.insert(index, obj) #grammar #Index -- the index position where the object obj needs to be inserted. #obj -- object to insert into the list.
list1 = ['Google', 'Runoob', 'Taobao'] list1.insert(1, 'Baidu') print ('After inserting elements into the list : ', list1) #After inserting elements into the list, they are: [Google ',' Baidu ',' runoob ',' Taobao ']

The above two methods are only written because they are difficult to understand. The remaining functions are easy to understand. You can see the meaning of this method tomorrow

Tuple

1. Introduction

Tuples differ from lists in that the elements of tuples cannot be modified.

When a tuple contains only one element, you need to add a comma after the element, otherwise the parentheses will be used as operators:

2. Modify and delete tuples

3. Tuple built-in function

About tuples are immutable

The immutability of tuples refers to the immutability of the contents in the memory pointed to by tuples.

>>> tup = ('r', 'u', 'n', 'o', 'o', 'b') >>> tup[0] = 'g' # Modifying elements is not supported Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> id(tup) # View memory address 4440687904 >>> tup = (1,2,3) >>> id(tup) 4441088800 # The memory address is different
Six Dictionaries

1. Dictionary introduction

2. Modify or delete dictionary elements

a. Modify and add dictionary elements

dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} dict['Age'] = 8 # Update Age dict['School'] = "Rookie tutorial" # Add information #{'name':'runoob ',' age ': 8,' class':'first ',' school ':'rookie tutorial'}

b. Delete, empty dictionary

dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} del dict['Name'] # Delete key 'Name' #{'Name': 'Runoob', 'Class': 'First'} dict.clear() # Empty dictionary #{} del dict # Delete dictionary

3. Characteristics of dictionary

4. Dictionary method and function

Built in function

Built in method

Seven sets

1.set introduction

  1. Note: to create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary.
  2. You can create a collection using braces {} or the set() function.
  3. A set is an unordered sequence of non repeating elements.
#Create format parame = #perhaps set(value)

2. Basic operation of collection

a. Add element

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-mq3bidb5-1635742603864) (C: / users / 20539 / appdata / roaming / typora user images / image-20211023161149379. PNG)]

b. Remove element

Because set is unordered, the pop() method deletes an element at random

3. Built in method of collection

a.difference_ The difference between update () and difference() methods

The difference is that the difference() method returns a new collection with the same element removed, and the difference_ The update () method directly removes elements from the original collection without returning a value.

Eight loop statement

1. while loop

General form of while statement

while Judgment conditions(condition): Execute statement(statements)......

In Python, there is no do... while loop and no switch - case statement (conditional control statement)

The following example uses while to calculate the sum of 1 to 100:

n = 100 sum = 0 counter = 1 while counter <= n: sum = sum + counter counter += 1 print("1 reach %d Sum of: %d" % (n,sum)) #The sum of 1 to 100 is 5050

2. while circulates else statements

A loop statement can have an else clause, which is executed when the loop is terminated by an exhaustive list (in a for loop) or when the condition becomes false (in a while loop), but not when the loop is terminated by a break.

When the conditional statement after while is false, the else statement block is executed.

#Syntax format while <expr>: <statement(s)> else: <additional_statement(s)>

expr if the conditional statement is true, execute the statement (s) statement block; if false, execute additional_statement(s).

example

#!/usr/bin/python3 count = 0 while count < 5: print (count, " Less than 5") count = count + 1 else: print (count, " Greater than or equal to 5") # 0 less than 5 # 1 less than 5 # 2 less than 5 # 3 less than 5 # 4 less than 5 # 5 greater than or equal to 5

3. for loop

4. range() function

If you need to traverse * * * number sequence * * *, you can use the built-in range() function. It generates a sequence of numbers, for example:

#If you need to traverse a sequence of numbers, you can use the built-in range() function. It generates a sequence of numbers, such as for i in range(5): print(i , end=" ") # 0 1 2 3 4 #You can also use range to specify the value of the interval: for i in range(5,9): print(i , end=" ") # 5 6 7 8 #You can also make the range start with a specified number and specify different increments (even negative numbers, sometimes called 'steps'): for i in range(5,19,2): print(i , end=" ") # 5 7 9 11 13 15 17 #negative for i in range(-10, -100, -30) : print(i, end=" ") # -10 -40 -70

Nine function

1. Function introduction

grammar

def Function name (parameter list): Function body

example

def hello() : print("Hello World!") hello()

Functions with a little parent-child, with parameter variables:

#Compares two numbers and returns the larger number: def max(a, b): if a > b: return a else: return b a = 4 b = 5 print(max(a, b)) # 5 # Calculate area function def area(width, height): return width * height def print_welcome(name): print("Welcome", name) print_welcome("Runoob") w = 4 h = 5 print("width =", w, " height =", h, " area =", area(w, h)) # Welcome Runoob # width = 4 height = 5 area = 20

2. Anonymous function

sum = lambda arg1,arg2:arg1+arg2 #call print("Added value:",sum(10,20)) print("Added value:",sum(10,20)) #output #The added value is: 30 The added value is : 40

1 November 2021, 00:06 | Views: 6154

Add new comment

For adding a comment, please log in
or create account

0 comments