current position:Home>At the beginning of "Python", you must see the series. 10000 words are only for you. It is recommended to like the collection ~

At the beginning of "Python", you must see the series. 10000 words are only for you. It is recommended to like the collection ~

2021-08-23 09:35:55 It's dream

 Insert picture description here

Hello, Dear friends , Everybody, morning, noon and Good evening ! In fact, I have long wanted to update a more comprehensive Python Basic knowledge , All right, borrow C Stand in the first issue of the list of Heroes This activity , Take everything I've learned Python The basic grammar and conditional branches have been sorted out !️️️ Don't worry , After you like the collection, unlock the full text ~
 Insert picture description here

Did you like it today ~ Everybody sit in the front row :
 Insert picture description here

Basic grammar :

One . Introduction to grammar

1. Basic grammar

Python Single line comments in the are marked with # start !

#  The first note 
print (“Hello, Python!”)  #  The second note 

Multiline comments can start and end with three quotation marks :

""" print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) """

python The most distinctive feature is the use of indentation to represent code blocks :
 Insert picture description here
Python It's usually a sentence written one line at a time , But if the sentence is long , We need a new line , You can use \ To achieve .

2. Variables and assignments

Python Variables in are used to store data , Variables can be understood as shopping baskets in supermarkets , Its type and value are initialized at the moment of assignment .

#num1 and num2 Variables are like a small basket , The data they store is 100 and 87.
#result The data stored in variables is num1 and num2 these two items. “ Vegetable basket ” The cumulative sum of data in .
num1 = 100 
num2 = 87 
result = num1 + num2

The type of variable :
Numeric type ( integer , Replica , floating-point )
Boolean type
String type
List the type
A tuple type
Dictionary type
aggregate

3. identifier

If you want to represent something in a program , Developers need to customize some symbols and names , These symbols and names are called identifier .
Naming rules :

  1. The designator consists of the letters 、 Underline and numbers make up , And the number can't start .
  2. Python Identifiers in are case sensitive .
  3. python The identifier in cannot use the keyword

To standardize the naming of identifiers , The following suggestions are made on the naming of identifiers :

  1. See the meaning of the name
  2. Hump type
     Insert picture description here

Keywords refer to identifiers with special functions :

>>> help()               #  Enter the help system 
help> keywords       #  View a list of all keywords 
help> return             #  see return Description of this keyword 
help> quit                #  Exit the help system 

4. Simple numeric type

1. Integer types (int) It's called integer for short , It's used to represent integers .
2. floating-point (Float) Used to represent real numbers . Floating point literals can be expressed in decimal or scientific notation .E or e Indicates that the base is 10, The following integer represents the exponent , The positive and negative use of the index + or - Express .
3. Boolean type Boolean data has only two values :True and False
bool No operation , All the emptiness is False, All non emptiness is True

a = 0 #  Integers 0,False 
print(bool(a)) s = "" #  An empty string ,False 
print(bool(s)) lst = [] #  An empty list ,False 
print(bool(lst)) dic = {
    } #  An empty dictionary ,False 
print(bool(dic)) a = None # None Said empty ,False 
print(bool(a)) 

 Insert picture description here

5. Operator

1. Arithmetic operator :
 Insert picture description here
2. Assignment operator : There is only one assignment operator , namely =, Its function is to assign the value to the right of the equal sign to the left . for example ,x=1
3. Comparison operator :
 Insert picture description here

4. Logical operators : Insert picture description here
5. Compound assignment operator
 Insert picture description here

6. Operator priority

 Insert picture description here

7. character string

A string is a type that represents text data .

‘a’ 、'123'# Use single quotes 
“a”、"123" # Use double quotes 
# Use three quotes 
""" Hello """

Escape character :
 Insert picture description here
Formatted output of string :

name = ' Xiao Ming ‘
age = 5
print(" Hello everyone , My name is %s , I this year %d Year old "%(name,age))

 Insert picture description here
Input of string :
Python3 Provides input() Function reads a line of text from standard input , The default standard input is the keyboard .input Can receive a Python Expression as input , And return the result to .

username=input(" Please enter a user name ")
print(username)

String built-in functions :

upper: Convert lowercase letters to uppercase letters
ljust: Align left , Fill a new string with spaces to the specified length
center: Returns a specified width width Centered string
lstrip: Truncates the space to the left of the string or specifies the character
rstrip: Truncate the space to the right of the string or the specified character
strip: Truncate the space on the left and right sides of the string or the specified character

Two .Python Common sentences

1. Judgment statement

1.if sentence :
if Statement is the simplest conditional judgment statement , It can control the execution process of the program .
2. if-else sentence

if  Conditions :
         What to do when conditions are met 1
        ...( Omit )...
    else:
         What to do when conditions are not met 1

3.if nesting :
if Nesting refers to nesting in if perhaps if-else The statement contains if perhaps if-else.

 if  Conditions 1:
         Meet the conditions 1  Do the things 1
         Meet the conditions 1  Do the things 2
        ...( Omit )...
        if  Conditions 2:
             Meet the conditions 2  Do the things 1
             Meet the conditions 2  Do the things 2
            ...( Omit )...

2. Loop statement

1.while loop :

while  Conditional expression :
      Conditions met , Execute loop statement 

The conditional expression is always true, Infinite loop .
2.for loop :

for i in [0,1,2]:   
	print(i)

Considering that the range of values we use often changes ,Python Provides a built-in range() function , It can generate a sequence of numbers .

for i in range(start,end):
      Execute loop statement 

3.while nesting
while Nesting means while The loop also contains while loop .

 while  Conditions 1:
         Conditions 1 When satisfied , Do the things 1
         Conditions 1 When satisfied , Do the things 2
         Conditions 1 When satisfied , Do the things 3
        ...( Omit )...
        while  Conditions 2:
             Conditions 2 When satisfied , Do the things 1
             Conditions 2 When satisfied , Do the things 2
             Conditions 2 When satisfied , Do the things 3
            ...( Omit )...

3.Python Other statements for

1.break sentence
break Statement is used to end the entire loop .

i=1
for i in range(5):
     i+=1
     print("-------")
     if i==3:
         break
     print(i)

2.continue sentence
continue The function of is to end this cycle , And then the next cycle .

i=1
for i in range(5):
     i+=1
     print("-------")
     if i==3:
         continue
     print(i)

3.pass sentence
pass It's an empty statement , It is to maintain the integrity of the program structure .

for letter in 'Runoob': 
   if letter == 'o':
      pass
      print (' perform  pass  block ')
   print (' The current letter  :', letter)
print ("Good bye!")

4.else sentence
else Statements can be used in conjunction with loop statements , also else Statement is intended to execute after the loop is completed .

count = 0	
	while count < 5: 		
		print(count, " is less than 5") 		
		count = count + 1 	
	else:  		
		print(count, " is not less than 5")

3、 ... and . list Tuples Dictionaries

1. list :

The list is Python A data structure in , It can store different types of data .

A = [1,'xiaoWang','a', [2, 'b']]

The list index is from 0 At the beginning , We can access the values in the list by subscript index :

A = ['xiaoWang', 'xiaoZhang', 'xiaoHua']
print(A[0])
print(A[1])

There are many ways to add elements to the list , As follows :

  1. adopt append You can add elements... To the list
  2. adopt extend You can add elements from another list to the list .
  3. adopt insert At a designated location index Insert element before object.

There are three common ways to delete list elements , As follows :

  1. del: Delete according to subscript
  2. pop: Delete the last element
  3. remove: Delete based on the value of the element

The sorting of the list can be realized by the following two methods :

  1. sort Method : The elements of the list are arranged in a specific order .
  2. reverse Method : Invert the list .

2. Tuples

Python A tuple of is similar to a list , The difference is that the elements of a tuple cannot be modified . Tuples use braces , Use square brackets for lists .

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"

Tuples cannot be modified :

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz')
#  The following operation to modify tuple elements is illegal .
tup1[0] = 100

3. Dictionaries

A dictionary is a container for storing data , It's like a list , Can store multiple data .

 info = {
    'name':' Monitor of the class ', 'sex':'f', 'address':' Beijing '}

If we are not sure whether a key exists in the dictionary and want to get its value , have access to get Method , You can also set default values .

info = {
    ‘name’:‘ Monitor of the class ’,id:100, ‘sex’:‘f’, ‘address’:‘ Beijing ’}
age = info.get(‘age’)
print(age) #‘age’ The key doesn't exist , therefore age by None
print(type(age))
age = info.get(‘age’, 18) #  if info non-existent ‘age’, Return default 18
print(age)

1. Modify the elements of the dictionary :

info = {
    ‘name’:‘ Monitor of the class ’,id:100, ‘sex’:‘f’, ‘address’:‘ Beijing ’}
newId = input(' Please enter a new student number ')
info['id'] = int(newId)
print(' Modified id by :%d'%info['id'])

2. Add dictionary elements :

info = {
    ‘name’:‘ Monitor of the class ’,id:100, ‘sex’:‘f’, ‘address’:‘ Beijing ’}
newId = input(‘ Please enter a new student number ’)
info[id] = newId
print(info)

3. Delete dictionary elements :
del: Used to delete a dictionary ; After deleting , The dictionary doesn't exist at all , Can no longer ACCESS Dictionary values by key .
clear: Just empty the data in the dictionary , The dictionary still exists , Just no elements .

Four . function

Python Define function use def keyword , The format is as follows :

def  Function name ( parameter list ):
     The body of the function 

This is a custom function :

def printInfo():
    print('------------------------------------')
    print('  Life is short , I use Python ')
    print('------------------------------------')

After defining the function , Want this code to execute , You need to call the function . adopt “ Function name ()” To complete the call :

#  Call the function just defined 
printInfo()

If you want to define a function , You can calculate any two numbers and , When we define a function , Let the function receive data , This is the argument to the function .

def add2num(a, b):
    c = a+b
   print(c)

local variable :
So called local variables , It's a variable defined inside a function .
The scope of a local variable is within a function , Means that it is only valid in the function that defines it , Once the function ends, it disappears .
Global variables :
Define a global scope outside the function .
Global variables can be accessed throughout the program .
If the names of global variables and local variables are the same , Then what is accessed in the function is the local variable .
Recursive function :
The interior of a function can call other functions . however , If a function does not call other functions inside , It's what I say , This function is a recursive function .

def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)
Fact(5)
120
5*4*3*2*1

Anonymous functions :
Anonymous functions are functions without names , That is, no longer use def Function defined by statement . If you want to declare anonymous functions , You need to use lambda keyword , The declaration format of anonymous functions is as follows :

sum = lambda arg1, arg2: arg1 + arg2
print(“ Running results :", sum( 10, 20 ))
print(" Running results :", sum( 20, 20 ))
# Be careful : Use Lambda The declared anonymous function can accept any number of parameters ,
# But only the value of one expression can be returned . Anonymous functions cannot call directly print,
# because lambda We need an expression .

Conditional branch :

In fact, the conditions and branches involved here , In the basic grammar above Python Statements involve , Here we make a further summary :

One . Single branch structure :

if Conditions :
Conditional execution code

# Single branch structure example 
print(" Start code exercises ")
num = int(input(" Please enter an integer :"))
if num >=0:
    print(" The integer is a positive number .")
print(" Program end ")

Two 、 Two branch structure

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

#  Two branch structure   Judge whether a number is even 
x = int(input(" Please enter an integer :"))
if x % 2 == 0 :
    print(" This is an even number ")
else:
    print(" This is a singular number ")

3、 ... and 、 Multi branch structure

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

#  Multi branch structure example 
score = int(input(" Please enter your score :"))
if score == 100:
    print(" sanya 7 Day tour , Cool, dropping !")
elif score >= 95 and score < 100:
    print(" Buy a new cell phone , The king is very smooth ~")
elif score >= 90 and score < 95:
    print(" Watch a movie and reward yourself ")
elif score >= 80 and score < 90:
    print(" Don't worry , Make persistent efforts ")
else:
    print(" Drag out for a meal ")
print(" end "

Four 、 Nested structure

if Conditions 1:
# Conditions 1 by True When entering
else:
# Conditions 3 by False When entering
Code block 4…
else:
# Conditions 1 by False When entering
Code block 2…

#  Nested structure example 
x = int(input(" Please enter an integer :"))
if x >= 0 :
    if x % 2 == 0:
        print(" This number is even ")
    else:
        print(" This number is odd ")
else:
    print(" This number is negative ")

The last little benefit to everyone : If you want to get started quickly python My friends , This is sorted out in detail PPT Can quickly help everyone to fight python Basics , You can download it if you need it Python A complete set of introductory basic tutorials + Xiaobai Express + You won't come to me !
All right. , That's all I want to share with you today
️️️ If you like , Don't be stingy with your one key triple connection ~ Insert picture description here

copyright notice
author[It's dream],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2021/08/20210823093553178U.html

Random recommended