Python entry notes [basic grammar (below)]

Preface: This part is the focus of the basic grammar, and it is just a small step to get started with py.

Preview

table of Contents

  1. List modification find element
The main operation to modify the search element to the list is to add, delete, modify, and search
a=[1,2,3,4,5,6]print(a.index(5))Output 4, indicating that 5 is in this list, and the first occurrence of the subscript is 4.
For the index method, if the element to be searched appears multiple times in the list, the first occurrence of the subscript is displayed, and the search element must be in the list when searching, otherwise an error will be reported
value=a[1]print(value)print(a.count(2))#The count method means to find the number of occurrences of the specified element. Unlike the index method, if the element to be found does not appear, zero will be output and no error will be reported.
A little trick
e.g a=["on Monday","on Tuesday","on Wednesday","Thursday","on Saturday","Friday","Sunday"]
# Obviously the positions of Saturday and Friday in the list are reversed, we need to swap them now
a[4],a[5]=a[5],a[4] #This operation can be done, which is different from C language expression
Assignment can also be like this
a,b,c=1,2,3
s="on Monday,on Tuesday,on Wednesday,Thursday,on Saturday,Friday,Sunday"
a=s.split(",")print(a)#The formed a is a list, so that the string is converted to a list
# We can also convert the list into a string
a1="*".join(a) #The filler that can be connected in front can be filled in, if it is not filled in, "", please note that all elements in the a list must be of the same type when using the join method
print(a1)
  1. Add and delete elements
Add elements
a=[1,2,3,4]
a.append(5)#Add the specified element to the end of the list, but note that only one element can be inserted at the end
a.insert(3,2.45) #The insert method has two parameters. The first is the position to insert, and the second is the inserted content. After the insertion is successful, the original position and subsequent elements move backward.
In addition, the first parameter can also exceed the length of the list-1. In this case, the system is inserted at the end by default, such as-x,x>The length of the list is quite inserted in the head
a.extend([5,6,7])#Means append a new list at the end[5,6,7]
Such as b=[5,6,7]  a.extend(b)That's OK
You can also append the string s, for example
s="hello"
a.extend(s)#At this time, appended to the end is the output result of each element of the string split[1,2,3,4,'h','e','l','l','o']
Yes, if you don’t want this, you want to insert hello into the list as an independent element
a.extend([s])#Output[1,2,3,4,'hello']print(a)
  1. Introduction to Tuples
Introduction to Tuples
Tuples are also an ordered container like lists
Also use subscripts to index elements
Can also intercept
But it is an immutable type
a=(1,2,3)print(type(a))#<class'tuple'>
But only one element in the tuple should be expressed like this
b=1,
Or b=(1,)#Note and b=(1)The latter system will treat the brackets as an increase in priority
The following are some common operations for tuples:
a1=a*3print(a1)print(len(a1))print(4in a1)print(max(a))print(min(a))print(a1.count(3))Output separately:(1,2,3,1,2,3,1,2,3)9
False
313
But a[x]=xx,a.append(),a.remove()Operation
In addition, tuples support this assignment operation
t=(1,2,3)
a,b,c=t
print(f"t={t},a={a},b={b},c={c}")
# Output: t=(1,2,3),a=1,b=2,c=3
Recall the two variable assignment operations in the beginning of the past:
a,b=b,a
Similar to the list:
t[0],t[1]=t[1],t[0]print(t)
But tuples do not support this operation
  1. List nesting
List nesting
Any type of element can be stored in List
The integer decimal bool value can also be a list type, which is equivalent to a large box with several small boxes
e.g
stu1=["Xiao Ming",95]
stu2=["Xiao Hong",86]
stu3=["Xiao Wang",68]
stu=[stu1,stu2,stu3]#[['Xiao Ming',95],['Xiao Hong',86],['Xiao Wang',68]]
Or declare it like this:
stu=[["Xiao Ming",95],["Xiao Hong",86],["Xiao Wang",68]]print(stu)print(stu[0][0])#Xiao Ming
print(f"{stu[0][0]}The scores are:{stu[0][1]}")#小明The scores are:95
  1. List simple exercise
List exercise
1. Create a list of 10 elements, the value is[30,31,30,31...]
l=[30,31]*52.Delete the element with subscript 0
l.pop(0)3.Change the value of the element with subscript 1 to 28
l[1]=284.Insert an element 31 at the position of the subscript 7
l.insert(7,31)5.Append 2 elements to the end of the list: 30,31
l.extend([30,31])
The final result should be[31,28,31,30,31,30,31,31,30,31,30,31]print(l)#[31,28,31,30,31,30,31,31,30,31,30,31]
Prompt the user to enter a 1~The integer value between 12 represents the month, and then the console displays the number of days in the month entered by the user
For example, if the number entered by the user is 7, it will display &quot;31 days in July&quot;
month=input("Please enter a 1~An integer value between 12 represents the month:")
month=int(month)print(f"{month}Month has{l[month-1]}day")
This question can also use if elif statement
  1. Range method
Range method
l=list(range(x))Indicates that the generation starts from 0 to x-1 consecutive list
range(end)Generate 0-integer between end, not including end
range(start,end)Generate start-integer between end, not including end
range(start,end,step)Generate start-integer between end, not including end,And generate a number every step number
l=list(range(1,101))
t=tuple(l)print(f"The type of l is:{type(l)}\n{l}")print(f"The type of t is:{type(t)}\n{t}")
The type of l is:<class'list'>[1,2,3,4,5,6,7,8,9,....,100]
The type of t is:<class'tuple'>(1,2,3,4,5,6,7,8,9,....)
l=list(range(1,100,2))#Represents 1-All odd numbers of 100
  1. List traversal
List traversal
Traverse: take out each element in turn
for...in..for item in l:print(item)Tuple, string, range()Can use for to traverse
l=list(range(101))for item in l:print(item)#Output 1 in turn-100
 l=list(range(101))for item in"Python":print(item)#Output P ython in turn
  1. For loop & For exercise
for practice
1. Prompt the user to enter 5 numbers to form a list
l=[]for i inrange(5):
 num=input(f"Please enter the{i+1}Number:")
 num=int(num)
 l.append(num)print(f"The five numbers entered are:{l}")
Output:
Please enter the first number: 1
Please enter the second number: 2
Please enter the third number: 3
Please enter the fourth number: 4
Please enter the 5th number: 5
The five numbers entered are:[1,2,3,4,5]
The value of each element in the list*2for i inrange(len(l)):
 l[i]*=2print(f"The value of each element*2 new list:{l}")
Calculate the sum of all elements in the new list
sum=0for i inrange(len(l)):
 sum+=l[i]print(f"The sum of all elements in this new list is:{sum}")2.Find all multiples of 7 within 100 and numbers containing 7 and put them in a list
l=[]for i inrange(101):if i%7==0:
  l.append(i)else:
  temp=i
  while(temp):
   k=temp%10if(k==7):
    l.append(i)break
   temp/=10print(f"The elements that meet the conditions are placed in the list{l}")
The elements that meet the conditions are placed in the list[0,7,14,17,21,27,28,35,37,42,47,49,56,57,63,67,70,77,84,87,91,97,98]
  1. While loop
while loop
The simplest example:
i=0while i<10:print("balabala")
 i+=1
l=[]
i=''while  i!='q':
 i=input("Please enter the to-do list (deduct q to exit):")
 l.append(i)
l.pop()print(l)
Or declare like this:
while1:
 i=input("Please enter the to-do list (deduct q to exit):")if i=='q':break
 l.append(i)print(l)
An important difference between Python and C series languages:
for i inrange(4):
The system cannot tolerate your empty loop and will report an error. This is completely different from the C language, but if we only want to keep this loop (such as adding something in the future), we need to do this:
 pass #Can guarantee code integrity
  1. List comprehension
List comprehension
List comprehensions can quickly construct new data sequences
[ Expression for variable in list][Expression for variable in list if 筛选条件]
l1=[1,2,3,4,5]
l2=[i*2for i in l1]#Output[2,4,6,8,10] i*2 is the relationship between l1 and l2, that is, each element in l2 is twice as large as each corresponding element in l1
l2=[i for i inrange(10)if not i%2]#Output[0,2,4,6,8]
You can also convert the data types in the list like this:
l2=[str(i)for i inrange(10)]#Output['0','1','2','3','4','5','6','7','8','9']print(l2)
Since the string is also a sequence structure, we can also traverse the string
l=[i for i in'hello']#Output['h','e','l','l','o']
l=[i.upper()for i in'hello']#Output['H','E','L','L','O']
l=[i.upper()for i in'hello'if i!='h']#Output['E','L','L','O']print(l)
  1. Deductive exercise
Deductive exercise
1. Obtain['Food','Moon','Loop']The first letter of each element in the, and these three initial letters form a new string
l=['Food','Moon','Loop']
l1=[i[0]for i in l]print(l1)
s=''.join(l1)print(s)
operation result:
[' F','M','L']
FML
2. Find the elements that appear in both l1 and l2
l1=[2,4,6,8,10,12]
l2=[3,6,9,12]
l=[i for i in l1 if i in l2]print(l) #Output:[6,12]3.will[1,3,5,7,9]All elements in are printed on the console
l3=[1,3,5,7,9]
Solution one:[print(i)for i in l3]
Output:
13579
Solution 2:
for i in l3:print(i)
  1. Loop nesting
Loop nesting
The simplest example:
for i inrange(3):for j inrange(5):print(f"i={i},j={j}")
i=0,j=0 i=0,j=1 i=0,j=2 i=0,j=3 i=0,j=4 i=1,j=0 i=1,j=1 i=1,j=2 i=1,j=3 i=1,j=4
i=2,j=0 i=2,j=1 i=2,j=2 i=2,j=3 i=2,j=4
Create a two-dimensional list
l=[]for i inrange(3):
 item=[]
 l.append(item)for j inrange(5):
  item.append(j)print(l)#[[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4]]
# Two-dimensional list element search:
for i in l:for j in i:print(j)#The result is output sequentially
# Routine is layer by layer
# Both of the above can be solved with one line each of the list comprehension:
l1=[[j for j inrange(5)]for i inrange(3)]print(l1)#[[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4]][[print(j)for j in i]for i in l]#012340123401234
  1. Loop exercise
Loop exercise
1. 100 found-The smallest number of daffodils within 1000 (number of daffodils: the sum of the power of 3 of each number is equal to itself)
for i inrange(100,1001):
 a=i%10
 b=i//10%10
 c=i//100%10if a**3+b**3+c**3==i:print(f"{i}Is 100-Number of daffodils within 1000")
Output:
153 Is 100-Number of daffodils within 1000
370 Is 100-Number of daffodils within 1000
371 Is 100-Number of daffodils within 1000
407 Is 100-Number of daffodils within 1000

2. Find all prime numbers within 100 and store them in the list:
l=[]for i inrange(2,101):
 is_prime=True
 j=2while(j*j<=i):if i%j==0:
   is_prime=False
  j+=1if(is_prime):
  l.append(i)print(l)#[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]3.Print nine-nine multiplication table
for i inrange(1,10):for j inrange(1,10):print(f"{i}*{j}={i*j:2d}",end=' ')#Format note: every space, a number on a line, and ensure that the final result is aligned,we use:{i*j:2d}print("")1*1=11*2=21*3=31*4=41*5=51*6=61*7=71*8=81*9=92*1=22*2=42*3=62*4=82*5=102*6=122*7=142*8=162*9=183*1=33*2=63*3=93*4=123*5=153*6=183*7=213*8=243*9=274*1=44*2=84*3=124*4=164*5=204*6=244*7=284*8=324*9=365*1=55*2=105*3=155*4=205*5=255*6=305*7=355*8=405*9=456*1=66*2=126*3=186*4=246*5=306*6=366*7=426*8=486*9=547*1=77*2=147*3=217*4=287*5=357*6=427*7=497*8=567*9=638*1=88*2=168*3=248*4=328*5=408*6=488*7=568*8=648*9=729*1=99*2=189*3=279*4=369*5=459*6=549*7=639*8=729*9=81
  1. Dictionary basics
The dictionary-based variable container type stores keys in key-value pairs-the keys in the value dictionary must be unique and cannot be repeated
d={}print(d,type(d))#{}<class'dict'>
d={"Beijing":22,"Shanghai":24}#Normal statement
d={"Beijing":22,"Beijing":24} #Error statement
The keys in the dictionary must be immutable# l=[0,1,2] a={l:22}error
Check print(d["Beijing"])#Output 22
Change d["Beijing"]=20 
Increase d["Guangzhou"]=23
Delete d.pop("Beijing")You can use variables to receive
value=d.pop("Beijing")
value=key("Beijing")
Finding the value corresponding to a key in the dictionary does not rely on the so-called subscript but is searched by the key, so there is no so-called order in the dictionary
If you want to add multiple elements to the dictionary at once, you can use the update method
d.update({"xx":"xx"}) #{'Beijing':22,'Shanghai':24,'xx':'xx'}
If the element to be added in the update method is already existing, then the corresponding value is updated incidentally (that is, the new value in the update
print(d)
v=d.pop("aa",-1)print(v)#The second parameter means that if the first parameter to be deleted is not in the dictionary, assign the second parameter to v and output v=-1
The same operation has the following two variants
name=d.get("aa",-1)#The second parameter means that if the first parameter to be obtained is not in the dictionary, assign the second parameter to name and output name=-1
What are the benefits? The advantage is: if the key to find is not in the dictionary, the program will not crash
Furthermore, we have:
name=d.setdefault("aa",-1)#The second parameter means that if the first parameter to be deleted is not in the dictionary, assign the second parameter to name and output name=-1
And add a new key-value pair in the dictionary: &quot;aa&quot;:-1#Output:{'Beijing':22,'Shanghai':24,'aa':-1}print(d)
d.clear()print(d)#Output{}
You can look at the entire dictionary as a large string, with one of the following usages:
print("aaa"+str(d))#Output: aaa{'Beijing':22,'Shanghai':24}
You can determine whether a key is in the dictionary:
print("aa"in d)#Output False, please note that the first parameter &quot;aa&quot; can only be a key
The initialization of the dictionary can be written in separate lines:
c={"aa":1,"bb":2}#Output:{'aa':1,'bb':2}print(c)
Note: I said before that the key of the list must be immutable, so the list cannot be used as the key of the dictionary, but the list can be used as the value of the dictionary
  1. Dictionary traversal
Dictionary traversal
The concept of an iterable object: Allows to get only one element at a time, you can use for to traverse
s=dict(a=1,b=2,c=3)for i in s:print(f"key={i},value={s[i]}")
Output:
key=a,value=1
key=b,value=2
key=c,value=3
There are three ways:
for i in s.keys():print(f"key={i}")
Output:
key=a
key=b
key=c
for i in s.values():print(f"value={i}")
Output:
value=1
value=2
value=3
# The above two ways i represents the key of s and the value of s
The third traversal method:
for k,v in s.items():print(f"key={k},value={v}")
Output:
key=a,value=1
key=b,value=2
key=c,value=3
l=list(s.keys())print(l)
t=tuple(s.values())print(t)
Output:
[' a','b','c'](1,2,3)
Examples of dictionary and list or dictionary nesting:
s=dict(a=[1,2,3],b={"1":100,"2":200},c=3)print(s)#{'a':[1,2,3],'b':{'1':100,'2':200},'c':3}print(s["b"]["1"]) #Output 100print(s["a"][2]) #Output 3
Note: Use if the first subscript is a list or dictionary""or''
The second subscript:
If it is a subscript of a list, do not use single or double quotes
For the dictionary, use
You can refer to the two examples I gave

Finally present all the source code

import math

# my_string="hello world!"
# print(int(len(my_string)))  #Output string length
# index=my_string.find("888")
# print(int(index))  #If the substring matches in the original string, return the subscript of the first character in the original string, and report an error if the system is not found
# c=my_string.count("l")
# print(c)  #Record the number of times the substring is found, or zero if it does not appear
# new_string=my_string.replace("ello","*") #Two parameters, the first is the character to be changed, the second is the character to be changed
# print(new_string)
# print("h"in my_string) #in can indicate whether a string is included in the original string, the return value is Boolean true or false
# print("h" not in my_string)  #Also not in
# my_string="123,456,789"
# sub_my_string=my_string.split(",")
# print(sub_my_string) #Split means split, the meaning of the parameter in brackets is the split flag sub_my_string=["123","456","789"],List type

# F-String(python 3.6+)
# name ='Pharaoh'
# age=18
# result="Hello there"+name+","+"You already this year"+str(age)+"Years old!"
# result=f"Hello there{name}, You have already{age}Years old!"  #python3.Available only after version 6

# format()
# result="Hello there{0}, You have already{1}Years old!".format(name,age)

# %(Deprecated)
# result="Hello there%s,You already this year%d years old!"%(name,age)
# [( filling)Align][symbol][width][.Precision][Types of]<左Align,>右Align,^ 居中Align 
# pi=255
# Expressed as a percentage system
# result=f"PI{pi:#x}Is an infinite non-recurring decimal"
# Expressed as a value in other bases
# print(result)

# The result of the relational operation is a bool value
'''
a=1
result=a==6print(result)'''
# print(12=="12")
# print('a'>'A')
# 012.....< A B C ......Z<a b c d ..... z

# print(True or False)
# print(not 2>1)'''
html="""
< html><head></head></html>"""
print(html)'''

'''
priority
1.**2.* /%//3.+-4.><>=<===!=5.and or not
6.='''

# result=1+2**2*3>=12-4/2 and 'Apple'>='Car' 
# print(result)
# false

 # if statement practice
'''
It is required to realize that the user inputs a number from the terminal and receives it, and judges whether it is an even number
'''
'''
num=(input("Please enter an integer:"))
num=int(num)if num%2==0:print(f"The number you entered is{num}, It is an even number")if num %3==0:print(f"{num}It can also be divisible by 3!")else:print(f"{num}Not divisible by 3.")else:print(f"The number you entered is{num}, It is an odd number")print("End")'''

# elif statement practice
# score=input("Please enter a score(0-100)")
# if  score.isdigit():  #Determine whether the string is composed of numbers, if it is, return true elsefalse
#  score=int(score)

#  Determine grade based on score
#  100 S
#  90- 99 A
#  80- 89 B
#  70- 79 C     
#  60- 69 D  
#  0- 60 E  

#  if0<=score<=100:
#   if score==100:
#    print("S")
#   elif score>=90:
#    print("A")
#   elif score>=80:
#    print("B")
#   elif score>=70:
#    print("C")
#   elif score>=60:
#    print("D")
#   else:
#    print("E")
# else:
#  print("You made a mistake!")

# # Prompt the user to enter a month to determine if the year is a leap year
# year=input("Please enter a valid year:")
# if year.isdigit():
#  year=int(year)
#  if(year%400==0or(year%4==0 and year%100)):
#   print(f"{year}It&#39;s a leap year!")
#  else:
#   print(f"{year}It&#39;s normal years!")

# # Prompt the user to enter a 1-Integer between 99999, display the value of each digit of this number in turn(From small to large)
# num=input("Please enter a valid number:")
# if num.isdigit():
#  num=int(num)
#  while(num):
#   print(num%10)
#   num//=10

# Design a rock-paper-scissors guessing game
# 1- stone
# 2- scissors
# 3- cloth
# import random #Generate random numbers
# system_number=random.randint(1,3)
# user_number=input("Please enter a valid value:\n1.scissors\n2.stone\n3.cloth")
# user_number=int(user_number)
# if(user_number==system_number):
#  print(f"system_number is{system_number},your number is{user_number},draw")
# else:
#  if((user_number>system_number and  not(system_number==1 and user_number==3))or(system_number==3 and user_number==1)):
#   print(f"system_number is{system_number},your number is{user_number},you win!")
#  else:
#   print(f"system_number is{system_number},your number is{user_number},you lose!")

# a=[] #Empty list, list is the most basic data structure in python
# The list index starts from zero, use the index to get the element my_list[x]
# Also supports negative subscript my_list[-1]
# can use[start:end:step]Intercept the list my_list[1:4:1]Indicates to intercept the list from one to four, with a step size of one
# b=[1,3.14,"h",True] #The first letter of the Boolean value True should be capitalized, the same is true for False
# print(type(b))  #<class"list">
# Understand a major difference between strings and lists: strings are immutable and do not support modification operations, but lists can
# eg.
# c="hello"
# c[0]="k"#Error, string is immutable
# b[0]="hi"
# print(b) #Console output['hi',3.14,'h', True]
# The method of outputting a list in reverse order is the same as outputting a string in reverse order
# print(b[::-1])

# a=[1,2,3,4]
# if5in a:
#  print(f"{a}Contains this element")
# else:
#  print(f"{a}There is no such element")
# Positive index of the last element in the list: list length-1
# count=len(a)
# print(count)
# b=["a","b","c"]  #List merge operation
# new_list=a+b
# print(new_list)
# c=a*3
# print(c) #Output[1,2,3,4,1,2,3,4,1,2,3,4]
# List reverse operation: two methods
# 1. Can print(a[::-1])
# 2. a.reverse
# e.g
# a.reverse() #Not reverse(a)
# print(a) #Note a.reverse does not require new variables to receive!
# max_value=max(a),min_value=min(a)#Get the largest element in the list: Of course, the premise is that the list elements are the same type of value, like integer, floating point, of course, all strings can also be compared
# Sort the list
# a.sort() 
# print(a) #Sort the list: Of course, the premise is that the list elements are the same type of values, like integers, floating point types, and of course all strings can also be compared
# Such as variable name.()We are used to calling methods
# Such as a.sort(),a.reverse()
# The other is len(a),min(a),max(a)We call it a function

# The main operation to modify the search element to the list is to add, delete, modify, and search
# a=[1,2,3,4,5,6]
# print(a.index(5))Output 4, indicating that 5 is in this list, and the first occurrence of the subscript is 4.
# For the index method, if the element to be searched appears multiple times in the list, the first occurrence of the subscript is displayed, and the search element must be in the list when searching, otherwise an error will be reported
# value=a[1]
# print(value)
# print(a.count(2))#The count method means to find the number of occurrences of the specified element. Unlike the index method, if the element to be found does not appear, zero will be output and no error will be reported.
# A little trick
# e.g a=["on Monday","on Tuesday","on Wednesday","Thursday","on Saturday","Friday","Sunday"]
# # Obviously the positions of Saturday and Friday in the list are reversed, we need to swap them now
# a[4],a[5]=a[5],a[4] #This operation can be done, which is different from C language expression
# Assignment can also be like this
# a,b,c=1,2,3
# s="on Monday,on Tuesday,on Wednesday,Thursday,on Saturday,Friday,Sunday"
# a=s.split(",")
# print(a)#The formed a is a list, so that the string is converted to a list
# # We can also convert the list into a string
# a1="*".join(a) #The filler that can be connected in front can be filled in, if it is not filled in, &quot;&quot;, please note that all elements in the a list must be of the same type when using the join method
# print(a1)

# Add elements
# a=[1,2,3,4]
# a.append(5)#Add the specified element to the end of the list, but note that only one element can be inserted at the end
# a.insert(3,2.45) #The insert method has two parameters. The first is the position to insert, and the second is the inserted content. After the insertion is successful, the original position and subsequent elements move backward.
# In addition, the first parameter can also exceed the length of the list-1. In this case, the system is inserted at the end by default, such as-x,x>The length of the list is quite inserted in the head
# a.extend([5,6,7])#Means append a new list at the end[5,6,7]
# Such as b=[5,6,7]  a.extend(b)That&#39;s OK
# You can also append the string s, for example
# s="hello"
# a.extend(s)#At this time, appended to the end is the output result of each element of the string split[1,2,3,4,'h','e','l','l','o']
# Yes, if you don’t want this, you want to insert hello into the list as an independent element
# a.extend([s])#Output[1,2,3,4,'hello']
# print(a)

# Delete element
# a=[1,3,5,7,9]
# a.pop() #Output[1,3,5,7], Pop up the last element, this operation can also use variables to receive
# value=a.pop() #Output 9
# value=a.pop(2) #Represents the specified element with subscript 2 in the pop-up list
# You can also use variables to receive and pop up specific elements,
# But pay attention to a few points: 1.A unique parameter subscript is required, and the subscript you give cannot exceed the bounds, (negative subscripts can be used, such as a.pop(-1) Represents the last element to pop up)
# print(value)
# Delete elements can also use del operation
# del a[-2]#Means to delete the penultimate element, but the del operation does not support receiving with variables
# print(a)#Output[1,3,5,9]

# The dictionary-based variable container type stores keys in key-value pairs-the keys in the value dictionary must be unique and cannot be repeated
# d={}
# print(d,type(d))#{}<class'dict'>
# d={"Beijing":22,"Shanghai":24}#Normal statement
# d={"Beijing":22,"Beijing":24} #Error statement
# The keys in the dictionary must be immutable# l=[0,1,2] a={l:22}error
# Check print(d["Beijing"])#Output 22
# Change d["Beijing"]=20 
# Increase d["Guangzhou"]=23
# Delete d.pop("Beijing")You can use variables to receive
# value=d.pop("Beijing")
# value=key("Beijing")
# Finding the value corresponding to a key in the dictionary does not rely on the so-called subscript but is searched by the key, so there is no so-called order in the dictionary
# If you want to add multiple elements to the dictionary at once, you can use the update method
# d.update({"xx":"xx"}) #{'Beijing':22,'Shanghai':24,'xx':'xx'}
# If the element to be added in the update method is already existing, then the corresponding value is updated incidentally (that is, the new value in the update
# print(d)
# v=d.pop("aa",-1)
# print(v)#The second parameter means that if the first parameter to be deleted is not in the dictionary, assign the second parameter to v and output v=-1
# The same operation has the following two variants
# name=d.get("aa",-1)#The second parameter means that if the first parameter to be obtained is not in the dictionary, assign the second parameter to name and output name=-1
# What are the benefits? The advantage is: if the key to find is not in the dictionary, the program will not crash
# Furthermore, we have:
# name=d.setdefault("aa",-1)#The second parameter means that if the first parameter to be deleted is not in the dictionary, assign the second parameter to name and output name=-1
# And add a new key-value pair in the dictionary: &quot;aa&quot;:-1#Output:{'Beijing':22,'Shanghai':24,'aa':-1}
# print(d)
# d.clear()
# print(d)#Output{}
# You can look at the entire dictionary as a large string, with one of the following usages:
# print("aaa"+str(d))#Output: aaa{'Beijing':22,'Shanghai':24}
# You can determine whether a key is in the dictionary:
# print("aa"in d)#Output False, please note that the first parameter &quot;aa&quot; can only be a key
# The initialization of the dictionary can be written in separate lines:
# c={
#  " aa":1,
#  " bb":2
# }# Output:{'aa':1,'bb':2}
# print(c)
# Note: I said before that the key of the list must be immutable, so the list cannot be used as the key of the dictionary, but the list can be used as the value of the dictionary

# Dictionary traversal
# The concept of an iterable object: Allows to get only one element at a time, you can use for to traverse
# s=dict(a=1,b=2,c=3)
# for i in s:
#  print(f"key={i},value={s[i]}")
# Output:
# key=a,value=1
# key=b,value=2
# key=c,value=3
# There are three ways:
# for i in s.keys():
#  print(f"key={i}")
# Output:
# key=a
# key=b
# key=c
# for i in s.values():
#  print(f"value={i}")
# Output:
# value=1
# value=2
# value=3
# # The above two ways i represents the key of s and the value of s
# The third traversal method:
# for k,v in s.items():
#  print(f"key={k},value={v}")
# Output:
# key=a,value=1
# key=b,value=2
# key=c,value=3
# l=list(s.keys())
# print(l)
# t=tuple(s.values())
# print(t)
# Output:
# [' a','b','c']
# (1,2,3)
# Examples of dictionary and list or dictionary nesting:
# s=dict(a=[1,2,3],b={"1":100,"2":200},c=3)
# print(s)#{'a':[1,2,3],'b':{'1':100,'2':200},'c':3}
# print(s["b"]["1"]) #Output 100
# print(s["a"][2]) #Output 3
# Note: Use if the first subscript is a list or dictionary""or''
# The second subscript:
# If it is a subscript of a list, do not use single or double quotes
# For the dictionary, use
# See the two examples I gave above

# List comprehension
# List comprehensions can quickly construct new data sequences
# [ Expression for variable in list]
# [ Expression for variable in list if filter condition]
# l1=[1,2,3,4,5]
# l2=[i*2for i in l1]#Output[2,4,6,8,10] i*2 is the relationship between l1 and l2, that is, each element in l2 is twice as large as each corresponding element in l1
# l2=[i for i inrange(10)if not i%2]#Output[0,2,4,6,8]
# You can also convert the data types in the list like this:
# l2=[str(i)for i inrange(10)]#Output['0','1','2','3','4','5','6','7','8','9']
# print(l2)
# Since the string is also a sequence structure, we can also traverse the string
# l=[i for i in'hello']#Output['h','e','l','l','o']
# l=[i.upper()for i in'hello']#Output['H','E','L','L','O']
# l=[i.upper()for i in'hello'if i!='h']#Output['E','L','L','O']
# print(l)

# Deductive exercise
# 1. Obtain['Food','Moon','Loop']The first letter of each element in the, and these three initial letters form a new string
# l=['Food','Moon','Loop']
# l1=[i[0]for i in l]
# print(l1)
# s=''.join(l1)
# print(s)
# operation result:
# [' F','M','L']
# FML
# 2. Find the elements that appear in both l1 and l2
# l1=[2,4,6,8,10,12]
# l2=[3,6,9,12]
# l=[i for i in l1 if i in l2]
# print(l) #Output:[6,12]
# 3. will[1,3,5,7,9]All elements in are printed on the console
# l3=[1,3,5,7,9]
# Solution one:[print(i)for i in l3]
# Output:
# 1
# 3
# 5
# 7
# 9
# Solution 2:
# for i in l3:
#  print(i)

# Introduction to Tuples
# Tuples are also an ordered container like lists
# Also use subscripts to index elements
# Can also intercept
# But it is an immutable type
# a=(1,2,3)
# print(type(a))#<class'tuple'>
# But only one element in the tuple should be expressed like this
# b=1,
# Or b=(1,)#Note and b=(1)The latter system will treat the brackets as an increase in priority
# The following are some common operations for tuples:
# a1=a*3
# print(a1)
# print(len(a1))
# print(4in a1)
# print(max(a))
# print(min(a))
# print(a1.count(3))
# Output separately:
# (1,2,3,1,2,3,1,2,3)
# 9
# False
# 3
# 1
# 3
# But a[x]=xx,a.append(),a.remove()Operation
# In addition, tuples support this assignment operation
# t=(1,2,3)
# a,b,c=t
# print(f"t={t},a={a},b={b},c={c}")
# # Output: t=(1,2,3),a=1,b=2,c=3
# Recall the two variable assignment operations in the beginning of the past:
# a,b=b,a
# Similar to the list:
# t[0],t[1]=t[1],t[0]
# print(t)
# But tuples do not support this operation

# List nesting
# Any type of element can be stored in List
# The integer decimal bool value can also be a list type, which is equivalent to a large box with several small boxes
# e.g
# stu1=["Xiao Ming",95]
# stu2=["Xiao Hong",86]
# stu3=["Xiao Wang",68]
# stu=[stu1,stu2,stu3]#[['Xiao Ming',95],['Xiao Hong',86],['Xiao Wang',68]]
# Or declare it like this:
# stu=[
#  [" Xiao Ming",95],
#  [" Xiao Hong",86],
#  [" Xiao Wang",68]
# ]
# print(stu)
# print(stu[0][0])#Xiao Ming
# print(f"{stu[0][0]}The scores are:{stu[0][1]}")#小明The scores are:95

# List exercise
# 1. Create a list of 10 elements, the value is[30,31,30,31...]
# l=[30,31]*5
# 2. Delete the element with subscript 0
# l.pop(0)
# 3. Change the value of the element with subscript 1 to 28
# l[1]=28
# 4. Insert an element 31 at the position of the subscript 7
# l.insert(7,31)
# 5. Append 2 elements to the end of the list: 30,31
# l.extend([30,31])
# The final result should be[31,28,31,30,31,30,31,31,30,31,30,31]
# print(l)#[31,28,31,30,31,30,31,31,30,31,30,31]
# Prompt the user to enter a 1~The integer value between 12 represents the month, and then the console displays the number of days in the month entered by the user
# For example, if the number entered by the user is 7, it will display &quot;31 days in July&quot;
# month=input("Please enter a 1~An integer value between 12 represents the month:")
# month=int(month)
# print(f"{month}Month has{l[month-1]}day")
# This question can also use if elif statement

# Range method
# l=list(range(x))Indicates that the generation starts from 0 to x-1 consecutive list
# range(end)Generate 0-integer between end, not including end
# range(start,end)Generate start-integer between end, not including end
# range(start,end,step)Generate start-integer between end, not including end,And generate a number every step number
# l=list(range(1,101))
# t=tuple(l)
# print(f"The type of l is:{type(l)}\n{l}")
# print(f"The type of t is:{type(t)}\n{t}")
# The type of l is:<class'list'>
# [1,2,3,4,5,6,7,8,9,....,100]
# The type of t is:<class'tuple'>
# (1,2,3,4,5,6,7,8,9,....)
# l=list(range(1,100,2))#Represents 1-All odd numbers of 100

# List traversal
# Traverse: take out each element in turn
# for...in..
# for item in l:
#  print(item)
# Tuple, string, range()Can use for to traverse
# l=list(range(101))#Note: There can be no variable type list in the range
# for item in l:
#  print(item)#Output 1 in turn-100
#  l=list(range(101))
# for item in"Python":
#  print(item)#Output P ython in turn

# for loop
# forin loop through container type
# The simplest example:
# for item inrange(100):
#  print("hello,world!")
# sum=0
# for item inrange(1,101):
#  sum+=item
# print(sum)#Familiar 5050
# for item inrange(1,101):
#  if item %2==0:
#   sum+=item
# print(sum)#Familiar 2025

# for practice
# 1. Prompt the user to enter 5 numbers to form a list
# l=[]
# for i inrange(5):
#  num=input(f"Please enter the{i+1}Number:")
#  num=int(num)
#  l.append(num)
# print(f"The five numbers entered are:{l}")
# Output:
# Please enter the first number: 1
# Please enter the second number: 2
# Please enter the third number: 3
# Please enter the fourth number: 4
# Please enter the 5th number: 5
# The five numbers entered are:[1,2,3,4,5]
# The value of each element in the list*2
# for i inrange(len(l)):
#  l[i]*=2
# print(f"The value of each element*2 new list:{l}")
# Calculate the sum of all elements in the new list
# sum=0
# for i inrange(len(l)):
#  sum+=l[i]
# print(f"The sum of all elements in this new list is:{sum}")
# 2. Find all multiples of 7 within 100 and numbers containing 7 and put them in a list
# l=[]
# for i inrange(101):
#  if i%7==0:
#   l.append(i)
#  else:
#   temp=i
#   while(temp):
#    k=temp%10
#    if(k==7):
#     l.append(i)
#     break
#    temp/=10
# print(f"The elements that meet the conditions are placed in the list{l}")
# The elements that meet the conditions are placed in the list[0,7,14,17,21,27,28,35,37,42,47,49,56,57,63,67,70,77,84,87,91,97,98]

# while loop
# The simplest example:
# i=0
# while i<10:
#  print("balabala")
#  i+=1
# l=[]
# i=''
# while  i!='q':
#  i=input("Please enter the to-do list (deduct q to exit):")
#  l.append(i)
# l.pop()
# print(l)
# Or declare like this:
# while1:
#  i=input("Please enter the to-do list (deduct q to exit):")
#  if i=='q':
#   break
#  l.append(i)
# print(l)
# An important difference between Python and C series languages:
# for i inrange(4):
# The system cannot tolerate your empty loop and will report an error. This is completely different from the C language, but if we only want to keep this loop (such as adding something in the future), we need to do this:
#  pass #Can guarantee code integrity

# Loop nesting
# The simplest example:
# for i inrange(3):
#  for j inrange(5):
#   print(f"i={i},j={j}")
# i=0,j=0 i=0,j=1 i=0,j=2 i=0,j=3 i=0,j=4 i=1,j=0 i=1,j=1 i=1,j=2 i=1,j=3 i=1,j=4
# i=2,j=0 i=2,j=1 i=2,j=2 i=2,j=3 i=2,j=4
# Create a two-dimensional list
# l=[]
# for i inrange(3):
#  item=[]
#  l.append(item)
#  for j inrange(5):
#   item.append(j)
# print(l)#[[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4]]
# # Two-dimensional list element search:
# for i in l:
#  for j in i:
#   print(j)#The result is output sequentially
# # Routine is layer by layer
# # Both of the above can be solved with one line each of the list comprehension:
# l1=[[j for j inrange(5)]for i inrange(3)]
# print(l1)#[[0,1,2,3,4],[0,1,2,3,4],[0,1,2,3,4]]
# [[ print(j)for j in i]for i in l]#012340123401234

# Loop exercise
# 1. 100 found-The smallest number of daffodils within 1000 (number of daffodils: the sum of the power of 3 of each number is equal to itself)
# for i inrange(100,1001):
#  a=i%10
#  b=i//10%10
#  c=i//100%10
#  if a**3+b**3+c**3==i:
#   print(f"{i}Is 100-Number of daffodils within 1000")
# Output:
# 153 Is 100-Number of daffodils within 1000
# 370 Is 100-Number of daffodils within 1000
# 371 Is 100-Number of daffodils within 1000
# 407 Is 100-Number of daffodils within 1000

# 2. Find all prime numbers within 100 and store them in the list:
# l=[]
# for i inrange(2,101):
#  is_prime=True
#  j=2
#  while(j*j<=i):
#   if i%j==0:
#    is_prime=False
#   j+=1
#  if(is_prime):
#   l.append(i)
# print(l)#[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]

# 3. Print nine-nine multiplication table
# for i inrange(1,10):
#  for j inrange(1,10):
#   print(f"{i}*{j}={i*j:2d}",end=' ')#Format note: every space, a number on a line, and ensure that the final result is aligned,we use:{i*j:2d}
#  print("")
# 1*1=11*2=21*3=31*4=41*5=51*6=61*7=71*8=81*9=9
# 2*1=22*2=42*3=62*4=82*5=102*6=122*7=142*8=162*9=18
# 3*1=33*2=63*3=93*4=123*5=153*6=183*7=213*8=243*9=27
# 4*1=44*2=84*3=124*4=164*5=204*6=244*7=284*8=324*9=36
# 5*1=55*2=105*3=155*4=205*5=255*6=305*7=355*8=405*9=45
# 6*1=66*2=126*3=186*4=246*5=306*6=366*7=426*8=486*9=54
# 7*1=77*2=147*3=217*4=287*5=357*6=427*7=497*8=567*9=63
# 8*1=88*2=168*3=248*4=328*5=408*6=488*7=568*8=648*9=72
# 9*1=99*2=189*3=279*4=369*5=459*6=549*7=639*8=729*9=81

Acknowledgement:

NetEase Cloud Classroom:

** Bobo Classroom 41 hours of zero basic learning Python**

Recommended Posts

Python entry notes [basic grammar (below)]
Python introductory notes [basic grammar (on)]
Python entry tutorial notes (3) array
Python notes
Python entry-3
Python3 basic syntax
python study notes
Python basic summary
Python study notes (3)
Python basic operators
Python entry learning materials
03. Operators in Python entry
Python basic syntax generator
Python basic drawing tutorial (1)
Python3 entry learning four.md
Python function basic learning
python_ crawler basic learning
Python basic data types
Basic syntax of Python
Basic knowledge of Python (1)
Python3 entry learning three.md
Python3 entry learning one.md
Python basic data types
Python3 entry learning two.md
Python basic syntax iteration
2020--Python grammar common knowledge points
Python basic syntax list production
Python basic drawing tutorial (two)
05. Python entry value loop statement