python basic syntax

Posted by tckephart on Fri, 04 Mar 2022 11:32:42 +0100

python basic syntax

Section 1 Introduction to development environment installation

1, Computer composition

[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-5yyrpni6-1618656212448) (C: \ users \ administrator \ appdata \ roaming \ typora \ user images \ image-20210415091101436. PNG)]

CPU: Processing data
 In memory: CPU Data to process
 Hard disk: a place where data is stored permanently

2, Introduction to python

1. Why python is popular

Easy to learn
 Free and open source
 Wide range of applications: web Development, crawler, data analysis, artificial intelligence, machine learning, automated testing, automated operation and maintenance

Note: well known framework

[the external chain image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-0tfud3q0-1618656212451) (C: \ users \ administrator \ appdata \ roaming \ typora \ user images \ image-20210415092224072. PNG)]

2. python version

be based on python3.5 edition
 Course to 3.7 Version explanation

3. Download and install python

Download website: https://www.python.org/downloads/windows/

Installation: fool installation

Test: press cmd+r to enter the command line operation, enter python, and press enter to display the version number

Note: if you install multiple versions of python, you can rename different versions of the Python interpreter. For example, python2 (version of python2.X), python3 (version of python3.X)

3, PyCharm

1. The role of pycharm

It is an integrated development environment with functions of intelligent prompt, syntax highlighting, code jump, debugging code, interpretation code, framework and library...
Download community version

2. Download and install

Download website: https://www.jetbrains.com/pycharm/download/#section=windows

Check:

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-vpgmwsdw-1618656212454) (C: \ users \ administrator \ appdata \ roaming \ typora \ typora user images \ image-20210415101416067. PNG)]

3. pycharm basic usage

New project:

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ftxao22a-1618656212460) (C: \ users \ administrator \ appdata \ roaming \ typora \ typora user images \ image-20210415102633768. PNG)]

Create a new file and write code

[the external link image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-7txwvdj2-1618656212464) (C: \ users \ administrator \ appdata \ roaming \ typora \ typora user images \ image-20210415103547132. PNG)]

Run file

Right click run

[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-exra1wey-1618656212465) (C: \ users \ administrator \ appdata \ roaming \ typora \ typora user images \ image-20210415103629553. PNG)]

4. pycharm settings

Interface modification

Code style modification

Interpreter modification

5. Project management

Open project

Section II variables and basic data types

1, Notes

Single-Line Comments

# Note Content  
print("hello world")  # Simple notes
 Shortcut key CTRL+/

multiline comment

"""
	Note 1
	Note II
	Note III
"""

perhaps

'''
	Note 1
	Note II
	Note III
'''

Note: single line comments are generally comments on one line of code

Multiline comments are generally comments on multiline code or code blocks

2, Role of variables

Definition of variable: name of memory address

2.1 defining variables:
Variable name = value

Custom identifier, variable name
2.2 identifier:
  • It is composed of numbers, underscores and letters
  • Cannot start with a number
  • Built in keywords cannot be used
  • Strictly case sensitive
2.3 naming habits:
  • See the name and know the meaning
  • Big hump: MyName
  • Small hump: myName
  • Underline: my_name
2.4 using variables
my_name  = 'hello world'
print(my_name)
2.5 understanding bug s
  • Break
  • debug debugging

3, Data type

  1. Value type: int float

  2. Boolean bool

  3. String str

  4. List list

    list1 = [10, 20, 30]
    
  5. tuple

    tuple1 = (10, 20, 30)
    
  6. Set set

    set = {10, 20, 30}
    
  7. Dictionary dict

    dict1 = {'name': 'Li Bai', 'age': 18}
    

    Note: spaces should be added after commas and colons

4, Output

1. Format output

  • %s String
  • %d signed decimal integer
  • %f floating point number
  • %c character
  • %u unsigned decimal integer
  • %o octal integer
  • %x hexadecimal integer (lowercase ox)
  • %X hexadecimal integer (uppercase OX)
  • %E scientific counting method (lowercase 'e')
  • %E scientific counting method (capital 'e')
  • %Abbreviations for G% e and% f
  • %G is short for% e and% F

skill:

  • %06d indicates the display digit of the output integer, which is not enough to be filled with 0, and is output as it is beyond the current digit
  • %. 2f indicates the number of decimal places displayed after the decimal point

2. f format string

Format: f '{expression}'

Note: This is Python 3 6 and later versions

print('My name is%s,this year%d Years old' % (name, age))
use f The expression is followed by:
print(f'My name is{name},this year{age}Years old')

3. Escape character

  • \n: Line feed
  • \t: Tab, a tab key is the distance of 4 spaces

4. Terminator

print('hello')Actually print('hello', end="\n"),Default built-in end="\n"Line break Terminator
 Users can make changes according to their own needs

Section 3 data type conversion and operator

1, Input

1. Input syntax

input("Prompt information")

2. Input characteristics

  • The data input by the user is generally stored in variables for easy use
  • Input will treat any received user input data as a string

2, Convert data type

  • int(x[,base]) converts x to an integer
  • float(x) converts x to a floating point number
  • str(x) converts x to a string
  • eval(str) is used to evaluate valid Python expressions in strings and return an object
  • tuple(str) converts sequence s into a tuple
  • list(str) converts a string into a list
  • complex(real[,imag]) creates a complex number. Real is the real part and imag is the imaginary part
  • Convert Rep x object to Repx
  • chr(x) converts an integer to a Unicode character
  • ord(x) converts a character to its ASCII integer value
  • hex(x) converts an integer to a hexadecimal string

3, Operator

1. Arithmetic operator

add , subtract , multiply and divide:+ - * /
to be divisible by	//
Surplus	%
index	**		2**4=16
 Parentheses ()

2. Assignment operator

Equal sign =

Single variable assignment	num = 1
 Multivariable assignment	num1, float1, str1 = 10, 0.5, 'hellowold'
Multiple variables are assigned the same value	a = b = 10

3. Compound assignment operator

Addition, subtraction, multiplication and division assignment operator	+=,-=,*=,/=
Integer division assignment operator	//=
Remainder assignment operator	%=
Power assignment operator	**=

Note: d = 10  d *=  2 + 1 ---- 10*(2+1)
Evaluate the expression to the right of the assignment operator first

4. Comparison operator

==	Judge equality
!=	Not equal to
>	greater than
<	less than
>=	Greater than or equal to
<=	Less than or equal to

5. Logical operator

and And
or or
not wrong

Expansion: logical operation between numbers
and : As long as one value is 0, otherwise the result is the last non-0 number
    0 and 9 and 7	The result is: 0
    9 and 8 and 6	The result is: 6
or  : Only all values are 0, otherwise the result is the first non-0 number
    0 or 8 or 7		The result is: 8
    8 or 1		    The result is: 8

Section 4 if statement

1, if syntax

1. Grammar

if Conditions:
	Code 1 for conditional execution
    Code 2 for conditional execution
    . . . 

2. Examples

if Conditions:
	Code to be executed when the condition is satisfied
    
Note: if the condition is true, execute the code with indentation below
    
if True:
   print('Code executed when conditions are met') 

age = int(input('Please enter age:'))		# Note: age is a string type, and type conversion is required
if age >= 18:
    print('Users are adults and can surf the Internet')

2, Multiple judgment

1. Grammar

if Condition 1:
	Code 1
    Code 2
    ...
elif Condition 2:
	Code 1
    Code 2
    ...
...
else:
    If none of the above conditions is true, execute the code

2. Examples

age = int(input('Please enter your age:'))

if age < 18:
    print('Minors are not allowed to surf the Internet')
elif (age >= 18) and (age <= 60):	# Reducible: 18 < = age < = 60
    print('Adults can access the Internet')
else:
    print('Too old to surf the Internet')
print('System shutdown')

3, if nesting

1. Grammar

if Condition 1:
	Code 1
    Code 2
   	
    if Condition 2:
    	Code 3
        Code 4

2. Example: bus example

money = 1
seat = 1

if money == 1:
    print('Hello, please get in the car')

    if seat == 1:
        print('Sit')
    else:
        print('stand')
else:
    print('Come on, run after me')

4, Guessing game

1. Demand analysis

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-7xr53hul-1618656212469) (C: \ users \ administrator \ appdata \ roaming \ typora \ typora user images \ image-20210415194111599. PNG)]

1,punches 
	Player: manual input
    Computer: 1.Fixing: scissors 2.random
2,Judge whether to win or lose
	2.1 Player wins
    2.2 it ends in a draw
    2.3 Computer wins

2. Code writing

import random

print('Prompt (0)--Scissors, 1--Stone, 2--Cloth)')

player = int(input('Player input'))
computer = random.randint(0, 2)

if ((player == 0) and (computer == 2)) or ((player == 1) and (computer == 0)) or ((player == 2) and (computer == 1)):
    print('win victory')
elif ():
    print('it ends in a draw')
else:
    print('Computer wins')

5, Ternary operator

Expression for conditional execution if condition else The expression does not hold

a = 1
b = 2

c = a if a > b else b

Section 5 while loop

1, Grammar

while Conditions:
	Code 1
    Code 2
    ....
    
example:
i = 100
while i != 0:
    print('Daughter in law, I was wrong')
    i -= 1

2, Apply

1. Calculate the cumulative sum of numbers within 1 ~ 100

sum_i = 0
i = 0

while i <= 100:
    sum_i += i
    i += 1
print(f'100 The sum of numbers within is{sum_i}')

2. Calculate the cumulative sum of even numbers within 100

# Method 1: counter control
i = 0
sum_i = 0

while i <= 100:
    sum_i += i
    i += 2
print(f'100 The cumulative sum of even numbers within is{sum_i}')

# Method 2: use even number to judge the condition

i = 0
sum_i = 0
while i <= 100:
    if i % 2 == 0:
        sum_i += i
    i += 1
print(f'100 The cumulative sum of even numbers within is{sum_i}')

3, break and continue

1,break

Terminate this cycle

# Eat five apples and don't eat them after eating three apples

i = 1
while i <= 5:
    print(f'Eat the second{i}An apple')
    i += 1
    if i == 3:
        print('When you're full, don't eat')
        break

2,continue

Exit the current cycle and then execute the next cycle

# Eat five apples. When you are late for the third apple, the insect won't eat it

i = 1
while i <= 5:
    if i == 3:
        print('I've eaten worms. No more')
        i += 1	#Pay attention to the counter
        continue
    print(f'Eat the second{i}An apple')
    i += 1

4, while loop nesting

1. Grammar

while Condition 1:
	Code executed when condition 1 is true
    ...
    while Condition 2:
    	Code executed when condition 2 is true
        ....

2. Example:

# Say my daughter-in-law is wrong five times a day. I have to wash the dishes for three consecutive days

day = 3
count = 5

# Days of external circulation
while day != 0:
    while count != 0:
        print('Daughter in law, I was wrong')
        count -= 1
    print('Brush the bowl')
    count = 5
    day -= 1
    print('------------')

3. Apply

1. Print asterisk (square)
# Print square asterisk

count_row = 0
count_column = 0

while count_row < 5:
    while count_column < 5:
        print('*', end='')
        count_column += 1
    count_column = 0
    print()
    count_row += 1

2. Print triangles

# Print triangles

count_row = 1
count_column = 0
while count_row < 6:

    while count_column < count_row:
        print('*', end='')
        count_column += 1

    print()
    count_column = 0
    count_row += 1

3. Print 99 multiplication table

# Print 99 multiplication table

count = 9    # Control the number of rows and columns
i = j = 1                       # i and j are used for recording

while i <= count:

    while j <= i:
        print(f'{i}*{j}={i*j}', end=' ')
        j += 1

    print()
    j = 1
    i += 1

Section VI for loop

1, Grammar

for Temporary variable in Sequence:		# It is composed of multiple data
	Repeated code 1
    Repeated code 2
    ...
    
str1 = 'python'
for i in str1:
    print(i)

2, break and continue

# break 
for i in str1:
    if i == 'h':
        print('encounter h Do not print')
        break
    print(i)
    
# continue
for i in str1:
    if i == 'h':
        print('encounter h Do not print')
        continue
    print(i)

3, else and the use of recycling

  • Both while and for can be used with else
  • Meaning of indented code under else: the code executed after the code ends normally
  • Breaking the loop does not execute the code indented below else
  • continue executes the indented code below else by exiting the loop

Section 7 string

1, Subscript

name = 'abcde'
print(name[0]) 

2, Slice

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

1. Grammar

sequence[Start position subscript: end position subscript: step size]


be careful:
1,The interval is left closed and right open
2,Step size is the selection interval, which can be positive or negative integers. The default step size is 1
3,The step size can not be written. The default value is 1

2. Examples

str1 = '012345678'
print(str1[2:5:1]) 		# 234
print(str1[2:5:2])		# 24
print(str1[2:5])		# 234
print(str1[:5])			# 01234
print(str1[2:])			# 2345678
print(str1[:])			# 012345678

# Negative test
print(str1[::-1])		# 876543210
print(str1[-4:-1])		# 567	# The reverse output adopts the principle of left closing and right opening

# Ultimate test
print(str1[-4:-1:1])	# 567
print(str1[-4:-1:-1])	# Data cannot be selected: from - 4 to - 1, the selection direction is from left to right, but - 1 step: from right to left 
# ***[key] if the selection direction (the direction from the beginning to the end of the subscript) conflicts with the direction of the step size, the data cannot be selected
print(str[-1:-4:-1])	# 876

3, Common operation methods

1. Search

find()
Check whether a substring is included in the string. If it is, the subscript at the beginning of the substring will be returned. Otherwise, it will be returned-1

Syntax: 
	String sequence.find(String, subscript of start position, subscript of end position)
 Note: the subscript at the beginning and the subscript at the end can be omitted, which means to search in the whole string sequence
index()
Check whether a substring is included in the string. If it is, the subscript at the beginning of the string will be returned. Otherwise, an error will be reported

Syntax:
	String sequence.index(Substring, Subscript of start position, Subscript of end position)
Note: the subscript of the start position and the subscript of the end position can be omitted
count()
Returns the number of occurrences of a substring in a string
  • rfind(): the same function as find, but the search direction only starts from the right
  • rindex(): the same function as index, but the search direction only starts from the right

2. Modification

replace()

Replace string

Syntax:

String sequence.replace(Old string, new string, replacement times)

mystr = "hello world and itcast and itheima and Python"

# Result: hello world he itcast he itheima he Python
print(mystr.replace('and', 'he'))
# Result: hello world he itcast he itheima he Python
print(mystr.replace('and', 'he', 10))
# Result: hello world and itcast and itheima and Python
print(mystr)

Note: if there is no write replacement times, it defaults to replace all. The return value is a string type

split()

Split string

grammar

String sequence.split(Split characters, num)

mystr = "hello world and itcast and itheima and Python"

# Result: ['hello world', 'itcast', 'itheima', 'Python']
print(mystr.split('and'))
# Result: ['hello world', 'itcast', 'itheima and Python']
print(mystr.split('and', 2))
# Results: ['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']
print(mystr.split(' '))
# Results: ['Hello ',' world ',' itcast and itheima and Python ']
print(mystr.split(' ', 2))

Note: num refers to the number of divisions, and the number of data to be returned is num + +. The return value type is a list type

join()

Merge string

grammar

Character or substring.join(A sequence of multiple strings)

list1 = ['chuan', 'zhi', 'bo', 'ke']
t1 = ('aa', 'b', 'cc', 'ddd')
# Result: chuan_zhi_bo_ke
print('_'.join(list1))
# Result: AA b... cc... ddd
print('...'.join(t1))
Case conversion function
capitalize(): Only the first character of the string is converted to uppercase, even if there are other uppercase characters in the string, it will be converted to lowercase
title(): Converts the first letter of each word in a string to uppercase
lower(): Converts uppercase to lowercase in a string
upper(): Convert small case to uppercase of string
Delete blank function
rstrip: Delete the white space character to the right of the string
lstrip: Delete the blank character to the left of the string
strip:  Delete white space characters on both sides of the string
Alignment function
ljust:Align left
rjust:Right align
center:Middle alignment

3. Judgment function

  • startwith(): check 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, check within the specified range

    Syntax:
    	String sequence.startwith(Substring, subscript of start position, subscript of end position)
    
  • endwith(): similar to startwith

  • 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(): the string is a combination of letters or numbers

  • isspace(): returns True if all strings are blank; otherwise, returns False

Section 8 list and tuple

1, Format of list

[Data 1, data 2, data 3, ...]

The list can store multiple data at one time and can be of different data types

2, Common operation

1. Search

  • subscript
name_list = ['Tom', 'Lily', 'Rose']
print(name_list[0])	# Tom
print(name_list[1]) # Lily
  • function
  1. index(): returns the subscript of the specified data location

    Note: if the searched data does not exist, an error will be reported

    Syntax:
    	List sequence.index(Data, start position subscript, end position subscript)
        
    name_list = ['Tom', 'Lily', 'Rose']
    print(name_list.index('Lily', 0, 2))	# 1
    
  2. count(): counts the number of times the specified data appears in the current list

    name_list = ['Tom', 'Lily', 'Rose']
    print(name_list.count('Tom'))	# 1
    print(name_list.count('Toms'))	# 0
    
  3. len(): access list length, that is, the number of data in the list

    name_list = ['Tom', 'Lily', 'Rose']
    print(name_list.len())	# 3
    
  • Determine whether a data exists
  1. In: judge whether a data is in the list. If it is in the list, it will return a True; if not, it will return a False

    name_list = ['Tom', 'Lily', 'Rose']
    isLily = 'Lily' in name_list
    print(isLily)	# True
    
  2. Not in: judge whether the specified data is not in a list sequence. If it is not, a True is returned; otherwise, a False is returned

    name_list = ['Tom', 'Lily', 'Rose']
    isLily = 'Rose' not in name_list
    print(isLily)	# False
    

    Experience case

    Requirement: check whether the name entered by the user already exists

    name_list = ['Tom', 'Lily', 'Rose']
    
    name = input('Please enter a name')
    
    if name in name_list:
        print('The name you entered already exists')
    else:
        print('The name you entered does not exist')
    

2. Increase

  • append(): add data at the end of the list

    Syntax:
    	List sequence.append((data)
        
    name_list = ['Tom', 'Lily', 'Rose']
    name_list.append('xiaoming')
    print(name_list)	# ['Tom', 'Lily', 'Rose', 'xiaoming']
    name_list.append(['xiaoming', 'xiaoming'])
    print(name_list)	# ['Tom', 'Lily', 'Rose', 'xiaoming', ['xiaoming', 'xiaoming']]
    # Note: if the data appended to append is a sequence, the entire sequence will be appended to the list
    
  • extend(): append data at the end of the list. If the data is a sequence, add the data of this sequence to the list one by one

    # Single data:
    name_list = ['Tom', 'Lily', 'Rose']
    
    name_list.extend('xiaoming')
    print(name_list)
    # Results: ['Tom', 'Lily', 'Rose', 'x', 'I', 'a', 'o','m ',' I ',' n ',' g ']
    
    # Multiple data
    name_list.extend(['xiaoming', 'xiaohong'])
    print(name_list)
    # Results: ['Tom', 'Lily', 'Rose', 'xiaoming', 'xiaohong']
    
  • insert(): add data at the specified location

    Syntax:
    	list.insert(Location (subscript, data)
        
        name_list = ['Tom', 'Lily', 'Rose']
    
    name_list.insert(1, 'xiaoming')
    
    # Results: ['Tom', 'xiaoming', 'Lily', 'Rose']
    print(name_list)
    

3. Delete

  1. del
You can delete the specified data	del name_list[0]
You can also delete the list		del name_list
  1. pop(): delete the data of the specified subscript (the last one by default) and return the data

    Syntax:
    	List sequence.pop(subscript)
      
        name_list = ['Tom', 'Lily', 'Rose']
        del_name = name_list.pop(1)
        print(del_name)		# Lily
        print(name_list)	# ['Tom', 'Rose']
        
        name_list = ['Tom', 'Lily', 'Rose']
        del_name = name_list.pop()
        print(del_name)		# Rose
        print(name_list)	# ['Tom', 'Lily']
    
  2. remove(): removes the first match of a data in the list

    Syntax:
    	List sequence.remove(data)
        
        name_list = ['Tom', 'Lily', 'Rose']
        
        name_list.remove('Rose')
        print(name_list)	# [['Tom', 'Lily']
    
  3. clear(): clear the list

    name_list = ['Tom', 'Lily', 'Rose']
    
    name_list.clear()
    print(name_list)	# Result []
    

4. Modification

  name_list = ['Tom', 'Lily', 'Rose']

name_list.insert(1, 'xiaoming')

Results: ['Tom', 'xiaoming', 'Lily', 'Rose']

print(name_list)

#### 3. Delete

1.  del

 ```python
 You can delete the specified data	del name_list[0]
 You can also delete the list		del name_list
  1. pop(): delete the data of the specified subscript (the last one by default) and return the data

    Syntax:
    	List sequence.pop(subscript)
      
        name_list = ['Tom', 'Lily', 'Rose']
        del_name = name_list.pop(1)
        print(del_name)		# Lily
        print(name_list)	# ['Tom', 'Rose']
        
        name_list = ['Tom', 'Lily', 'Rose']
        del_name = name_list.pop()
        print(del_name)		# Rose
        print(name_list)	# ['Tom', 'Lily']
    
  2. remove(): removes the first match of a data in the list

    Syntax:
    	List sequence.remove(data)
        
        name_list = ['Tom', 'Lily', 'Rose']
        
        name_list.remove('Rose')
        print(name_list)	# [['Tom', 'Lily']
    
  3. clear(): clear the list

    name_list = ['Tom', 'Lily', 'Rose']
    
    name_list.clear()
    print(name_list)	# Result []
    

4. Modification

Topics: Python