Python basic syntax (quick start)

Posted by dinku33 on Tue, 04 Jan 2022 01:43:03 +0100

data type

Integer type (int)

x = 108
print(x)
print(type(x))
y = 888888888888888888888
print(y)
print(type(y))

No matter how large or small integers are, Python uses only one type of storage, int.

Operation results:

Decimal / floating point number (float)

The exponential form of Python decimal is written as follows:

aen or aen

A is the mantissa, which is a decimal number; N is the exponential part, which is a decimal integer; E or E is a fixed character used to split the mantissa part and the exponent part. The whole expression is equivalent to a × 10^n.

As long as it is written in exponential form, it is a decimal, even if its final value looks like an integer. For example, 108E3 is equivalent to 108000, but 108E3 is a decimal.

a = 10.8
print("a Value of:",a)
print("a Type of:",type(a))
b = 108E2
print("b Value of:",b)
print("b Type of:",type(b))
c = 0.21565616849658495316616
print("c Value of:",c)
print("c Type of:",type(c))

Operation results:

complex type

The complex number consists of a real part and an imaginary part. In Python, the imaginary part of the complex number takes J or j as the suffix. The specific format is:

a + bj

a represents the real part and b represents the imaginary part.

c1 = 12 + 0.2j
print("c1Value: ", c1)
print("c1Type", type(c1))

c2 = 6 - 1.2j
print("c2Value: ", c2)

#Simple calculation of complex numbers
print("c1+c2: ", c1+c2)
print("c1*c2: ", c1*c2)

Operation results:

c1Value:  (12+0.2j)
c1Type <class 'complex'>
c2Value:  (6-1.2j)
c1+c2:  (18-1j)
c1*c2:  (72.24-13.2j)

character string

  • Strings in Python must be surrounded by double quotes' 'or single quotes''
  • When quotation marks appear in the string content, we need special treatment
  1. Escape quotation marks by adding a backslash \ before the quotation marks
str = 'I\'m your friend.'
print(str)

Operation results:
I'm your friend.

  1. Enclose the string with different quotation marks
    If a single quotation mark appears in the string content, you can surround the string with double quotation marks and vice versa.

String interception

#[start position: end position: step value]

str = "HelloWorld"
print(str)
print(str[1])#e
print(str[0:4])#Hell
print(str[1:8:2]) #elWr
print(str[8:])#ld
print(str[:8])#HelloWor

To be added

List

Different types can be stored in the list

namelist = ["Xiao Zhang","Xiao Chen","Kobayashi"]
print(namelist[0])
print(namelist[1])
print(namelist[2])
print("==============")
testlist = [108,"Xiao Zhang"]
print(testlist[0],"->",type(testlist[0]))
print(testlist[1],"->",type(testlist[1]))

ergodic

  • for loop
for name in namelist:
    print(name)
  • while Loop
length = len(namelist)
i = 0
while i<length:
    print(namelist[i])
    i+=1

Add, delete, modify and query

Add (append(), extend(), insert())

  • Use append()
namelist = ["Xiao Zhang","Xiao Chen","Kobayashi"]

print("-----Before increase·List data------")
for name in namelist:
    print(name,end="\t")
name = input("\n Please enter the added Name:")
namelist.append(name);    #Append an element to the end
print("-----After increase·List data------")
for name in namelist:
    print(name,end="\t")

a = [1,6]
b = [2,8]
a.append(b) #The list is treated as an element and nested in a list
print(a)
  • Use extend()
a = [1,6]
b = [2,8]
a.extend(b) #Append each element in the b list to the end of the a list one by one
print(a)

  • Insert the element at the subscript position specified by insert()
a = [1,2,4,5]
a.insert(2,3) #Insert (subscript, element / object) specifies the subscript position to insert the element
print(a)

Delete (del, pop(), remove())

bookName = ["The Dream of Red Mansion","Romance of the Three Kingdoms","Alive","Water Margin","Journey to the West","Alive"]
print("-----Before deletion·List data------")
for name in bookName:
    print(name,end="\t")
print("\n")
#del bookName[2]  #Deletes an element at the specified location
#bookName.pop() #Pop up the last element at the end
#bookName.pop(1) #Pop up a specified element
bookName.remove("Alive") #Directly delete the element with the specified content. If there are elements with the same content in the list, only the first duplicate will be deleted
print("-----After deletion·List data------")
for name in bookName:
    print(name,end="\t")

modify

namelist = ["Xiao Zhang","Xiao Chen","Kobayashi"]

print("-----Before modification·List data------")
for name in namelist:
    print(name,end="\t")
print("\n")
namelist[2]="Xiao Zhou"
print("-----After modification·List data------")
for name in namelist:
    print(name,end="\t")

Find (in, not in)

namelist = ["Xiao Zhang","Xiao Chen","Kobayashi"]
findName = input("Please enter the name you want to find:")
if findName in namelist:
    print("eureka")
else:
    print("Can't find")

ergodic

Here is an example of using enumeration

list = {"aa","bb","cc","dd"}
for i,x in enumerate(list):
    print(i+1,x)

index()

list = ["a","b","c","d","a"]
#Find the elements in the specified range and return the subscript of the corresponding data
print(list.index("a",0,3))#Range: left closed right open [1,3)

count()

list = ["a","b","c","d","a"]
print(list.count("a"))#Count how many times an element appears

reverse()

a = [1,2,3,4]
print("Before reversing:",a)
a.reverse() #Invert all elements of the list
print("After reversal:",a)

sort()

b = [5,8,4,1]
print("Original list:",b)
b.sort() #Ascending order
print("Ascending order:",b)
b.sort(reverse=True) #Descending order
print("Descending order:",b)

Tuple (tuple)

Tuples differ from list s in that:

  • The elements of the list can be changed, including modifying element values, deleting and inserting elements, so the list is a variable sequence;
  • Once a tuple is created, its elements cannot be changed, so a tuple is an immutable sequence.

When there is only one data type element in the created tuple, a comma must be added after the element, which is the tuple

a = (11,)
b = (11)
print(type(a)) #<class 'tuple'>
print(type(b)) #<class 'int'>

Add (connect)

tup1 = (12,34,56)
tup2 = ("aa","bb","cc")

tup = tup1+tup2
print(tup) #(12, 34, 56, 'aa', 'bb', 'cc')

delete

tup1 = (12,34,56)
del tup1  # The entire tuple variable was deleted
print("After deletion",tup1) #NameError: name 'tup1' is not defined

modify

Tuples are immutable sequences, and the elements in tuples cannot be modified, so we can only create a new tuple to replace the old tuple. Or reassign the original tuple.

Access element

Slightly, similar to the list

Dict (Dictionary)

Dictionary (dict) is an unordered and variable sequence. Its elements are stored in the form of "key value". In contrast, list s and tuple s are ordered sequences, and their elements are stored next to each other at the bottom.

info = {"name":"Xiao Zhang","age":18,"sex":"male"}
#Dictionary access
print(info["name"])
#A nonexistent key was accessed
#print(info["mobile"])#Will report an error
#Access with get() and no default value can be set. Otherwise, the default value will not work
print(info.get("age",20))
print(info.get("mobile","123456789"))

increase

student = {"name":"Xiao Zhang","age":19}
newID = input("Please enter the new student number:")
student["id"] = newID
print(student["id"])

Delete & empty

#Delete the specified key value pair, and an error will be reported after deletion
del student["name"]
#Delete the dictionary, and an error will be reported when accessing it
del student
student = {"name":"Xiao Zhang","age":19}
#Clear -- clear
print("Before emptying:",student)
student.clear()
print("After emptying:",student)

change

student = {"name":"Xiao Zhang","age":25}
student["age"] = 18
print(student["age"])

Access data

info = {"name":"Xiao Zhang","age":18,"sex":"male"}
print(info.keys()) #Get all keys (list)
print(info.values()) #Get all values (list)
print(info.items()) #Get all items (lists), and each key value pair is a tuple

ergodic

#Traverse all keys
for key in info.keys():
    print(key,end="\t")
#Traverse all values
for value in info.values():
    print(value,end="\t")
#Traverse all key value pairs
for key,value in info.items():
    print("key=%s,value=%s"%(key,value))

Set set

Like the set concept in mathematics, it is used to save non repeating elements, that is, the elements in the set are unique and different from each other.

List, tuple, dictionary, set difference

output

print()

print("Hello World")
  • Output multiple variables and strings at the same time
name = "Xiao Zhang"
age = 18
print("full name:",name,"Age:",age)

Operation results:

age = 18
print("I this year%d year"%age)
print("My name is%s,My nationality is%s"%("Xiao Zhang","China"))

Operation results:

  • If you want to change the default separator, you can set it through the sep parameter
print("www","baidu","com",sep=".")

Operation results:

  • By default, the output of the print() function will always wrap lines. This is because the default value of the end parameter of the print() function is "\ n", and this "\ n" represents line wrapping. If you want the print() function to output without line breaks, reset the end parameter
print("Hello",end="")
print("World",end="\t")
print("Python",end="\n")
print("end")

Operation results:

Specifies the minimum output width

Specify the minimum output width (at least how many character positions to occupy) using the following format:
%10d indicates that the integer width of the output is at least 10;
%20s means that the output string width is at least 20.
For integers and strings, when the actual width of the data is less than the specified width, it will be filled with spaces on the left; When the actual width of the data is greater than the specified width, it will be output according to the actual width of the data.

Specify alignment

signexplain
+Specify left alignment
-The number indicating the output should always be signed; Positive numbers with +, negative numbers with -.
0Indicates that 0 is supplemented when the width is insufficient, rather than spaces.

Supplement:

  • For integers, when specifying left alignment, it has no effect to fill 0 on the right, because this will change the value of the integer.
  • For decimals, the above three flags can exist at the same time.
  • For a string, you can only use the - flag, because the symbol has no meaning for the string, and complementing 0 will change the value of the string

Specify decimal precision

For decimals (floating-point numbers), print() also allows you to specify the number of digits after the decimal point, that is, to specify the output precision of the decimal point.

The precision value needs to be placed after the minimum width with a dot in the middle separate; You can also write only the precision without writing the minimum width. The specific format is as follows:

%m.nf
%.nf

m represents the minimum width, n represents the output accuracy It must exist.

Cast type

int(string) converts a string to an int type;
float(string) converts a string to float type;
bool(string) converts a string to bool type.

n = int(input("Please enter a number:"))
print("The number entered is:%d"%n)

Operation results:

operator

Arithmetic operator

Here are the operators different from c:

operatorexplainexampleresult
/Division (as in Mathematics)7 / 23.5
//Integer division (only the integer part of the quotient is retained)7/23
/Remainder, which returns the remainder of the division7/21
**Power operation / power operation, that is, return the y power of x2**416

Assignment operator & comparison operator

slightly

Logical operator

Ternary operator (ternary operator)

This is similar to the ternary operator in other programming languages: Writing method of

max = a if a>b else b

If a > b is true, take a as the value of the whole expression and assign it to the variable max;
If a > b does not hold, b is taken as the value of the whole expression and assigned to the variable max.

member operator

Identity operator


Note: the id(x) function is used to get the memory address of the object

Process control

Conditional judgment statement

Format:

if Expression 1:
    Code block 1
elif Expression 2:
    Code block 2
else: 
    Code block 3

Note: don't forget to indent the same code block by the same amount

Python marks code blocks with indentation. Code blocks must have indentation. Code blocks without indentation are not code blocks. In addition, the indent of the same code block should be the same, and those with different indents do not belong to the same code block.
give an example:

score = 68

if score >=90 and score <=100:
    print("Grade is A")
elif score >= 80 and score < 90:
    print("Grade is B")
elif score >= 70 and score < 80:
    print("Grade is C")
elif score >= 60 and score < 70:
    print("Grade is D")
else:
    print("Grade is E")
print("end")

Operation results:

Circular statement

if loop statement

#By default, it starts from 0 and ends at 5
for i in range(5):
    print(i)


Start with 1

#From 1 to 5
for i in range(1,5):
    print(i)

#From 0 to 5, add 2 each time
for i in range(0,5,2):
    print(i)
name = "china"
for x in name:
    print(x,end="\t")

a = ["aa","bb","cc","dd"]
for i in range(len(a)):
    print(i,a[i])

while loop statement

i = 0
while i<5:
    print("The current is the second%d Execution cycle"%(i+1))
    print("i=%d"%i)
    i+=1

break, continue, and pass

  • The break statement can jump out of the loop body of for and while
  • The continue statement skips the current cycle and proceeds directly to the next cycle
  • pass is an empty statement. It is generally used as a placeholder statement and does nothing
    Sometimes the program needs to occupy a position or put a statement, but it doesn't want this statement to do anything. At this time, it can be realized through the pass statement. Using the pass statement is more elegant than using comments.

function

#Function without return value
def add(a,b):
    c = a+b
    print(c)
add(11,66)

#Function with return value
def add(a,b):
    return a+b
print(add(11,66))

#Function that returns multiple values
def div(a,b):
    sh = a//b # Division
    yu = a%b   #Surplus
    return sh,yu
sh,yu = div(11,8)
print("Business:%d,remainder:%d"%(sh,yu))

Topics: Python