程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Basic syntax of Python

編輯:Python

One 、 notes

The goal is

  • The function of annotation

  • The classification and grammar of annotations

  • Characteristics of annotation

1、 The function of annotation

By using a familiar language , In the program, some codes are annotated , That's what annotations do , Can greatly enhance the readability of the program .

2、 The classification and grammar of annotations

Annotations fall into two categories : Single line comments and multi line comments

  • Single-line comments

Only one line can be annotated , The grammar is as follows :

# The comment 
  • Multiline comment

You can annotate multiple lines of content , It is usually used to comment a piece of code , The grammar is as follows :

"""
The first line notes
Second line of notes
The third line notes
……
"""
​
'''
notes 1
notes 2
notes 3
……
'''

Be careful : The interpreter does not execute any comment content

summary

  • The function of annotation

Is it treated in a language familiar to humans? Explain it , Convenient later maintenance .

  • Classification of notes

    • Single-line comments :# The comment , Shortcut key Ctrl+/

    • Multiline comment :""" The comment """ perhaps ''' The comment '''

  • The interpreter does not execute annotation content

Two 、 Variable

The goal is

  • Role of variables

  • Defining variables

  • Understanding data types

1、 Role of variables

Example experience : Let's go to the library to read , How to quickly find the books you want ? Is the administrator putting the book in a fixed position in advance , And numbered this position , We only need to search the designated location according to this number in the library to find the books we want .

This number is actually a name for the shelf where the books are stored , Easy to find and use later .

In the program , Data is temporarily stored in memory , To find or use this data more quickly , Usually we define a name after storing this data in memory , The name is the variable .

A variable is just the name of the memory address where the current data is stored .

2、 Defining variables

 Variable name  =  value 

Variable name customization , To satisfy the identifier naming rules

2.1 identifier

Identifier naming rules Python A unified specification for defining various names in , As follows :

  • By digital 、 Letter 、 Underline composition

  • Cannot start with a number

  • You can't use built-in keywords

  • Case sensitive

False      None     True     and      as       assert    break     class
continue   def      del      elif     else     except    finally   for
from       global   if       import   in       is        lambda    nonlocal
not        or       pass     raise    return   try       while     with        yield

2.2 Naming habits

  • See the name and know the meaning

  • Hump : That is, every word is capitalized , for example :MyName

  • Little hump : the second ( contain ) Later words are capitalized , for example :myName

  • Underline : for example :my_name

3、 Using variables

my_name='Tom'
print(my_name)
​
schoolName=" Black horse programmer "
print(schoolName)

4、 Understanding data types

stay Python In order to meet different business needs , Also divide the data into different types

# int—— integer
num1 = 1
# float—— floating-point , It's a decimal
num2 = 1.1
# str—— character string , characteristic : Data should be quoted
a = 'hello whorld'
# bool—— Boolean type , Usually used in judgment . Boolean has two values :True and False
b = True
# list—— list
c = [10,20,30]
# tuple—— Tuples
d = (10,20,30)
# set—— aggregate
e = {10,20,30}
# dict—— Dictionaries : Key value pair
f={'name':'TOM','age':'18'}

summary

  • The syntax for defining variables

  •  Variable name = value 
  • identifier

    • By digital 、 Letter 、 Underline composition

    • Cannot start with a number

    • You can't use built-in keywords

    • Case sensitive

  • data type

    • integer :int

    • floating-point :float

    • character string :str

    • Boolean type :bool

    • Tuples :tuple

    • aggregate :set

    • Dictionaries :dict

3、 ... and 、Debug Tools

Debug The tool is pycharm IDE Tools integrated in to debug programs , Here, the programmer can view the execution details and process of the program or mediation bug.

Debug How to use the tool :

  1. Breaking point

  2. Debug debugging

3.1 Breaking point

  • Breakpoint location

The first line of code of the code block to be debugged by the target can , That is, a breakpoint .

  • The way to interrupt

Click the blank space to the right of the line number of the object code .

Four 、 Output

The goal is

  • Format output

    • Format symbol

    • f- character string

  • print The terminator

Output

effect : Program output content to users

demand : Output “ My age this year is 18 year ”

1、 Format output

The so-called formatted output is to output content in a certain format .

1.1 Format symbol

Format symbol transformation %s character string %d Signed decimal integers %f Floating point numbers %c character %u An unsigned decimal integer %o Octal integer %x Hexadecimal integer ( A lowercase letter ox)%X Hexadecimal formal ( Capitalization OX)%e Scientific enumeration ( A lowercase letter 'e')%E Scientific enumeration ( Capitalization 'E')%g%f and %e Abbreviation %G%f and %E Abbreviation

skill %06d, Indicates the number of integer display digits of the output , not enough 0 completion , If it exceeds the current digit, it will be output as is

%.2f, Represents the number of decimal places displayed after the decimal point

'''
1、 Prepare the data
2、 Format symbol output data
'''
age = 18
name = 'TOM'
weight = 75.5
stu_id = 1
# 1、 My age this year is x year —— Integers %d
print(' My age this year is %d year '%age)
# 2、 My name is X—— character string %s
print(' My name is %s'%name)
# 3、 My weight is x kg —— Floating point numbers %f
print(' My weight is %f kg '%weight)
print(' My weight is %.2f kg '%weight)  Be careful : This one has two decimal places
# 4、 My student number is x
print(' My student number is %d'%stu_id)
print(' My student number is %03d'%stu_id)   Be careful : This integer is expressed in 3 Bit integer display
# 5、 My name is x, This year, x Year old
print(' My name is %s, This year, %d Year old '%(name,age))
# 5.1 My name is x, This year, x Year old
print(' My name is %s, This year, %d Year old '%(name,age+1))
# 6、 My name is x, This year, x Year old , weight x kg , The student number is x
print(' My name is %s, This year, %d Year old , weight %.2f kg , The student number is %03d'%(name,age,weight,stu_id))
print(' My name is %s, This year, %s Year old , weight %s kg '%(name,age,weight))

1.2 f'{ expression }'

Format string except %s, It can also be written as f'{ expression }'

name='TOM'
age=18
# My name is X, This year, X Year old
print(f' My name is {name}, This year, {age} Year old ')

f- The format string is Python3.6 New formatting method in , This method is easier to read

1.3 Translate characters

  • \n: Line break

  • \t: tabs , One tab key (4 A space ) Distance of

print("hello \n world")
print("\t abcd")

1.4 Terminator

Think about it , Why two print Will wrap output ?

print(' Output content ',end="\n")

stay Python in ,print(), Default by oneself end="\n" This newline Terminator , So it leads to every two print Direct line feed display , Users can change the terminator as required

summary

  • Format symbol

    • %s: Format output string

    • %d: Format output integers

    • %f: Format output floating point number

  • f- character string

    • f'{ expression }'

  • Escape character

    • \n: Line break

    • \t: tabs

  • print Terminator

print(' Content ',end="")

5、 ... and 、 Input

The goal is

  • Syntax of input function

  • Input input Characteristics

1、 Input

1.1 The role of input

stay Python in , The function of the program to accept the data entered by the user is to input .

1.2 Input syntax

input(" Prompt information ")

1.3 The characteristics of input

  • When the program is executed to input, Waiting for user input , After the input is completed, continue to execute down

  • stay Python in ,input After receiving user input , Generally stored in scalar , Easy to use

  • stay Python in ,input The received data input by any user will be treated as a string .

password=input(' Please enter your password :')
print(f' The password you entered is {password}')

6、 ... and 、 Convert data type

The goal is

  • The necessity of data type conversion

  • Common methods of data type conversion

1、 The role of converting data types

ask :input() The data received from the user is of string type , If user input 1, I want to know how to operate an integer ?

answer : Convert the data type , Convert string type to integer

2、 Functions that convert data types

function explain int(x[,base]) take x Convert to an integer float(x) take x Convert to a floating point number complex(real[,imag]) Create a complex number ,real It is the real part ,imag It is the imaginary part str(x) Put the object x Convert to string repr(x) Put the object x Converts to an expression string eval(str) Used to calculate the validity in a string Python expression , And returns an object tuple(s) The sequence of s Converts to a tuple list(s) The sequence of s Convert to a list chr(x) Convert an integer to a Unicode character ord(x) Converts a character to its ASCII An integer value hex(x) Convert an integer to a hexadecimal string
# 1、float()—— Convert data to floating point
num1 = 1
str1 = '10'
print(type(float(num1))) # float
print(float(num1)) # 1.0
print(float(str1)) # 10.0
# 2、str()—— Convert data to string type
print(typr(str(num1))) #str
# 3、tuple()—— Convert a sequence into tuples
list1 = [10 ,20 ,30]
print(tuple(list1)) #(10 ,20 ,30)
# 4、list()—— Convert a sequence into a list
t1 = (100 ,200 ,300)
print(list(t1)) #[100 ,200 ,300]
# 5、eval()—— Calculate the validity of in string Python expression , And returns an object
str2 = '1'
str3 = '1.1'
str4 = '(1000 ,2000 ,3000)'
str5 = '[1000 ,2000 ,3000]'
print(type(eval(str2))) # int
print(type(eval(str3))) # float
print(type(eval(str4))) # tuple
print(type(eval(str5))) # list

summary

  • Common functions for converting data types

    • int()

    • float()

    • str()

    • list()

    • tuple()

    • eval()

7、 ... and 、 Operator

The goal is

Master the functions of common operators

Classification of operators

  • Arithmetic operator

  • Assignment operator

  • Compound assignment operator

  • Comparison operator

  • Logical operators

1、 Arithmetic operator

Operator describe example + Add 1+1 The output is 2- reduce 1-1 The output is 0* ride 2*2 The output is 4/ except 10/5 The output is 2.0( The result is float type )// to be divisible by 9//4 The output is 2% Remainder 9%4 The output is 1** Index 2**4 The output is 16() parentheses Parentheses are used to increase the priority of operations , namely (1+2)*3 The output is 9

Be careful :

  • Mixed operation priority order :() higher than ** higher than *///% higher than +-

2、 Assignment operator

Operator describe example = assignment take = The result on the right is assigned to the variable on the left of the equal sign
  • Single variable assignment

num = 1
print(num)
  • Multiple variable assignments

num1,float1,str1=10,0.5,'hello world'
print(num1)
print(float1)
print(str1)
  • Many variables are given the same value

a = b = 10
print(a)
print(b)

3、 Compound assignment operator

Operator describe example += Addition assignment operator c += a Equivalent to c = c+a-= Subtraction assignment operator c -= a Equivalent to c = c-a*= Multiplication assignment operator c = a Equivalent to c = ca/= Division assignment operator c /= a Equivalent to c = c / a//= The integer division assignment operator c //= a Equivalent to c=c//a%= The remainder assignment operator c %= a Equivalent to c=c%a**= Power assignment operator c = a Equivalent to c=ca

Be careful :

The operation order is to operate the calculation on the right side of the compound assignment operator first , Then perform the compound assignment operation

4、 Comparison operator

Comparison operators are also called relational operators , Usually used to judge

Operator describe == Judge equal . If the results of two operands are equal , Then the conditional result is true (True), Otherwise, the conditional result is false (False)!= It's not equal to . If the results of two operands are not equal , Then the condition is true (True), Otherwise, the conditional result is false (False)> Whether the left-hand result of the operator is greater than the right-hand result of the operator , If it is greater than , Then the condition is true , Otherwise it is false < Whether the result of the operands on the left side of the operator is less than the result of the operands on the right side , If it is less than , Then the condition is true , Otherwise it is false >= Whether the left-hand result of the operator is greater than or equal to the right-hand result of the operator , If greater than or equal to , Then the condition is true , Otherwise it is false <= Whether the left-hand result of the operator is less than or equal to the right-hand result of the operator , If less than or equal to , Then the condition is true , Otherwise it is false

5、 Logical operators

Operator Logical expression describe example andx and y Boolean “ And ”: If x For false ,x and y Return to leave , Otherwise, it returns true True and False, return Falseorx or y Boolean “ or ”: If x It's true ,x or y Return to true , Otherwise return to y Value False or True, return Turenotnot x Boolean “ Not ”: If x It's true ,x and y Return to leave , If x For false ,not x Return to true not True return False,not False return True

expand — Logical operations between numbers

a=0
b=1
c=2
# and Operator , As long as a value of 0, The result is 0, Otherwise it turns out to be the last non 0 Numbers
print(a and b)#0
print(b and a)#0
print(a and c)#0
print(c and a)#0
print(b and c)#2
print(c and b)#1
# or Operator , Only all values are 0, The result is 0, Otherwise it turns out to be the first non 0 Numbers
print(a or b)#1
print(a or c)#2
print(b or c)#1

summary

  • Priority of arithmetic operations

    • Mixed budget priorities :() higher than ** higher than *///% higher than +-

  • Assignment operator

    • =

  • Compound assignment operator

    • +=

    • -=

    • priority

      • Let's start with the expression to the right of the compound assignment operator

      • Then calculate the arithmetic operation of compound assignment operation

      • Final assignment operation

  • Comparison operator

    • Judge equal :==

    • Greater than or equal to :>=

    • Less than or equal to :<=

    • It's not equal to :!=

  • Logical operators

    • And :and

    • or :or

    • Not :not

8、 ... and 、 Conditional statements

The goal is

  • Conditional statements work

  • if sentence

  • if……else……

  • Multiple judgments

  • if nesting

1、 Understand conditional statements

Suppose a scenario :

  • Have you ever been to an Internet cafe at this age ?

  • What is the one thing you must do when you go to an Internet cafe to surf the Internet ?

  • Why give the ID card to the staff ?

  • Is it to judge whether you are an adult ?

  • If adults can surf the Internet ? If you are not an adult, you are not allowed to surf the Internet ?

In fact, the so-called judgment here is conditional statement , namely If the condition holds, execute some code , If the condition does not hold, the code will not be executed

2、if grammar

2.1 grammar

if Conditions :
Conditional execution code 1
Conditional execution code 2
……

2.2 Quick experience

if True:
print(" Conditional execution code 1")
print(" Conditional execution code 2")

3、 example : surf the internet

Demand analysis : If the user is older than or equal to 18 year , That's adult , Output “ Has reached adulthood , You can go online ”

3.1 Simple version

age=20
if age>=18:
print(" Has reached adulthood , You can go online ")
print(" System off ")

3.2 premium

New demand : Users can output their own age , And then the system decides whether or not you're an adult , Adults export “ Your age is ‘ The age entered by the user ’, Has reached adulthood , You can go online ”.

# input String type when accepting user input data , On the condition that age And integers 18 Do judgment , So here it is int Convert data type
age = int(input(" Please enter your age :"))
if age >= 18:
print(f' Your age is {age}, Has reached adulthood , You can go online ')
print(' System off ')

4、if……else……

effect : Implementation of conditions if Code below ; Conditions not established , perform else Code below

reflection : Examples of Internet cafes , If you grow up , Allow access to the Internet , If you're not an adult ? Should we reply that users can't access the Internet ?

4.1 grammar

if Conditions :
Conditional execution code 1
Conditional execution code 2
……
else:
Code executed when the condition does not hold 1
Code executed when the condition does not hold 2
……

4.2 Utility version : Internet cafes surf the Internet

age = int(input(" Please enter your age :"))
if age >= 18:
print(f' The age you entered is {age}, Has reached adulthood , You can go online ')
else:
print(f' The age you entered is {age}, Children , Go home and do your homework ')

Be careful : If some conditions are true, the relevant code is executed , In other cases, the code interpreter will not execute

5、 Multiple judgments

reflection : The legal working age in China is 18~60 year , That is, if the age is less than 18 Child labor at the age of , illegal ; If the age is 18~60 The legal length of service is between two years old ; Greater than 60 The legal retirement age is 15 years old .

5.1 grammar

if Conditions 1:
Conditions 1 Set up the code to execute 1
Conditions 1 Set up the code to execute 2
……
elif Conditions 2:
Conditions 2 Set up the code to execute 1
Conditions 2 Set up the code to execute 2
……
……
else:
None of the above conditions holds. The executed code 

Multiple judgments can also be related to else In combination with . commonly else Put it all over if At the end of the sentence , Indicates the code to be executed when none of the above conditions is true .

age = int(input(" Please enter your age :"))
if age < 18:
print(f" The age you entered is {age}, Child labor ")
elif (age >= 18) and (age <= 60): # perhaps elif 18<=age<=60:
print(f" The age you entered is {age}, legal ")
elif age > 60:
print(f' The age you entered is {age}, retired ')

6、if nesting

reflection : By bus : If you have money, you can get on the bus , You can't get on the bus without money ; When you get on the bus, if you have a seat available , You can sit down ; If there are no empty seats , It's about standing . How to write a program ?

6.1 grammar

if Conditions 1:
Conditions 1 Set up the code to execute 1
Conditions 1 Set up the code to execute 2
……
if Conditions 2:
Conditions 2 Set up the code to execute 1
Conditions 2 Set up the code to execute 2
……

Be careful : Conditions 2 Of if Also out of conditions 1 Inside the indent relationship

6.2 example : By bus

money = 1
seat = 0
if money == 1:
print(" Local tyrants , Please get in the car ")
if seat == 1:
print(" There are vacant seats , Sit down ")
else:
print(" There are no empty seats , Stand and wait ……")
else:
print(" friend , No money , Run with me , Run faster ")

7、 Three eye algorithm

Ternary operators are also called ternary operators or ternary expressions .

7.1 grammar

 If the condition is true, the expression of execution if Conditions else An expression executed when the condition is not true .

Quick experience :

a = 1
b = 2
c = a if a > b else b
print(c)

summary

  • if Sentence syntax

if Conditions :
Conditional execution code 
  • if……else……

if Conditions :
Conditional execution code
else:
Code executed when the condition does not hold 
  • Multiple judgments

if Conditions 1:
Conditions 1 Set up the code to execute
elif Conditions 2:
Conditions 2 Set up the code to execute
else:
None of the above conditions holds. The executed code 
  • if nesting

if Conditions 1:
Conditions 1 Set up the code to execute
if Conditions 2:
Conditions 2 Set up the code to execute
……
  • Ternary operator

 If the condition is true, the expression of execution if Conditions else An expression executed when the condition is not true 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved