Python basic syntax

Keywords: Python

catalogue

1, Variable

1.1 function of variables

1.2 variable definition of Python

2, Data type

3, Output

3.1 format output

3.2. Built in function format

3.3. f- format string

3.4. Truth!

3.5 escape character and terminator

4, Input

4.1 grammar

4.2 characteristics

5, Convert data type

6, Operator

7, Conditional statement

7.1 introduction

7.2 if statement

7.3. if statement instance

  7.4 ternary operator

8, Circulation

8.1 function

8.2,while

8.3,for

8.4 break and continue

8.5. Cycle... else

9, String

9.1 introduction

9.2 subscript

9.3 slicing

9.4 common operation methods

9.4.1 search

9.4.2 modification

9.4.3 judgment

10, List

10.1 introduction

10.2. Add, delete, modify and check the list!

10.2.1 search

10.2.2. Add

10.2.3 deletion

10.2.4 modification

10.2.5 reproduction

11, Tuple

11.1 definitions

11.2. Query

11.3 precautions

12, Dictionary

12.1. Syntax of creating dictionary

12.2. Addition, deletion, modification and query

12.2.1. Add & modify

12.2.2 deletion

12.2.3 query

12.3 loop traversal

13, Assemble

13.1. Create

13.2. Addition, deletion and query

13.2.1 query

13.2.2. Add

13.2.3 deletion

14, Public operation

14.1 operator

14.1.1. Merge (+), which can be used for strings, lists and tuples

14.1.2 copy (*), which can be used for string, list and tuple

14.1.3 whether the element exists (in, not in), which can be used for string, list, tuple and dictionary

14.2 public methods

14.2.1,range(start, end, step)

14.2.2,enumerate()

14.3 container type conversion

14.3.1,list()

14.3.2,tuple()

14.3.3,set()

1, Variable

1.1 function of variables

In short, it is to set aside a space in the memory space and take a meaningful name to store specific data. It's like setting aside a room at home called the study for books.

1.2 variable definition of Python

Fixed format: variable name on the left and value on the right.

Variable name = value

1.2.1 identifier naming rules

The variable name shall conform to the naming rules of the identifier, which specifies the composition like a micro signal. In short:

  • Alphanumeric underline
  • Cannot start with a number
  • Built in keywords cannot be used
  • Case sensitive

1.2.2 naming habits

Big hump: MyName

Small hump: myName

Underline: my_name

2, Data type

One day we visited a friend's house. There was a room in a mess. We asked, "what kind of room is this?", and the friend said: "(< class' sundry room)", laughing ~.

Method for detecting data type: type (variable name or value)

-- integer
a = 1
print(type(a))  # <class 'int'> 
-- float 
b = 1.1
print(type(b))  # <class 'float'> 
-- Boolean
c = True
print(type(c))  # <class 'bool'> 
-- character string
d = "12345"
print(type(d))  # <class 'str'> 
-- list
e = [10, 20, 30]
print(type(e))  # <class 'list'> 
-- tuple
f = (10, 20, 30)
print(type(f))  # <class 'tuple'> 
-- aggregate
h = {10, 20, 30}
print(type(h))  # <class 'set'> 
-- Dictionaries
g = {"name": "Arthur", "age": 35}
print(type(g))  # <class 'dict'> 

Why does Python have so many data types?

Adapt to different variables and make rational use of memory.

Don't be too wild at home (dog head). The gym, cloakroom and garden are not complete.

Python is a weak voice type, and the data type doesn't need programmers to care much!!!

3, Output

3.1 format output

I don't know what the formatted output is. Let's put it another way. Placeholders are symbols used after occupying this position. Ha ha, they are similar to the library's substitute board.

SymboltransformationSymboltransformation
%S (common)character string%xHexadecimal integer (lowercase ox)
%D (common)Signed decimal integer%XHexadecimal integer (uppercase OX)
%F (common)Floating point number%eScientific counting (lowercase e)
%ccharacter%EScientific counting (capital E)
%uUnsigned decimal integer%g%Abbreviations for f and% e
%oOctal integer%G%Abbreviations for f and% E

%03d represents the minimum number of display digits of an integer. If it is insufficient, it is filled with 0. For example, 1 is displayed as 001, and 1111 is displayed as 1111.%. 2f represents the decimal reserved digits of floating-point type, and 3.1415926 is displayed as 3.14.

name = "Yao"
age = 16
weight = 45
student_id = 1

# My name is Yao
print('My name is%s' % name)

# My student number is 0001
print('My student number is%04d' % student_id)

# My weight is 45.00 kg
print('My weight is%.2f kg .' % weight)

# My name is Yao. I'm 16 years old
print('My name is%s,this year%d Years old' % (name, age))

# My name is Yao. I will be 17 next year
print('My name is%s,next year%d Years old' % (name, age + 1))

3.2. Built in function format

For string formatting, the function is super powerful. It is a super placeholder, ha ha.

The format is: str.format(), which is not limited to parameter format and does not require position. It's good to correspond one by one.

# My name is Yao. I will be 17 next year
print('My name is{0}, next year{1}Years old'.format(name, age+1))

# My name is yunzhongjun. I'm 20 years old
print('My name is{0}, this year{1}Years old'.format("Yun Zhongjun", 20))

3.3. f- format string

Well, it's hard to explain, but it's really a way to format strings. It'll be simpler, more readable, and faster. The format is: f '{expression}'

# My name is Yao. I will be 17 next year
print(f'My name is{name}, next year{age + 1}Years old')

3.4. Truth!

In fact, the essence of string output is to splice strings. In fact, it is OK to use% s. anyway... Integer or floating-point should be converted into strings.

3.5 escape character and terminator

  • \n: Line feed
  • \t: Tab
  • In fact, python will add a print ('content ', end="\n") by default at the end of print(), but we can change it ourselves

4, Input

4.1 grammar

input("prompt information")

4.2 characteristics

  • When the program is executed to input, it can continue to execute downward only after the user's input is completed
  • General input content is stored in variables for easy use
  • The input data received by input will be processed as a string

5, Convert data type

Hu Luwa: "the content entered by the user is not kneaded by dough!".

Bring it to you! I want floating point! Ha ha

functionexplainfunctionexplain
int(x)Convert x to integerlist(s)Convert sequence s to list
float(x)Convert x to floating pointchr(x)Converts an integer to Unicode characters
str(x)Convert x to stringord(x)Converts a character to ASCII characters
repr(x)Convert x to an expression stringhex(x)Converts an integer to a hexadecimal string
eval(str)

Converts the data in a string to the native type of a Python expression

oct(x)Converts an integer to an octal string
tuple(s)Convert sequence s to tuplebin(x)Converts an integer to a binary string

6, Operator

7, Conditional statement

7.1 introduction

Python conditional statements are code blocks that determine the execution result (True or False) of one or more statements.

In other words, the conditions are met.

7.2 if statement

if Judgment conditions:
    Execute statement
elif Judgment conditions:
    Execute statement
else: 
    Execute statement
    

7.3. if statement instance

# __anthor: XU CHEN
# date: 2021/9/18

import random
import sys

print("Welcome to the stone scissors paper game")
userName = input("Please enter your game name:")


def Game(inNum, comNum):
    if inNum == comNum:
        print(f'The machine is out of order{comNum},it ends in a draw!')
    elif (inNum==0 and comNum==2) or (inNum-comNum==1):
        print(f'The machine is out of order{comNum},You win!')
    else:
        print(f'The machine is out of order{comNum},You lost')
    res = input('Again, please enter X,To exit, press any key')
    if res == 'X' or res == 'x':
        return
    else:
        sys.exit(0)


while True:
    stats = input(f'welcome{userName}Come to this game and start game input Y,Launch game input N: ')
    if stats == 'Y' or stats == 'y':
        print('The game begins!')
        print('Stone input 0, scissors input 1, cloth input 2')
        inNum = int(input("Please punch"))
        if inNum == 0 or inNum == 1 or inNum == 2:
            comNum = random.randint(0, 2)
            Game(inNum, comNum)
        else:
            print('Incorrect input')
    elif stats == 'N' or stats == 'n':
        print('game over!')
        sys.exit(0)
    else:
        print("Please re-enter as required!")

  7.4 ternary operator

exp1 if contion else exp2

max = a if a>b else b

8, Circulation

8.1 function

Improve the reuse rate of code, like a reusable environmental bag, cheap and environmentally friendly, hey hey

8.2,while

while conditional expression:
    Code block

8.3,for

for iteration variable in string | list | tuple | dictionary | set:
    Code block

8.4 break and continue

break and continue are two different ways to exit a loop when certain conditions are met.

break ends the loop, and continue skips the current loop.

8.5. Cycle... else

Execute else only after the normal end of the loop. Oh, the break end does not belong to.

while condition:
    Code executed repeatedly when the condition is true
else:
    Code to be executed after the loop ends normally

9, String

9.1 introduction

String is the most commonly used data type in Python. We usually use quotation marks to create strings. Creating a string is as simple as assigning a value to a variable.

The three quotation mark string supports line feed. If you need to use quotation marks in quotation marks, you need to use escape characters

9.2 subscript

Also called "index", it is the seat number of each character in the string.

name = "abcdef"

print(name[1])
print(name[0])
print(name[2])

The output is: b a c (python starts from 0)

9.3 slicing

Slicing refers to the operation of intercepting part of the operated object. String, list and tuple all support slicing operation

sequence[Start position subscript:End position subscript:step]

It's like cutting potato chips. Where to cut from, how thick each piece is. Potato chips are delicious only when they are thin! Step - 1 means reverse order. And the ending subscript - 1 means the last character. If they are empty, it means step 1 from beginning to end.

9.4 common operation methods

9.4.1 search

It is usually to find the location of the target substring or the number of times it returns.

String sequence.find(Substring, Start position subscript, End position subscript)

  Check whether a substring is included in the string. If the subscript is at the beginning of the substring, otherwise - 1 is returned. Both the start and end subscripts can be omitted, indicating that they are searched in the whole string sequence.

String sequence.index(Substring, Start position subscript, End position subscript)

The difference from find is that if no substring is found, an exception is reported

  • rfind(): the same function as find(), but the search direction starts from the right.
  • rindex(): the same function as index(), but the search direction starts from the right.
  • count(): returns the number of times a substring appears in the string.
String sequence.count(Substring, Start position subscript, End position subscript)

9.4.2 modification

String sequence.replace(Old substring, New substring, Replacement times)

  Data can be divided into variable type and immutable type according to whether it can be modified directly. When modifying string type data, the original string cannot be changed, and the type that cannot modify data directly is immutable type.

String sequence.split(Split character, num)

Num indicates the number of times the split character appears. The number of data to be returned is num+1. If the split character is a substring in the original string, the substring will be lost after segmentation.

Concatenation character or substring.join(A sequence of multiple strings)

capitalize(): converts the first character of a string to uppercase.

title(): converts the first letter of each word in the string to uppercase.

lower(): converts uppercase to lowercase in a string.

lstrip(): delete the blank character at the left of the string.

rstrip(): deletes the white space character to the right of the string.

strip(): delete the blank characters on both sides of the string.

ljust(): returns a new string that is left aligned with the original string and filled to the corresponding length with the specified character (default space).

rjust(): returns a right aligned original string and fills it with a new string of corresponding length with the specified character (default space). The syntax is the same as ljust().

center(): returns a new string centered on the original string and filled with the specified character (default space) to the corresponding length. The syntax is the same as ljust().

9.4.3 judgment

The so-called judgment is to judge whether it is True or False. The returned result is Boolean data type: True or False.

String sequence.startswith(Substring, Start position subscript, End position subscript)

Startswitch(): checks whether the string starts with the specified substring. If yes, it returns True; otherwise, it returns False. If the start and end position subscripts are set, it checks within the specified range.

String sequence.endswith(Substring, Start position subscript, End position subscript)

Endswitch():: checks whether the string ends with the specified substring. If yes, it returns True, otherwise it returns False. If the start and end position subscripts are set, it checks within the specified range.

isalpha(): returns True if the string has at least one character and all characters are letters; otherwise, returns False.

isdigit(): returns True if the string contains only numbers; otherwise, returns False

isalnum(): returns True if the string has at least one character and all characters are letters or numbers; otherwise, returns False

isspace(): returns True if the string contains only white space; otherwise, returns False.

10, List

10.1 introduction

The format of the list is [data 1, data 2, data 3,...], and the list can store multiple different types of data in order at one time.

10.2. Add, delete, modify and check the list!

10.2.1 search

Method 1: according to the subscript index data, it is actually the same as looking up the string.

name_list[0]

Method 2: use the function to check the number or length of positions

index() check the location. If you can't find it, you will report an error

List sequence.index(data, Start position subscript, End position subscript)

count() number

name_list.count('Lily')

len() number length

len(name_list)

You can use in and not in to judge whether there is a problem

10.2.2. Add

Method 1: append() append a data to the end of the list.

However, using append() to add data will change the list into a variable data type.

If the appended data is a sequence, append() will put the sequence as a data in the original list.

List sequence.append(data)

Method 2. extend() appends a data to the end of the list

Unlike append(), if the appended data is a sequence, extend() will add the data to the original list one by one.

List sequence.extend(data)

Method 3. insert() adds data at the specified location

Unlike append() and extend(), insert can specify the new location, so the method parameter needs to specify the insertion location.

If the new data is a sequence, insert() and append() will package the insertion.

List sequence.insert(Position subscript, data)

10.2.3 deletion

Method 1. Del, del can delete not only the list elements, but also the list directly

By the way, did you find that there are no parentheses after del, ha ha, because it is a keyword rather than a built-in method

del target
del myList[2]

Method 2. pop(), delete the data of the specified subscript.

pop() has a default value and a return value. The default is the last one and returns the deleted data.

List sequence.pop(subscript)

Method 3. remove(), remove the first matching item of a data in the list

It's like using index() to find out the subscript according to the data, and then deleting the data according to the subscript del.

So if not, it will report an error!

List sequence.remove(data)

Method 4: clear() to clear the list

name_list.clear()

10.2.4 modification

a) It is the most convenient way to modify the data of a single location.

b) Reverse / reverse: reverse()

c) Sorting: sort(), you can change the positive and negative through the parameter, reverse = False, ascending (default)

List sequence.sort( key=None, reverse=False)

10.2.5 reproduction

copy(), the list after copy and the original list point to different addresses in memory even if the data is the same.

11, Tuple

Tuple cannot be modified! Tuple cannot be modified! Tuple cannot be modified!

Tuple cannot be modified! Tuple cannot be modified! Tuple cannot be modified!

Tuple cannot be modified! Tuple cannot be modified! Tuple cannot be modified!

11.1 definitions

List definitions are in brackets, and tuple definitions are in parentheses ()

If the tuple data has only one data A, add A comma!

But if not, the tuple data type is the data type of data A!

t2 = (10,)
print(type(t2))  # tuple

t3 = (20)
print(type(t3))  # int

11.2. Query

What did we say in the first sentence? you 're right! Tuples cannot be modified. Naturally, they cannot be added, modified or deleted.

Tuples can only be queried.

Method 1: index the data according to the subscript, which is the same as the string and list methods

Method 2: index(). Check the subscript according to the data. If there is no subscript, an error will be reported. The syntax and string list are the same

Method 3: count(), count the number of occurrences of data

Method 4: len(), count the number of tuple data

11.3 precautions

  1. Tuple cannot be modified! An error will be reported if you modify it!
  2. Although tuples cannot be modified, if there is a list in a tuple, the data in the list in the tuple can be modified
tuple2 = (10, 20, ['aa', 'bb', 'cc'], 50, 30)
print(tuple2[2])  # Access to list

# Results: (10, 20, ['aaaaa ',' BB ',' CC '], 50, 30)
tuple2[2][0] = 'aaaaa'
print(tuple2)

12, Dictionary

The data structure of a dictionary is a key value pair. Disorder! Variable!

12.1. Syntax of creating dictionary

The list is [], the tuple is (), and the dictionary is {}

# There is a data dictionary
dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'}
# Empty dictionary
dict2 = {}
dict3 = dict()

By the way, what is the key value pair? The colon is preceded by a key and followed by a value

12.2. Addition, deletion, modification and query

12.2.1. Add & modify

Syntax: dictionary sequence [key] = value

If the key already exists, it will be re assigned. If it does not exist, this key value pair will be added.

dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'}

dict1['name'] = 'Rose'
# Results: {name ':'rose', 'age': 20, 'gender':'male '}
print(dict1)

12.2.2 deletion

Method 1. del/del(): del can delete the specified key value pair (the key and value are deleted together!), or directly delete the dictionary.

dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'}

del dict1['gender']
# Result: {name ':'Tom','age ': 20}
print(dict1)

Method 2. Clear (): clear the dictionary. Dictionary sequence. clear()

12.2.3 query

Method 1: press the key to check the value, and no error will be reported!

dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'}
print(dict1['name'])  # Tom
print(dict1['id'])  # report errors

Method 2: get()

Dictionary sequence.get(key, Default value)

If the key does not exist, the default value will be returned (the default value is None)

dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'}
print(dict1.get('name'))  # Tom
print(dict1.get('id', 110))  # 110
print(dict1.get('id'))  # None

Method 3. keys() to query all the keys in the dictionary

dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'}
print(dict1.keys())  # dict_keys(['name', 'age', 'gender'])

Method 4. values(), query all the values in the dictionary

dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'}
print(dict1.values())  # dict_values(['Tom', 20,' male '])

Method 5. items(), query each key value pair

dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'}
print(dict1.items())  # dict_ Items ([('name ',' Tom '), ('age', 20), ('gender ',' male ')])

12.3 loop traversal

Dictionary traversal of key, value and items can be done by using the query method and using for in()

But traversing key value pairs:

dict1 = {'name': 'Tom', 'age': 20, 'gender': 'male'}
for key, value in dict1.items():
    print(f'{key} = {value}')

13, Assemble

Set has certainty, disorder and de duplication.

13.1. Create

Set {} can be used to create a set, or {} can be used like a dictionary. If the key value pair is in the big bracket, it is a dictionary. If it is a single element, it is a set. If the big bracket is empty, then this is an empty dictionary, not an empty collection! Only set() can be used to create an empty collection.

The collection can be de duplicated! The collection is out of order, which means that the index cannot be indexed!

13.2. Addition, deletion and query

Why didn't you change it? Because the change is meaningless, you can delete it if you don't need it, and you can add it if you need a new one!

13.2.1 query

In and not in to judge whether the data is in the set

13.2.2. Add

Method 1. add() is used to add a single element. If it already exists, it will not be operated.

s1 = {10, 20}
s1.add(100)
s1.add(10)
print(s1)  # {100, 10, 20}

Method 2. update() is used to add sequences (add them one by one instead of packaging them directly)

s1 = {10, 20}
# s1.update(100)  # report errors
s1.update([100, 200])
s1.update('abc')
print(s1)   # {'a', 100, 200, 10, 'b', 'c', 20}

13.2.3 deletion

Method 1: remove() deletes the specified data

Collection. remove()

Method 2: discard() deletes the specified data

Collection. remove()

Method 3. pop() randomly a data and returns

Collection. pop()

14, Public operation

14.1 operator

14.1.1. Merge (+), which can be used for strings, lists and tuples

# 1. String 
str1 = 'aa'
str2 = 'bb'
str3 = str1 + str2
print(str3)  # aabb


# 2. List 
list1 = [1, 2]
list2 = [10, 20]
list3 = list1 + list2
print(list3)  # [1, 2, 10, 20]

# 3. Tuple 
t1 = (1, 2)
t2 = (10, 20)
t3 = t1 + t2
print(t3)  # (10, 20, 100, 200)

14.1.2 copy (*), which can be used for string, list and tuple

# 1. String
print('-' * 10)  # ----------

# 2. List
list1 = ['hello']
print(list1 * 4)  # ['hello', 'hello', 'hello', 'hello']

# 3. Tuple
t1 = ('world',)
print(t1 * 4)  # ('world', 'world', 'world', 'world')

14.1.3 whether the element exists (in, not in), which can be used for string, list, tuple and dictionary

# 1. String
print('a' in 'abcd')  # True
print('a' not in 'abcd')  # False

# 2. List
list1 = ['a', 'b', 'c', 'd']
print('a' in list1)  # True
print('a' not in list1)  # False

# 3. Tuple
t1 = ('a', 'b', 'c', 'd')
print('aa' in t1)  # False
print('aa' not in t1)  # True

14.2 public methods

14.2.1,range(start, end, step)

Generate a number from start to end in step for the for loop.

range is left surround!!!

# 1 3 5 7 9
for i in range(1, 10, 2):
    print(i)

14.2.2,enumerate()

enumerate(Traversable object, start=0)

The function is used to combine a traversable data object (such as list, tuple or string) into an index sequence, and list data and data subscripts at the same time. It is generally used in the for loop. The start parameter is used to set the starting value of the subscript of the traversed data, which is 0 by default.

list1 = ['a', 'b', 'c', 'd', 'e']

for i in enumerate(list1):
    print(i)

for index, char in enumerate(list1, start=1):
    print(f'The subscript is{index}, The corresponding character is{char}')

14.3 container type conversion

What? What is a container? Containers can hold elements of different data types... Data types!

What? What are the container types? Strings, lists, tuples, dictionaries and collections are all

14.3.1,list()

Function: convert a sequence into a list

When a string is converted to a list, each character in the string is treated as an element of the list

Collections, tuples, and dictionaries can all be converted to list types, but dictionaries retain only the keys in the dictionary

# n = {'name':'zhangsan','age':20}
# res = list(n)
# print(n,type(n),res,type(res))

14.3.2,tuple()

Function: convert a sequence into tuples

# n = {'name':'zhangsan','age':20}
# res = tuple(n)
# print(n,type(n),res,type(res))

14.3.3,set()

Function: convert a sequence into a set.

# n = {'a':1,'b':2}
# res = set(n)
# print(n,type(n),res,type(res))

Posted by the_loser on Mon, 20 Sep 2021 21:29:02 -0700