Varriable
1.Variable position & Attribute & input
2.if…elif…else
3.list & range & for…in… & input and sum
4.Multiplication table & input value and product & Calculator prime & Count to number & break and contiune
5.break & contiune
6.While
7.Dictionary & order funtion & key and value & divmod
8.String
9.Random number
10.Time
class & Area calculation & Module import
Error code & try...except...else & raise & assert
Variable position & Attribute & input
Variable position
#Use {} and format() to make position for unit
name = “Apple”
score = 100
print (“{}‘score is {}“.format(name,score))
#Apple score is 100
Variable attribute
#%5d %() *digital* , %5s %() *strings* , %8.2f %() *float*
price=50.0
print(“apple juice’s price is %5.2f” %price)
# apple juice’s price is 50.0
input
#int() for number *integer* ,
#str() for word *strings* ,
#float() for float *float number*
#input(“”) can enter word or number in parameter.
math=input(“Please write your math score:”)
eng=input(“Please write your english score:”)
sum=(int(math)+int(eng))
average=sum/2
print(“Total score:%d,Average score:%5.2f“%(sum,average))
# Please write your math score: …
# Please write your english score: …
# Total score: … ,Average score: …
if...elif...else
if…elif…else
#Use if to set a conditions and use elif to check the situation and if not met any conditions use else.
cost = int(input(“please enter your cost:”))
if (cost >= 1000):
if cost >= 30000:
print (int(cost*0.6),”dollors”)
elif cost >= 20000:
print(cost*0.75,”dollors”)
elif cost >= 10000:
print(cost*0.85,”dollors”)
elif cost >= 5000:
print(cost*0.9,”dollors”)
else:
print(cost,”dollors”)
# please enter your cost:…
list & range & for...in... & input and sum
list
#Use list[] can store a lot of variable and choose the particular one or more.
score=[90,75,88]
#len(list) can get how many total value from list.
#min(list) max(list) can get min or max value from list.
#.index() can get index of value in list.
#.count() can count how many times in the list.
#.append() , .extend() can append units at the end of the list.
#.insert(n,n1) can add n1 at n position.
#.remove() can remove units.
#.reverse() can reverse value of the list.
print (“english score = %2d:” %score[0])
print (“science score = %2d:” %score[1])
print (“chinese score = %2d:” %score[2])
# english score = 90
# science score = 75
# chinese score = 88
range
#Use list() and range() can set a digital conition to show.
num=range(5,19,2)
num1=range(50,3,-3)
num2=range(-30,60,9)
num3=range(90,60)
print([list(num),list(num1),list(num2),list(num3)])
# [5, 7, 9, 11, 13, 15, 17] [50, 47, 44, 41, 38, 35, 32, 29, 26, 23, 20, 17, 14, 11, 8, 5] [-30, -21, -12, -3, 6, 15, 24, 33, 42, 51] []
for… in…
#Use (1,2,sep=””) can let every variable get a particular value at behind,
#Use (1,2,end=””) can get a particular value at the end,
#Use (1,2,end=”\n“) can change to next line.
#Use for “” in list[] make variable to operate action what in the list
#Use c=range(start digital,end digital,set condition for every split count).
for a in list[1,3,15,17]:
b=(2,5,8,9)
c=range(67,368,39)
print(a,b,c,sep=”@”)
print(a,b,list(c),end=”\n8520″)
# list[1, 3, 15, 17]@(2, 5, 8, 9)@range(67, 368, 39)
#list[1, 3, 15, 17] (2, 5, 8, 9) [67, 106, 145, 184, 223, 262, 301, 340]
#8520
input and sum
#Use for i in range(1,n+1) and “” += i can get digital total and need to check print line position , don’t below in last line , because it will print all the process.
sum = 0
n = int(input(“please enter digital:”))
for i in range(1,n+1):
sum += i
print(“1 to %d‘s total are %d “%(n,sum))
# please enter digital: … 5
# 15 (1+2+3+4+5)
Multiplication table & input value and product & Calculator prime & Count to number
Multiplication table
#Use for and for can get product total, %-3d let digital move left 3 dot space #Use end=”” make they keep on same line
for i in range(1,10):
for j in range(1,10):
product = i*j
print(“%d*%d=%-3d“%(i,j,product),end=””)
print(“”)
#
1*1=1 1*2=2 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9
2*1=2 2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18
3*1=3 3*2=6 3*3=9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27
4*1=4 4*2=8 4*3=12 4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 6*7=42 6*8=48 6*9=54
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 7*8=56 7*9=63
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 8*9=72
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
input value and product
#two digital product calculator
a=int(input(“please enter frist digital:”))
b=int(input(“please enter second digital:”))
product= a*b
print(“%d * %d = %-4d“%(a,b,product))
# please enter frist digital: …(2)
# please enter second digital: …(4)
# 8
Calculator prime
#Use % can divided digital and know if it is prime.
n=int(input(“please enter any digital number over 1 :”))
if (n==2):
print(“%d is prime number!”%n)
for i in range(2,n):
if (n%i==0):
print(“%d is not prime number!!”%n)
break
else :
print(“%d is prime number!!”%n)
for i in range(2,n):
a=n%i
print(a,end=””)
# please enter any digital number over 1 :…(11)
#11 is prime number!!
#123154321
Count to number
#Use if set condition,and use for i in range(1,n+1) to get action
n =int(input(“please enter how many floor we have:”))
print(“The floor level we have is:”,end=””)
if (n > 3):
n += 1
for i in range(1,n+1):
if (i==4):
continue
print(i,,’’,end=””)
print(“”)
# please enter how many floor we have:…(5)
# The floor level we have is:”1 2 3 5 6.
break & contiune
break & contiune
#Use break can stop process and quite the loop when condition is match,
#Use continue can stop process and back to the loop again when condition is match.
for i in range(1,8):
if i == 5:
break
print(i,end=”\n”)
for i in range(1,8):
if i == 5:
continue
print(i,end=””)
#1
#2
#3
#4
#1,2,3,4,6,7,8
While
While
#Use while can action in condition number of times.
total=n=0
while n < 10:
n += 1
total += n
print(total)
#55(1+2+3+…+9+10)
While
#Use while if didn’t met the while condition,loop will keep going when it met.
print(“If finish loading , enter -1 to end !!”)
total=person=score=0
while (score !=-1):
person += 1
total += score
score = int(input(“Please enter %d‘s score:”%person))
average = total/ (person-1)
print (“The class of student have %d , and average score are%3.2d !!”%(person-1,average) )
# If finish loading , enter -1 to end !!
#Please enter 1’s score:90
#Please enter 2’s score:89
#Please enter 3’s score:-1
#The class of student have 2 , and average score are 89 !!
While
score=[]
total = inscore = person =0
print(“When finish , enter -1 to end and see the result!”)
while (inscore != -1):
person += 1
inscore= int(input(“please enter %d student’s score:”%person))
score.append(inscore)
for i in range(0,len(score)-1):
total += score[i]
average = total / (len(score)-1)
print(“We have %d student!”%(len(score)-1))
print(“And total score are %d , average score are %5.2f !”%(total,average))
#When finish , enter -1 to end and see the result!
#please enter 1 student’s score:50
#please enter 2 student’s score:65
#please enter 3 student’s score:78
#please enter 4 student’s score:-1
#We have 3 student!
#And total score are 193 , average score are 64.33 !
Dictionary & order funtion & key and value & divmod
Dictionary
#Use len(dict) can know how many value in the dictionary.
#Use dict.copy() can copy data form dictionart.
#Use key in dict can check the key exists in dictionary or not.
#Use dict.get(“key“:”value“) can get corresponding value of key , if it didn’t match anything , you will get “None” !!
dict={“A”:”introvert”,”B”:”extrovert”,”O”:”snsible”,”AB”:”smart”}
name=input(“please enter what blood type you what to search:”)
blood = dict.get(name)
if blood == None:
print (“no this blood type !!”)
print (“no「”+name+”」blood type”)
else :print (name + ” character is ” + blood + ” !! “)
print(end=”\n”)
# please enter what blood type you what to search: A
# A character is introvert !!
order function
dict = {“rice”:”50″,”noodle”:”45″,”soup”:”30″}
print (“We have rice , noodle , soup .”)
order = input(“Please enter what yuou want :”)
cost = dict.get(order)
while cost == None:
print(“Please choose what we have !!”)
order = input(“Please enter what yuou want :”)
cost = dict.get(order)
print(“Your order is ” + order + ” , and it cost ” + cost + “$.”)
# We have rice , noodle , soup .
# Please enter what yuou want :rice
# Your order is rice , and it cost 50$.
key and value
#Use dict.items() with for() in () can get all the key and value.
#Use dict.keys() and dict.values() can get key and value,which was in the dict.
dict={“apple”:50,”banana”:35,”orange”:45}
key=list(dict.keys())
value=list(dict.values())
for i in range (len(key)):
print( “%s price is %d !” %(key[i],value[i]))
store = list(dict.items())
for name, num in store:
print(“we have %s and the price is %d !” %(name, num))
#apple price is 50 !
#banana price is 35 !
#orange price is 45 !
#We have apple and the price is 50 !
#We have banana and the price is 35 !
#We have orange and the price is 45 !
divmod
#Use divmod(x,y) can get x divided y and the left
student=int(input(“Please enter how many student :”))
chicken=int(input(Please enter how many chicken :”))
ret=divmod(chicken,student)
print(“Each student can get “+str(ret[0])+” chicken , and there are “+str(ret[1])+” left.”)
# Please enter how many student :3
# Please enter how many chicken :7
# Each student can get 2 chicken , and there are 1 left.
String
String
#Use .upper() .lower() can make string upper and lower.
#Use .ljust() or .rjust() can let string align left or right inside the condition block.
#Use .center(n) can center strings withn n blocks spaces.
#Use .find() can search value position in the strings.
#Use .endswith(n) .startswith(n) can check string end or start word if n or not.
#Use .islower() .isupper() can check strings word were lower and upper or not.
#Use n.join() can let n be a connection word for strings to the strings.
#Use .lstrip() .rstrip() can remove empty string blocks on the left or right side.
#Use .replace(n1,n2) can replace n1 to n2.
#Use .split(n) can split string with n into a new string
name = [“apple”,”banana”,”orange”]
price = [60,50,55]
level = [“great”,”good”,”nice”]
print(“name price level postion”.upper())
for i in range(0,3):
print(name[i].upper().ljust(6),str(price[i]).rjust(6),level[i].rjust(7),(“site”).rjust(7),str(i+1).ljust(0))
#NAME PRICE LEVEL POSTION
#APPLE 60 great site 1
#BANANA 50 good site 2
#ORANGE 55 nice site 3
Random number
Random number
#Use import can loading particular modules, as can set it a simple name.
#Use r.choice() can get a random value from the strings.
#Use r.random() can get a random float number from 0 to 1.
#Use r.randint(n1,n2) can get a random number from n1 to n2.
#Use r.uniform(n1,n2)can get a random float number from n1 to n2.
#Use r.shuffle(list) can shuffle value in the list.
#Use r.sample( value , times ) can get a random value in the specified times
#Use r.sort() can show the value in the list from min to max.
#Use r.pop() can remove list random value and saving in other list.
#Use while true: can avoid numbers have same in number
import random as r
list = list(range(1,51))
number=r.sample(list,8)
number.sort()
numbers=str(r.sample(list,1))
while True:
if numbers not in number:
break
print(“Today’s special number is:” + str(number))
print(“Plus number is :”+ numbers , end=”\n”)
#Today’s special number is:[7, 13, 14, 26, 28, 32, 35, 36]
#Plus number is :[40]
number1=r.sample(range(1,51),8)
number1.sort()
number2=number1.pop()
print(“Today’s special number is :”,end=””)
for i in range(0,7):
if i == 6 :
print(str(number1[i]))
else:
print(str(number1[i]),end=”,”)
print(“Plus number is :”+str(number2))
#Today’s special number is :8,9,10,22,23,39,42
#Plus number is :49
Time
Time
# use .localtime() can get time data.
# use .tm_yday can get currently day in this year.
# use .tm_isdst can know have DST or not.
# .tm_year , .tm_mon , .tm_mday , .tm_hour , .tm_min , .tm_sec
import time as t
week = [” Mon”, ” Tus”, ” Wed”, ” Thus”, ” Fir”, ” Sat”, ” Sun”]
dst = [” None DST”, ” Have DST”]
time1 = t.localtime()
show = “localtime :” + str(int(time1.tm_year)-1911) +” year “
show += str(time1.tm_mon) + ” month ” + str(time1.tm_mday) + ” day ” +”\n“
show += ” :”+str(time1.tm_hour) + “hour ” + str(time1.tm_min) + “min “
show += str(time1.tm_sec) + “sec ” + week[time1.tm_wday] +”\n“
show += “Today is ” + str(time1.tm_yday) + ” day from is year, here” + dst[time1.tm_isdst]
print(show)
#localtime :113 year 4 month 28 day
# :18hour 51min 54sec Sun
#Today is 119 day from is year, here None DST
class & Area calculation & Module import
Class
#Use def __init__(self,[n1,n2,n3…]): can define attribute and set method for unit, and the first attribute need add self.
#If subclass didn’t set it own class , than it will inherit the father class.
#If subclass already set own attribute, but it want use father’s attribute, than it can use super().
class Animal():
def __init__(self,name):
self.name = name
def fly(self):
print(self.name + “is a animal!”)
class Bird(Animal):
def __init__(self,name,age):
super().__init__(name)
self.age = age
def fly(self):
print(str(self.age),end=”years“)
super().fly()
pigeon = Animal(“cat“)
pigeon.fly()
parrot = Bird(“dog”,5)
parrot.fly()
#cat is a animal!
#5 years dog is a animal!
#Use __( _*2) can define private attritube to avoid other class use that attribute.
#Use return can get the private attribute from father class.
class Father():
def __init__(self,name):
self.name = name
self.__eye=”black”
def getEye(self):
return self.__eye
class Child(Father):
def __init__(self,name,eye):
super().__init__(name)
self.eye=eye
self.fatherEye=super().getEye()
joe = Child(“Jack”,”blue”)
print(joe.name+”eyes color is “+joe.eye+”,and his father is “+joe.fatherEye)
#Jack eyes color is blue,and his father is black.
Area calculation
Area calculation
class Rectangle():
def __init__(self, width,height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Triangle(Rectangle):
def area2(self):
return (self.width * self.height)/2
triangle = Triangle(4,8)
print(“Rectangle area is =”,triangle.area())
print(“Triangle area is =”,triangle.area2())
#Rectangle area is =32
#Triangle area is =16
Module import
Module import
#Use import * can loading all function from module into python.
#Use from … import can loading specific function.
#Use as can set module name to other word.
calculate
def add(n1,n2):
return n1+n2
def sub(n1,n2):
return n1–n2
from calculate import *
from calculate import add,sub as a
from calculate import add as a
print(a(6,8))
print(add(8,4))
print(sub(5,3))
#14
#12
#2
Error code
Error code
#AttributeError unit don’t have this attribute.
#Exception all of mistake.
#FileNotFoundError file didn’t exist.
#IOError input and output problem.
#IndexError out of index range.
#MemoryError not enough memory.
#NameError variable didn’t set name problem.
#SyntaxError grammar error.
#TypeError data type erroe.
#ValueError input wrong word or number.
#ZeroDivisionError division can’t be zero.
#ArithmeticError there has math arithmetic error in the function.
try...except...else & raise & assert
try…except…else
#Use try…except…else can get the error code and set the action for it from except function, or keep going to else function.
#Use finally will doing function no matter any error.
try:
a=int(input(“Please enter frist number:”))
b=int(input(“Please enter second number:”))
r = a % b
except ValueError:
print(“There is a wrong values problem!”)
except Exception as e:
print(“There is a “,e,” problem,Include errors with denominator 0!”)
else:
print(“r=”,r)
finally:
print(“The function here will definitely be work”)
#Please enter frist number:5
#Please enter second number:0
#There is a ValueError problem,Include errors with denominator 0!
#The function here will definitely be work
raise
#Use raise can output the action when the condition being touch.
class MyException(ArithmeticError):
def __init__(self, arg):
self.args = arg
def CheckSpeed(speed):
if speed < 70:
raise Exception(“speed is to slow!”)
if speed > 110:
raise Exception(“you are over speed!”)
else:
raise MyException(“everything is good !”)
def convertTuple(tup): #Use this define to make the variable become to string.
abc = ”.join(tup)
return abc
for speed in (60,100,120):
try:
CheckSpeed(speed)
except MyException as e:
err= convertTuple(e.args)
print(“Current speed:{},{}” .format(speed,err))
except Exception as e:
print(“Current speed:{},{}” .format(speed,e))
#Current speed:60,speed is to slow!
#Current speed:100,everything is good !
#Current speed:120,you are over speed!
assert
#Use assert can set a condition and action to function, if it being true,function will stop can operate action. Otherwise, function will pass it and continue run.
class Car():
def __init__(self, speed):
self.speed = speed
def Turbo(self,n):
assert speed >= 0,
self.speed += n
for speed in (60,-20):
bus=Car(speed)
print(“speed=”,bus.speed,end=” “)
bus.Turbo(50)
print(” after speed up ,speed= “bus.speed)
#speed= 60 , after speed up ,speed= 110
#speed= -20 Traceback (most recent call last): AssertionError
Regular expression function list
Re function list
# . all of the characters expect newline. a.b~a3bc123=a3b
# ^ start of input. ^ab~abc123=ab , ^ab~a1b23=None
# $ end of input. ab$~123ab=ab , ac$!123ab=None
# * last object can appear 0 times or unlimit times. ac*~accc12=accc
# + last object can appear 1 times or unlimit times. ac+~accc12=accc
# ? last object can appear 0 times or 1 times. ac?~a123=a
# [abc] include a b c.
# [a-z] include a to z.
# \ The after characters were processed as normal characters.
# n{2} n need appear 2 times.
# n{2,} n appears more than 2 times and max to unlimit times.
# n{2,4} n appears more than 2 times and max to 4 times.
# \d , [0-9] include all of number.
# [^a-z] ^ mean expect all of a to z.
# \D all of the characters expect number.
# \n newline.
# \r carriage return.
# \t tab character.
# \s space,tab,newline,newpage.
# \S all of the characters expect space,tab,newline,newpage.
# \w number,word or_ . [0-9A-Za-z+]
# \W all of the characters expect number,word or_ .
compile & match & search & findall
compile & match & search & findall
# Use import re to loading re module.
# Use n=re.compile(r’[A-Za-z0-9_]+ ‘) can building a re unit, and r let unit be a re.
# Use match to return the matching string in the re (regular expression
) on start, when it touch no match will stop.
# Use group() can return the matching string in the re.
# Use start() can return matching start position.
# Use end() can return matching end position.
# Use span() can return (start,end).
match
import re
pat = re.compile(r‘[a-z]+‘) # pat = r‘[a-z]+‘
m = pat.match(‘tem12po’) # m = re.match(pat ,’tem12po’)
print(m)
if not m==None:
print(m.group())
print(m.start())
print(m.end())
print(m.span())
#<re.Match object; span=(0, 3), match=’tem’>
#tem
#0
#3
#3(0, 3)
search
# Use search to return the matching string in the re (regular expression
) on start, after, stop on no match.
import re
pat = re.compile(‘[a-z]+‘) # pat = ‘[a-z]+‘
m = pat.search(‘3tem12po’) # m = re.search (pat ,’3tem12po’)
print(m)
if not m==None:
print(m.group())
print(m.start())
print(m.end())
print(m.span())
#<re.Match object; span=(1, 4), match=’tem’>
#tem
#1
#4
#(1, 4)
findall
# Use findall to return all the matching string in the re (regular expression
) with list ,if there were nothing match string, it will return empty list back.
import re
pat = re.compile(‘[a-z]+‘)
m = pat.findall(‘tem12po’) # m = re.findall (r‘[a-z]+‘ ,’tem12po’)
print(m)
#[‘tem’, ‘po’]
| & sub
|
# Use | can search more type condition at same time.
import re
phoneList=[“0412345678″,”(04)12345678″,”(04)-12345678″,”(049)2987654″,”0937-998877”]
pat = r‘\(\d{2,4}\)-?\d{6,8}|\d{9,10}|\d{4}-\d{6,8}’
for phone in phoneList:
phoneNum = re.search(pat,phone)
if not phoneNum ==None:
print(phoneNum.group())
# 0412345678
# (04)12345678
# (04)-12345678
# (049)2987654
# 0937-998877
sub
#Use re.sub(pattern,replace,string,count=0) can replace old string into new string,and only return the new one,the old one will keeping it, and pattern mean re type.
import re
pat=r“\d+”
substr=”****”
s=”Password:1234,ID:5678″
result = re.sub(pat,substr,s)
print(result)
#Password:****,ID:****
0.o
o.O
There is nothing in here :p .