[Python introduction] - basic syntax and variable types

Posted by nutt318 on Sun, 02 Feb 2020 11:18:40 +0100

1. Basic grammar

Branch structure

if i < 0:
 	print("negative")
elif i == 0:
	print("0")
else:
	print("Positive number")
Cyclic structure

while

while i < 100:
    print("HelloWorld")

for

# range(N) from 0 to n-1
for i in range(5): #Print 0~4
    print("Hello:",i) #Result Hello: 0 comma for space
    
# range(M,N) from M to n-1
for i in range(1,5): #Print 1~4
    print("Hello:",i) #Result Hello: 1 comma for space

Declaring function

def fun(var):
    return 1

2. Number type and operation

integer

Python has arbitrary precision integers, so there is no real fixed maximum. You are only limited by available memory.

Floating point number

round(x,d)     #To round x, d is the number of decimal places to prevent uncertainty
round(0.1+0.2,1) == 1  #Using round for floating point comparison si

complex

z = 1.23e-4 + 5.6e+89j  #z is a complex z.real gets real part z.imag gets imaginary part

operator

x / y ා mathematical divisor returns floating-point number
 x // y ා integers return integers
 x ** y ා power operation x's y power 10 square root is 10 * * 0.5

Many types of numeric operations result in the widest data types
 Integer < float < complex 

Arithmetic function

divmod(x,y)  #Quotient and remainder function (x//y, x%y), output quotient and remainder at the same time
# For example, divmod(10,3) = (3,1)
pow(x,y[,z]) # The parameter in the power CO function [] means that the parameter can be omitted 
# For example, the module of pow (3,9910000) 3 to 10000
round(x[,d]) #To round x, d is the number of decimal places to prevent uncertainty
max(x1,x2,x3...) #Maximum function can have multiple parameters
min(x1,x2,x3...) #Minimum function can have multiple parameters
int(x) #Force x to integer
float(x) #Force x to float
complex(x) #Force x to complex

Example: the power of rising day by day

# Example 3 the power of day up

#1% improvement every day.
dayup  = pow(1.001,365)
print(dayup) #1.4402513134295205
#Step back 1% every day.
daydown  = pow(0.999,365)
print(daydown) #0.6940698870404745

###########################
#5% improvement every day. Step back 5% every day.
dayfactor = 0.005
print(pow(1+dayfactor,365))#6.17
print(pow(1-dayfactor,365))#0.16
#1% improvement per day, 1% retrogression per day.
dayfactor = 0.01
print(pow(1+dayfactor,365))#37.78
print(pow(1-dayfactor,365))#0.025

############################
#365 days a year, 5 working days a week, 1% progress every day, 2 rest days, 1% step back every day
dayfactor = 0.01
ans = 1
for i in range(365):
    if i % 7 in [6,0]:
        ans *= (1-dayfactor)
    else:
        ans *= (1+dayfactor)
print("{:.2f}".format(ans))

############################
#Working day mode: working days should be improved by x%, and rest days should be reduced by 1% in order to be the same as working hard by 1% every day
def DayUp(df):
    dayup_ = 1
    for i in range(365):
        if i % 7 in [6,0]:
            dayup_ *= (1-0.01)
        else:
            dayup_ *= (1+df)
    return dayup_
dayf = 0.01
while DayUp(dayf) < 37.78:
    dayf += 0.001
print(dayf)

3. string

There are 2 types and 4 representations

'misable' -- single quotation mark
 "Double quotation mark" ා double quotation mark string
 '''three single quotes ා three single quotes or three double quotes multiline string
        Three double quotes' '
#String experiment
print('Miserable')
print("double quotes")
print('' 'three single quotes
        Three double quotation marks' '
print('Here's a double quotation mark (") ') ා double quotation mark in string and single quotation mark in outer layer
 print("here is a single quotation mark (')) ා a single quotation mark in a string is a double quotation mark
 print('''here is a single quotation mark (') and a double quotation mark (')') (both have outer layers, which are three quotation marks)
You can still use the escape character '\'

The sequence number of the string

In both directions

String slicing

#Use [] to get one or more characters in a string
TempStr = "37C"
#Indexes
#Str[N] gets the character at the position of string N
TempStr[-1] = "C"  
#Section
#Str[M:N] gets the substring from string m to N-1
TempStr[0:-1] = "37"
#Str[M:N:K] intercepts substring in K steps from m to N-1
#M missing to start N missing to end K missing in steps of 1  
"1235467890"[:3] = "0 one or two"   #Substring steps of 0 ~ 2 are 1
"1235467890"[1:8:2] = "1357"  #Substring steps of 1-7 are 2
"1235467890"[::-1] = "187, 654, 3200"  #Taking 0-10 strings from the back to the front one by one is equivalent to flipping the strings

String Operators

x+y   #Connect two strings x and y
n*x or x*n  #Copy n times string x
x in s  #Check if x is a substring of s, otherwise False
#WeekNanme.py based on the input data, it's the day of the week
#Version 1
weekStr = "Monday Tuesday Wednesday Thursday Friday Saturday Sunday"
weekid = eval(input())
pos = (weekid-1)*3
print(weekStr[pos:pos+3])
#Version two
weekStr ="One two three four five six"
weekid = eval(input())
print("week"+weekStr[weekid-1])

String processing function

len(x)  #Return string length
str(x)  #Change any type of variable x to a string
hex(x)  #Hexadecimal form of integer x
oct(x)  #Octal form of integer x

chr(u)  #u is Unicode code, and the codes in the corresponding character Py returned are all Unicode
ord(x)  #x is a character, return its corresponding Unicod e encoding
"1 + 1 = 2 "+chr(10004)  =  '1 + 1 = 2 √'
for i in range(12):
    print(chr(9800+i)+" ",end="")  #Print twelve constellations

String processing method (the method should be in the form of object. name())

str.lower() or str.upper() #String becomes all uppercase or all lowercase
str.split(sep = Node) #Return a list sep as a separator 
#For example, "a, B, C". Split (",") ['a ','b','c ']
str.count(sub) #Returns the number of occurrences of substring sub
str.replace(old,new) #Replace all old substrings with new 
#For example, "python".replace("n","n123.io") = "python123.io"
str.center(width[,fillchar])  #str is centered according to the width, and fillchar is the fill character
str.strip(chars) #Remove the left and right characters from the string 
#For example "= oython =". Strip ("= NP") = "ytho"
str.join(iter)  #It is good to add an s after each element except the last one

Formatting of strings

Similar to JAVA, "slot" is used to occupy space


Six kinds of formatting control marks inside "slot"
1. Normal string

"{0:=^20}".format("PYTHON")  #Fill with "=", align in the middle, output width is 20px

2. Numeric string

"{0:,.2f}".format(12345.6789) #For the 0-th parameter, use the thousand separator to keep two decimal places after the decimal point. The floating-point type represents
122 original articles published, 49 praised, 40000 visitors+
Private letter follow

Topics: Python REST encoding Java