Python introductory notes [basic grammar (on)]

Written in front: IDE:Visual Studio Code

 The following source code can be run directly, **python is actually easier for people who have learned c++ or c language, the main difference is that python pays more attention to format indentation, and its expression is even more flexible than c language* *

table of Contents

  1. String method (common functions and their use)
  2. Format string
  3. if statement practice
  4. elif statement exercise
  5. Lists and subscripts
  6. Simple use of lists
​

​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 truefalseprint("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)
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!")

first question:

# 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!")

Second question:

# 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

The third question:

# 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*3print(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

Foresee the funeral, [please see next time decomposition] (https://blog.csdn.net/weixin_43798170/article/details/90050937)

Recommended Posts

Python introductory notes [basic grammar (on)]
Python entry notes [basic grammar (below)]
Python notes
Python basic syntax (1)
Python study notes (1)
Python3 basic syntax
python study notes
Python basic summary
Python study notes (3)
Python basic operators
Python basic syntax generator
Python basic drawing tutorial (1)
Python function basic learning
Install Python3 on Ubuntu 14.04
python_ crawler basic learning
Python basic data types
Basic syntax of Python
Basic knowledge of Python (1)
Install Python3 on Ubuntu 16.04
Python basic data types
Install Python3.7 on Ubuntu
python Tic-Tac-Toe-text version (on)
Python basic syntax iteration
Python basic knowledge question bank
Install Python 3.7 on Ubuntu 18.04 LTS
Python on image processing PIL
Python entry tutorial notes (3) array
2020--Python grammar common knowledge points
Python basic syntax list production
Install python3 on linux, keep python2
Python basic drawing tutorial (two)