Basic syntax (variable + data type conversion + input() + operator + program structure)

Chapter I

I notes

① Single line note

Start with "#"

② Multiline comment

Start with three single / double quotes

③ Chinese coding statement notes

Add Chinese declaration comments at the beginning of the file to specify the encoding format of the source file

#coding:gbk

II operator

☝ Add -- "+“

☝ Minus - "-"

☝ Multiply - "*"

☝ Except -- "/“

☝ Quotient - "/ /"

☝ Remainder - "%"

☝ Power - "* *"

III Output function

 1. Use of print() function

(1) What can the print() function output

a. The output of the print () function can be numbers

b. The output of the print () function can be a string

c. The output of the print () function can be an expression containing an operator

(2). The print() function can output content to a destination

a. Display

b. Documents

(3) The output form of the print() function

a. Line feed

b. No line breaks

#number
print(520)
#character string
print('Helloworld')
#Expression with operator
print(1+3)
#Output the data to a file, note 1 The specified drive letter does not exist 2 Use file=fp
fp=open('D:/text.txt','a+')#a +: if the file does not exist, it will be created. If it exists, it will continue to be added after the file content
print('Helloworld',file=fp)
fp.close()

#No newline output (output content in one line)
print('hello','world'.python')

IV Escape character

1. What is an escape character

Backslash + the first letter of the escape function you want to achieve

2. Why do you need escape characters

When a string contains special-purpose characters such as backslash, single quotation mark and double quotation mark, these characters must be escaped with backslash (escape a meaning)

Backslash:\

Single quotation mark: \ '

Double quotation marks:\“

3. When the string contains special characters that cannot be directly represented, such as line feed, carriage return, horizontal tab or backspace, escape characters can also be used when the string contains line feed
When special characters such as carriage return, horizontal tab or backspace cannot be directly represented, the transfer character can also be used

Wrap: \ n

Enter: \ r

Horizontal tab: \ t

Backspace: \ b

#Escape character
print('hello\nworld')
print('hello\tworld')
print('hello\rworld')#world will overwrite hello
print('hello\bworld')#\b is a backspace, o will be covered
#Original character: use the original character if you do not want the escape character of the string to work. The original character is to add R or r before the string
print(R'hello\nworld')

4. Precautions

The last character cannot be \, but it can be\

V Identifiers and reserved words

1. Reserved words (the following code can be used to find reserved words in python)

import keyword
print(keyword.kwlist)

2. Identifier (the names of variables, functions, classes, modules and other objects are called identifiers)

  ♠ rule

● letters, numbers, underscores

● cannot start with a number

● cannot be reserved

● case sensitive

Vi variable

1. General

Box with label in memory

2. Composition of variables

● identification: indicates the memory address stored by the object, which is obtained by using the built-in function id(obj)

● type: refers to the data type of the object, which is obtained by using the built-in function type(obj)

● value: represents the specific data stored in the object. The value can be printed by using print(obj)

3. Variable name = variable value (it can be assigned multiple times and the last new value is output)

4. Naming of variables (meaningful)

☆ hump type

1) Big hump

2) Small hump

☆ underline

★ how to find nouns that cannot be named (reserved words)

import keyword
print(keykord.keylist)

VII data type

7.1 common data types

  1. Integer type → int → 98
  2. Floating point type → float → 3.14159
  3. Boolean type → bool → Ture,False
  4. String type → str → 'ABCD'
#Integer type
#1. It can be expressed as positive number, negative number and 0
n1=90
n2=-76
n3=0
print(n1,type(n1))#90<class 'int'>
print(n2,type(n2))#-76<class 'int'>
print(n3,type(n3))#0<class 'int'>
#Integers can be expressed in binary, decimal, octal, hexadecimal
print('decimal system',118)#Decimal 118
print('Binary',0b10101111)#Binary 175
print('octal number system',0o176)#126
print('hexadecimal',0x1EAF)#7855
#Floating point type: consists of integer part and decimal part
a=3.14159
print(a,type(a))
#Floating point storage imprecise
n1=1.1
n2=2.2
print(n1+n2)#3.3000000000000003
#Import the module decimal to solve the above problems
from decimal import Decimal
print(Decimal('1.1')+Decimal('2.2'))#3.3
'''
Boolean type
1.Used to indicate true or false values
2.Ture It means true, Flase Indicate false
3.Boolean values can be converted to integers
  Ture→1
  Flase→0 
'''
print(Ture+1)#2
print(Flase+1)#1
'''
String type
1.Also known as immutable character sequence
2.You can use single quotes'',Double quotation mark"",Three quotation marks''' '''or""" ""'To define
3.The strings defined by single and double quotation marks must be on one line
4.The string defined by three quotation marks can be distributed on multiple consecutive lines
'''
str1='Life is short, work hard'
str2="Life is short, work hard"
str3='''Life is short,
Work hard'''
print(str1)
print(str2)
print(str3)

7.2 data type conversion

name='Zhang San'
age=20
print(type(name),type(age))# str int indicates that the data types of name and age are different
#print('My name is' + name + 'this year' + age + 'years old') when connecting str type and int type, an error is reported. Solution: data type conversion
print('My name is'+name+'this year'+str(age)+'year')#My name is Zhang San. I'm 20 years old
#str() converts other types to str types
a=10
b=198.8
c=Flase
print(str(a),str(b),str(c))
#int() converts other types of to int
s1='128'
f1=98.7
s2='76.77'
ff=True
s3='hello'
print(int(s1),type(int(s1)))#Convert str type to int type and string to number
print(int(f1),type(int(f1)))#Convert float type to int type, intercept integer part and round off decimal part
#print(int(s2),type(int(s2))) converts str type to int type and reports an error because the string is a decimal string
print(int(ff),type(int(ff)))
print(int(s3),type(int(s3)))#An error is reported. Convert str type to int type. It must be a number and an integer
#float() converts other types of to float
s1='128'
s2='76'
ff=True
s3='hello'
i=98
print(float(s1),type(float(s1)))
print(float(s2),type(float(s2)))
print(float(ff),type(float(ff)))
#print(float(s3),type(float(s3))) #If the data in the string is a non numeric string, conversion is not allowed
print(float(i),type(float(i)))

VIII input() function

8.1. Introduction to the input() function

1.1 function: accept input from users

1.2 return value type: the type of the input value is str

1.3 value storage: use = to store the entered value

8.2. Basic use of input() function

present=input('What gift do you want')
print(present)

8.3. Advanced use of the input() function

​
#Enter two integers from the keyboard and sum them
a=input('Please enter an addend')
a=int(a)
b=input('Please enter another addend')
b=int(b)
print(a+b)

​

IX operator

(1) Arithmetic operator

☝ Add -- "+“

☝ Minus - "-"

☝ Multiply - "*"

☝ Except -- "/“

☝ Quoting - "/ /"

☝ Remainder - "%"

☝ Power - "* *"

operatorexpressexampleresult
+plus1+12
-reduce1-10
*ride2*48
/except1/20.5
%Remainder (one positive and one negative formula)9%41
Remainder = divisor divisor * quotient

9%-4

9-(-4)*(-3)

-3
**exponentiation 2**38
Integer (one positive and one negative rounded down)11//25
//Integer (one positive and one negative rounded down)9//-4-3
Integer (one positive and one negative rounded down)-9//4-3

(2) Assignment operator

1. Operation sequence

Right to left

2. Chain assignment is supported

a=b=c=20

3. Support parameter assignment

☝ += a += 3 is equivalent to a = a + 3

☝-= b - = 4 , equivalent to b = b - 4

☝*= c *= 5 is equivalent to c = c * 5

☝/= d /= 6 , equivalent to d = d / 6

☝%= E% = 7 , equivalent to , e = e% 7

4. Support series unpacking and assignment

a,b,c=20,30,40

Exchange the values of two variables

a,b=10,20
print('Before exchange:',a,b)
#exchange
a,b=b,a
print('After exchange:',a,b)

(3) A Comparison operator

  • Greater than >
  • Less than<
  • Greater than or equal to >=
  • Less than or equal to<=
  • Equal==
  • Unequal=

A variable consists of three parts: identification, type and value== The value is compared, and the identifier of the comparison object is

a=10
b=10
print(a==b)#Ture indicates that the values of a and b are equal
print(a is b)#Figure indicates that the IDs of a and B are equal
lst1=[11,22,33,44]
lst2=[11,22,33,44]
print(lst1==lst2)#Figure indicates that lst1 and lst2 values are equal
print(lst1 is lst2)#False indicates that the ID IDs of lst1 and lst2 are not equal
print(lst1 is not lst2)#Figure indicates that the ID identifiers of lst1 and lst2 are not equal

(4) A Boolean operator

operatorArithmetic numberOperation resultremarks

   and

(and)

TureTureTureWhen both operands are true, the operation result is true
TureFalseFalse
FalseTure
FalseFalse

or

(or)

TureTureTureAs long as one operand is true, the operation result is true
TureFalse
FalseTure
FalseFalseFalse

not

(negation of boolean type)

TureFalseIf the operand is true, the result is False
FalseTureIf the operand is False, the result is true

(5) A Bitwise Operators

Convert data to binary for calculation

  1. Bits and & - the corresponding bits are 1, and the result number is 1, otherwise it is 0
  2. Bit or | - the corresponding digits are 0, and the result number is 0, otherwise it is 1
  3. Left shift operator (< <) -- high overflow discard, low complement 0 (moving one bit to the left is equivalent to multiplying 2, and moving two bits to the left is equivalent to multiplying 4)
  4. Shift right operator (> >) -- low overflow discard, high complement 0 (moving one bit to the right is equivalent to dividing by 2)
print(4&8) #0
print(4|8) #12
print(4<<1) #8 move one bit to the left
print(4<<2) #16 move two bits to the left
print(4>>1) #2

Illustration

(6) Operator priority

  1. Arithmetic operators (multiplication and division first, then addition and subtraction, and power operation first)
  2. Bit operation
  3. Comparison operator
  4. Boolean operator
  5. Assignment Operators

 

 10. Sequential structure

The program executes the code from top to bottom without any judgment and jump until the end of the program

11. Boolean value of object

(1). All Python objects have a Boolean value, and the built-in function bool() is used to obtain the Boolean value of the object

(2). The Boolean value of the following object is False:

  • False
  • Value ()
  • None
  • Empty string
  • Empty list
  • Empty tuple
  • Empty dictionary
  • Empty set
#Boolean value of the test object
print(bool(False))  #False
print(bool(0))  #False
print(bool(0.0))  #False
print(bool(None))  #False
print(bool(''))  #False
print(bool(""))  #False
print(bool([]))  #False empty list
print(bool(list()))  #False empty list
print(bool(()))  #False empty tuple
print(bool(tuple()))  #False empty tuple
print(bool(dict()))  #False empty dictionary
print(bool({}))  #False empty dictionary
print(bool(set()))  #False empty set

12. Select structure

12.1 single branch structure

12.1.1 Chinese semantics

If Just

12.1.2 grammatical structure

if Conditional expression:
      Conditional executor

12.1.3 flow chart

12.2 double branch structure

12.2.1 Chinese semantics

If dissatisfaction... Just

12.2.2 grammatical structure

if Conditional expression :
     Condition executor 1
else:
     Conditional actuator 2

12.2.3 flow chart

12.3 multi branch structure

12.3.1 Chinese meaning

  • ..... Is it? No
  • ..... Is it? No
  • ..... Is it? No
  • ..... Is it? No
  • ..... Is it? Yes

12.3.2 grammatical structure

if Conditional expression 1 :
     Conditional actuator 1
elif Conditional expression 2:
     Conditional actuator 2
elif Conditional expression N:
     Conditional executor N
[else:]
      Conditional executor N+1

12.3.3 flow chart

12.4 nested if

12.4.1 grammatical structure

if Conditional expression 1:
   if Inner conditional expression:
        Inner condition actuator 1
   else:
        Inner conditional actuator 2
else:
   Conditional executor

12.5 conditional expressions

The conditional expression is if Abbreviation for else

12.5.1 grammatical structure

x   if   Judgment conditions   else  y

12.5.2 operation rules

If the Boolean value of the judgment condition is True, the return value of the condition expression is x; otherwise, the return value of the condition expression is False

13. Circulation structure

13.1 while loop

13.1.1 basic grammar

initial condition       #It is usually a counter executed repeatedly
while  condition(Judge whether the counter reaches the target number of times) : 
       When the condition is completed, task 1 is completed
       When the condition is completed, task 2 is completed
       When the condition is completed, task 3 is completed
       ......
   treatment conditions (Counter + 1)

Note: the while statement and the indented part are a complete block of code

13.1.2 cases

# 1. Define an integer variable to record the number of cycles
i = 1
# 2. Start cycle
while i <= 5 :
   # 1> Code you want to execute within a loop
   print(" Hello future")
   # 2> Processing counter
   i = i + 1

13.1.3 dead cycle

Because the programmer forgot to modify the judgment conditions of the loop inside the loop, the loop continued and the program could not be terminated

13.1.4 counting method

  1. Natural counting (starting from 1) - in line with people's usual habits
  2. Program counting method (starting from 0) - almost all program languages choose to count from 0

13.1.5 cycle calculation

Case 1: calculate the even sum result between 0-100

#1. Define an integer variable to record the number of cycles
i=0
#Define end result variables
sum = 0
#Start cycle
while i<=100:
    if i%2==0:
        sum += i
    #Processing counter
    i+=1
print(sum)

 14.break and continue

break and continue are keywords specifically used in loops

  • When a condition is met, exit the loop and no subsequent code will be executed
  • continue when a condition is met, the subsequent code is not executed

break and continue are only valid for the current loop

15.while loop nesting

15.1 loop nesting

while  Condition 1:
       When the condition is completed, task 1 is completed
       When the condition is completed, task 2 is completed
       When the condition is completed, task 3 is completed
       ......

       while  Condition 2:
       When the condition is completed, task 1 is completed
       When the condition is completed, task 2 is completed
       When the condition is completed, task 3 is completed
       ......
       Treatment condition 2
   Treatment condition 1

Keywords: Python

Added by mobtex on Fri, 21 Jan 2022 11:28:42 +0200