100 small Python examples

Author: RichardFu123
https://github.com/RichardFu123/Python100Cases

The address of the original question: http://www.runoob.com/python/python-100-examples.html, the original example is the py2.7 version, a lot of it is free to play during the rewriting process, and the running version is rewritten : Python3.7.

Example 001: Number combination

**Question: ** There are four numbers: 1, 2, 3, 4. How many different three-digit numbers can be formed without repeated numbers? What is each?

**Program analysis: ** Traverse all the possibilities and shave off the duplicates.

total=0for i inrange(1,5):for j inrange(1,5):for k inrange(1,5):if((i!=j)and(j!=k)and(k!=i)):print(i,j,k)
    total+=1print(total)

**Easy way: ** Use permutations in itertools.

import itertools
sum2=0
a=[1,2,3,4]for i in itertools.permutations(a,3):print(i)
 sum2+=1print(sum2)

Example 002: "Individual tax calculation"

**Topic: ** Bonuses issued by companies are based on profit commissions. When the profit (I) is less than or equal to 100,000 yuan, the bonus can be increased by 10%; when the profit is more than 100,000 yuan, and when the profit is less than 200,000 yuan, the portion of less than 100,000 yuan will be commissioned at 10%, which is higher than 100,000 yuan The commission is 7.5%; between 200,000 and 400,000, the part higher than 200,000 yuan can be commissioned 5%; between 400,000 and 600,000, the part higher than 400,000 yuan can be commissioned 3% ; Between 600,000 and 1 million, the portion above 600,000 yuan can be commissioned 1.5%, when it is more than 1 million yuan, the portion exceeding 1 million yuan will be commissioned at 1%. Enter the monthly profit I from the keyboard, and ask for it The total number of bonuses distributed?

**Program analysis: ** Calculate in intervals.

profit=int(input('Show me the money: '))
bonus=0
thresholds=[100000,100000,200000,200000,400000]
rates=[0.1,0.075,0.05,0.03,0.015,0.01]for i inrange(len(thresholds)):if profit<=thresholds[i]:
  bonus+=profit*rates[i]
  profit=0breakelse:
  bonus+=thresholds[i]*rates[i]
  profit-=thresholds[i]
bonus+=profit*rates[-1]print(bonus)

Example 003: Perfect square number

**Question: ** An integer. After adding 100 to it, it is a perfect square number, and adding 168 is a perfect square number. What is the number?

**Program analysis: ** Because 168 is too small for exponential explosion, you can directly omit mathematical analysis and use the simplest method to get the upper limit:

n=0while(n+1)**2-n*n<=168:
 n+=1print(n+1)----------85

The idea is: the worst result is that the square of n is exactly 168 different from the square of (n+1). Because of the square relationship, it is impossible to have a larger gap than this. As for judging whether it is a perfect square number, the simplest method is: the value of the square root can be a decimal of 0. Combined:

n=0while(n+1)**2-n*n<=168:
 n+=1for i inrange((n+1)**2):if i**0.5==int(i**0.5)and(i+168)**0.5==int((i+168)**0.5):print(i-100)

Example 004: The first few days of the day

**Topic: ** Enter a certain day, a certain month, and a certain day, which day is the day of the year?

**Program analysis: ** In special circumstances, an extra day in February should be considered for leap years:

def isLeapYear(y):return(y%400==0or(y%4==0 and y%100!=0))
DofM=[0,31,28,31,30,31,30,31,31,30,31,30]
res=0
year=int(input('Year:'))
month=int(input('Month:'))
day=int(input('day:'))ifisLeapYear(year):
 DofM[2]+=1for i inrange(month):
 res+=DofM[i]print(res+day)

Example 005: Three-number sorting

**Question: ** Enter three integers x, y, z, please output these three numbers from small to large.

**Program analysis: ** If you practice your hands, just find a sorting algorithm to implement it. If you are lazy, just adjust the function directly.

raw=[]for i inrange(3):
 x=int(input('int%d: '%(i)))
 raw.append(x)for i inrange(len(raw)):for j inrange(i,len(raw)):if raw[i]>raw[j]:
   raw[i],raw[j]=raw[j],raw[i]print(raw)

raw2=[]for i inrange(3):
 x=int(input('int%d: '%(i)))
 raw2.append(x)print(sorted(raw2))

Example 006: Fibonacci sequence

**Subject: ** Fibonacci sequence.

**Program analysis: ** Fibonacci sequence (Fibonacci sequence), starting from 1, 1, each item in the back is equal to the sum of the previous two items. Recursive implementation for graph convenience, and loop for graph performance.

# Recursive implementation
def Fib(n):return1if n<=2elseFib(n-1)+Fib(n-2)print(Fib(int(input())))
    
# Naive realization
target=int(input())
res=0
a,b=1,1for i inrange(target-1):
 a,b=b,a+b
print(a)

Example 007: copy

**Title: ** Copy data from one list to another list.

**Program analysis: ** Use the list [:], if you are uncertain, you can call the copy module.

import copy
a =[1,2,3,4,['a','b']]

b = a     #Assignment
c = a[:]    #Shallow copy
d = copy.copy(a)  #Shallow copy
e = copy.deepcopy(a) #Deep copy

a.append(5)
a[4].append('c')print('a=',a)print('b=',b)print('c=',c)print('d=',d)print('e=',e)============ RESTART: F:\PyWorkspace\Python100\100examples\007.py ============
a=[1,2,3,4,['a','b','c'],5]
b=[1,2,3,4,['a','b','c'],5]
c=[1,2,3,4,['a','b','c']]
d=[1,2,3,4,['a','b','c']]
e=[1,2,3,4,['a','b']]

Example 008: Nine-Nine Multiplication Table

**Question: ** Output 9*9 multiplication formula table.

**Program analysis: ** Considering rows and columns, a total of 9 rows and 9 columns, i control row, j control column.

for i inrange(1,10):for j inrange(1,i+1):print('%d*%d=%2ld '%(i,j,i*j),end='')print()

Example 009: Pause output for one second

**Subject: ** Pause output for one second.

**Program analysis: ** Use the sleep() function of the time module.

import time
for i inrange(4):print(str(int(time.time()))[-2:])
 time.sleep(1)

Example 010: Time to show people

**Title: ** Pause output for one second and format the current time.

**Program analysis: ** Same as 009.

import time

for i inrange(4):print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
 time.sleep(1)

Example 011: Raising a rabbit

**Topic: ** There is a pair of rabbits. From the third month after birth, one pair of rabbits will be born every month, and the little rabbit will give birth to a pair of rabbits every month after the third month. If the rabbits are not dead, ask each What is the total number of rabbits in a month?

**Program analysis: ** I think the original solution is a bit of a joke, without considering the issue of maturity at 3 months, how do people or babies give birth? Considering three months of maturity, four data can be constructed, among which: January rabbits grow up to become February rabbits every month, February rabbits become March rabbits, March rabbits become annual rabbits, and adult rabbits (including newly mature rabbits) The March rabbit) gives birth to the same number of January rabbits.

month=int(input('How many months to breed? :'))
month_1=1
month_2=0
month_3=0
month_elder=0for i inrange(month):
 month_1,month_2,month_3,month_elder=month_elder+month_3,month_1,month_2,month_elder+month_3
 print('First%d months total'%(i+1),month_1+month_2+month_3+month_elder,'To the rabbit')print('Among them, January Rabbit:',month_1)print('Among them, the February rabbit:',month_2)print('Among them, March Rabbit:',month_3)print('Of which adult rabbits:',month_elder)

Example 012: Prime numbers from 100 to 200

**Question: ** Determine how many prime numbers are between 101 and 200, and output all prime numbers.

**Program analysis: ** The method of judging prime numbers: Divide a number from 2 to sqrt (the number). If it can be divisible, it means that the number is not a prime number, otherwise it is a prime number.

import math
for i inrange(100,200):
 flag=0for j inrange(2,round(math.sqrt(i))+1):if i%j==0:
   flag=1breakif flag:continueprint(i)print('\nSimplify the code with "else"\n')for i inrange(100,200):for j inrange(2,round(math.sqrt(i))+1):if i%j==0:breakelse:print(i)

Example 013: Number of all daffodils

**Topic: ** Print out all the "daffodil numbers". The so-called "daffodil number" refers to a three-digit number whose cube sum is equal to the number itself. For example: 153 is a "daffodil number", because 153 = 1 cube + 5 cube + 3 cube.

**Program analysis: ** Use the for loop to control 100-999 numbers, and each number is decomposed into units, tens, and hundreds.

for i inrange(100,1000):
 s=str(i)
 one=int(s[-1])
 ten=int(s[-2])
 hun=int(s[-3])if i == one**3+ten**3+hun**3:print(i)

Example 014: Decompose prime factors

**Question: ** Decompose an integer into prime factors. For example: input 90 and print out 90=233*5.

**Program analysis: ** There is no need to judge whether it is a prime number at all. Starting from 2 and traversing the number itself, the smallest prime number must be divisible.

target=int(input('Enter an integer:'))print(target,'= ',end='')if target<0:
 target=abs(target)print('-1*',end='')

flag=0if target<=1:print(target)
 flag=1while True:if flag:breakfor i inrange(2,int(target+1)):if target%i==0:print("%d"%i,end='')if target==i:
    flag=1breakprint('*',end='')
   target/=i
   break

Example 015: Score archive

**Topic: ** Use the nesting of conditional operators to complete this question: students with academic performance >= 90 points are represented by A, those with a score between 60 and 89 are represented by B, and those with a score of less than 60 are represented by C.

**Program analysis: ** Just use conditional judgment.

points=int(input('Enter score:'))if points>=90:
 grade='A'
elif points<60:
 grade='C'else:
 grade='B'print(grade)

Example 016: Output date

**Title: ** Output the date in the specified format.

**Program analysis: ** Use the datetime module.

import datetime
print(datetime.date.today())print(datetime.date(2333,2,3))print(datetime.date.today().strftime('%d/%m/%Y'))
day=datetime.date(1111,2,3)
day=day.replace(year=day.year+22)print(day)

Example 017: String composition

**Title: ** Enter a line of characters and count the number of English letters, spaces, numbers and other characters.

**Program analysis: ** Using while or for statements, the condition is that the input character is not'\n'.

string=input("Input string:")
alp=0
num=0
spa=0
oth=0for i inrange(len(string)):if string[i].isspace():
  spa+=1
 elif string[i].isdigit():
  num+=1
 elif string[i].isalpha():
  alp+=1else:
  oth+=1print('space: ',spa)print('digit: ',num)print('alpha: ',alp)print('other: ',oth)

Example 018: Adding Repeaters

**Question: ** Find the value of s=a+aa+aaa+aaaa+aa...a, where a is a number. For example, 2+22+222+2222+22222 (a total of 5 numbers are added at this time), and the addition of several numbers is controlled by the keyboard.

**Program analysis: ** Solve with strings.

a=input('Added number:')
n=int(input('How many times? :'))
res=0for i inrange(n):
 res+=int(a)
 a+=a[0]print('The result is:',res)

Example 019: Finish the number

**Question: ** If a number is exactly equal to the sum of its factors, this number is called "final number". For example, 6=1+2+3. Program to find all the completed numbers within 1000.

**Program analysis: ** Add each pair of factors to the set, and the duplication has been automatically removed in this process. The final result request does not calculate itself.

def factor(num):
 target=int(num)
 res=set()for i inrange(1,num):if num%i==0:
   res.add(i)
   res.add(num/i)return res

for i inrange(2,1001):if i==sum(factor(i))-i:print(i)

Example 020: High-altitude parabolic

**Question: ** A ball falls freely from a height of 100 meters, and rebounds back to half of its original height each time it hits the ground. When it falls again, how many meters does it pass on the 10th landing? How high is the 10th rebound?

**Program analysis: ** None

high=200.
total=100for i inrange(10):
 high/=2
 total+=high
 print(high/2)print('Total length:',total)

Example 021: Monkey steals a peach

**Topic: ** Problem with monkey eating peaches: The monkey picked off a few peaches on the first day, and ate half of it immediately, but was not addicted, and ate another one more. The next morning, he ate half of the remaining peaches and ate more One. After that, I ate half and one of the remaining half of the previous day every morning. When I wanted to eat again in the morning of the 10th day, I saw that there was only one peach left. How many were picked on the first day?

**Program analysis: ** According to the reverse inference of the rules: the monkey has a peach, and he stole a peach. He felt that it was not enough and stole the same amount of peaches in his hand for 9 days.

peach=1for i inrange(9):
 peach=(peach+1)*2print(peach)

Example 022: Competition opponent

**Topic: ** Two table tennis teams compete, each with three players. Team A is composed of a, b, and c, and Team B is composed of x, y, and z. Lots have been drawn to determine the list of matches. Someone asked the players for the roster of the game. a says he does not compare with x, c says he does not compare with x, z, please program to find the list of the three teams.

**Program analysis: ** Find three opponents that do not repeat under the conditions.

a=set(['x','y','z'])
b=set(['x','y','z'])
c=set(['x','y','z'])
c-=set(('x','z'))
a-=set('x')for i in a:for j in b:for k in c:iflen(set((i,j,k)))==3:print('a:%s,b:%s,c:%s'%(i,j,k))

Example 023: Draw a rhombus

**Title: ** Print out the following pattern (diamond):

*    ***   *****  *******   *****    ***     *

**Program analysis: ** Just call recursively.

def draw(num):
 a="*"*(2*(4-num)+1)print(a.center(9,' '))if num!=1:draw(num-1)print(a.center(9,' '))draw(4)

Example 024: Fibonacci Sequence II

**Question: ** There is a sequence of scores: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13... Find the sum of the first 20 items of this sequence.

**Program analysis: ** is the last term of the Fibonacci sequence divided by the previous term.

a =2.0
b =1.0
s =0for n inrange(1,21):
 s += a / b
 a,b = a + b,a
print(s)

Example 025: Factorial summation

**Question: ** Find the sum of 1+2!+3!+...+20!.

**Program analysis: ** 1+2!+3!+...+20!=1+2(1+3(1+4(...20(1))))

res=1for i inrange(20,1,-1):
 res=i*res+1print(res)

Example 026: Recursively find factorial

**Question: ** Use recursion to find 5!.

**Program analysis: ** Just call recursively.

def factorial(n):return n*factorial(n-1)if n>1else1print(factorial(5))

Example 027: Recursive output

**Topic: ** Use the recursive function call method to print out the 5 characters entered in reverse order.

**Program analysis: ** Recursion is really stupid.

def rec(string):iflen(string)!=1:rec(string[1:])print(string[0],end='')rec(input('string here:'))

Example 028: Recursively find arithmetic sequence

**Topic: ** There are 5 people sitting together, ask how old is the fifth person? He said he was 2 years older than the fourth person. Asked the age of the fourth person, he said that he was 2 years older than the third person. Ask the third person and say that he is two years older than the second person. Ask the second person and say that he is two years older than the first person. Finally, I asked the first person, he said he was 10 years old. How old is the fifth person?

**Program analysis: ** Just the first arithmetic sequence.

def age(n):if n==1:return10return2+age(n-1)print(age(5))

Example 029: Reverse output

**Question: ** Give a positive integer with no more than 5 digits. Requirements: 1. Find the number of digits in it, and 2. Print out the digits in reverse order.

**Program analysis: ** Learn to decompose each digit, and the method of using strings is always easier.

n=int(input('Enter a positive integer:'))
n=str(n)print('%d digits'%len(n))print(n[::-1])

Example 030: Number of palindrome

**Subject: ** A 5-digit number, to determine if it is a palindrome. That is, 12321 is the number of palindrome, the ones place is the same as the ten thousand place, and the ten place is the same as the thousand place.

**Program analysis: ** It is more convenient to use a string, even if the input is not a number.

n=input("Enter whatever you want:")
a=0
b=len(n)-1
flag=True
while a<b:if n[a]!=n[b]:print('Not palindrome')
  flag=False
  break
 a,b=a+1,b-1if flag:print('Palindrome')

Example 031: Letters to recognize words

**Topic: ** Please enter the first letter of the day of the week to determine the day of the week. If the first letter is the same, continue to determine the second letter.

**Program analysis: ** Here, the comparison relationship is directly stored in the form of a dictionary.

weekT={'h':'thursday','u':'tuesday'}
weekS={'a':'saturday','u':'sunday'}
week={'t':weekT,'s':weekS,'m':'monday','w':'wensday','f':'friday'}
a=week[str(input('Please enter the first letter:')).lower()]if a==weekT or a==weekS:print(a[str(input('Please enter the second letter:')).lower()])else:print(a)

Example 032: Reverse output II

**Title: ** Output the values of the list in reverse order.

**Program analysis: ** None.

a =['one','two','three']print(a[::-1])

Example 033: List to string

**Title: ** Separate the list by commas.

**Program analysis: ** None.

L =[1,2,3,4,5]print(','.join(str(n)for n in L))

Example 034: Call function

**Topic: ** Practice function call.

**Program analysis: ** None.

def hello():print('Hello World!')
def helloAgain():for i inrange(2):hello()if __name__=='__main__':helloAgain()

Example 035: Set output color

**Title: ** Text color settings.

**Program analysis: ** None.

classbcolors:
 HEADER ='\033[95m'
 OKBLUE ='\033[94m'
 OKGREEN ='\033[92m'
 WARNING ='\033[93m'
 FAIL ='\033[91m'
 ENDC ='\033[0m'
 BOLD ='\033[1m'
 UNDERLINE ='\033[4m'print(bcolors.WARNING +"Warning color font?"+ bcolors.ENDC)

Example 036: Calculating prime numbers

**Question: ** Find prime numbers within 100.

**Program analysis: ** Use else to execute the reward code of the for loop (if the for ends normally, not break).

lo=int(input('Lower limit:'))
hi=int(input('Upper limit:'))for i inrange(lo,hi+1):if i >1:for j inrange(2,i):if(i % j)==0:breakelse:print(i)

Example 037: Sorting

**Topic: ** Sort 10 numbers.

**Program analysis: ** Same as example 005.

raw=[]for i inrange(10):
 x=int(input('int%d: '%(i)))
 raw.append(x)for i inrange(len(raw)):for j inrange(i,len(raw)):if raw[i]>raw[j]:
   raw[i],raw[j]=raw[j],raw[i]print(raw)

Example 038: Sum of Diagonal Lines of Matrix

**Question: ** Find the sum of the main diagonal elements of a 3*3 matrix.

**Program analysis: ** None.

mat=[[1,2,3],[3,4,5],[4,5,6]]
res=0for i inrange(len(mat)):
 res+=mat[i][i]print(res)

Example 039: Inserting an element in an ordered list

**Question: ** There is an array that has been sorted. Now enter a number and require it to be inserted into the array according to the original rules.

**Program analysis: ** First judge whether this number is greater than the last number, and then consider the case of inserting the middle number. After inserting, the number after this element is moved one position in turn.

lis=[1,10,100,1000,10000,100000]
n=int(input('insert a number: '))
lis.append(n)for i inrange(len(lis)-1):if lis[i]>=n:for j inrange(i,len(lis)):
   lis[j],lis[-1]=lis[-1],lis[j]breakprint(lis)

Example 040: Reverse sequence list

**Topic: ** Output an array in reverse order.

**Program analysis: ** Exchange positions one by one, or call the reverse method directly.

lis=[1,10,100,1000,10000,100000]for i inrange(int(len(lis)/2)):
 lis[i],lis[len(lis)-1-i]=lis[len(lis)-1-i],lis[i]print('The first realization:')print(lis)

lis=[1,10,100,1000,10000,100000]print('The second realization:')
lis.reverse()print(lis)

Example 041: Class methods and variables

**Topic: ** Imitate the usage of static variables.

**Program analysis: ** Construct a class, understand its methods and variables.

def dummy():
 i=0print(i)
 i+=1classcls:
 i=0
 def dummy(self):print(self.i)
  self.i+=1

a=cls()for i inrange(50):dummy()
 a.dummy()

Example 042: Variable scope

**Topic: ** Learn how to use auto to define variables.

**Program analysis: ** The scope of variables in python.

i=0
n=0
def dummy():
 i=0print(i)
 i+=1
def dummy2():
 global n
 print(n)
 n+=1print('Variables with the same name inside the function')for j inrange(20):print(i)dummy()
 i+=1print('global declares variables with the same name')for k inrange(20):print(n)dummy2()
 n+=10

Example 043: Scope, class methods and variables

**Title: ** Another case of imitating static variables.

**Program analysis: ** Comprehensive example 041 and example 042.

classdummy:
 num=1
 def Num(self):print('class dummy num:',self.num)print('global num: ',num)
  self.num+=1

n=dummy()
num=1for i inrange(5):
 num*=10
 n.Num()

Example 044: Matrix addition

**Topic: ** Calculate the addition of two matrices.

**Program analysis: ** Create a new matrix, use for to iterate and take out the values of the corresponding positions in the X and Y matrices, add them and place them in the corresponding positions of the new matrix.

X =[[12,7,3],[4,5,6],[7,8,9]]
 
Y =[[5,8,1],[6,7,3],[4,5,9]]
 
res=[[0,0,0],[0,0,0],[0,0,0]]for i inrange(len(res)):for j inrange(len(res[0])):
  res[i][j]=X[i][j]+Y[i][j]print(res)

Example 045: Summation

**Topic: ** Count the sum of 1 to 100.

**Program analysis: ** None

res=0for i inrange(1,101):
 res+=i
print(res)

Example 046: Break the loop

**Question: ** Find the square of the input number, if the square operation is less than 50, then exit.

**Program analysis: ** None

while True:try:
  n=float(input('Enter a number:'))
 except:print('input error')continue
 dn=n**2print('Its square is:',dn)if dn<50:print('The square is less than 50, exit')break

Example 047: Function exchange variables

**Topic: ** The values of two variables are interchanged with functions.

**Program analysis: ** None

def exc(a,b):return(b,a)
a=0
b=10
a,b=exc(a,b)print(a,b)

Example 048: Number ratio size

**Subject: ** Comparison of numbers.

**Program analysis: ** None

a=int(input('a='))
b=int(input('b='))if a<b:print('a<b')
elif a>b:print('a>b')else:print('a=b')

Example 049: lambda

**Topic: ** Use lambda to create anonymous functions.

**Program analysis: ** None

Max=lambda x,y:x*(x>=y)+y*(y>x)
Min=lambda x,y:x*(x<=y)+y*(y<x)

a=int(input('1:'))
b=int(input('2:'))print(Max(a,b))print(Min(a,b))

Example 050: Random number

**Question: ** Output a random number.

**Program analysis: ** Use random module.

import random
print(random.uniform(10,20))

Example 051: Bitwise AND

**Topic: ** Learn to use bitwise and &.

**Program analysis: ** 0&0=0; 0&1=0; 1&0=0; 1&1=1.

a=0o77print(a)
b=a&3print(b)
b=b&7print(b)

Example 052: bitwise OR

**Topic: ** Learn to use bitwise or |.

**Program analysis: ** 0|0=0; 0|1=1; 1|0=1; 1|1=1

a=0o77print(a|3)print(a|3|7)

Example 053: Bitwise XOR

**Topic: ** Learn to use bitwise XOR^.

**Program analysis: ** 0^0=0; 0^1=1; 1^0=1; 1^1=0

a=0o77print(a^3)print(a^3^7)

Example 054: Bit inversion, bit shift

**Question: ** Take an integer a from 4 to 7 digits from the right end.

**Program analysis: ** It can be considered as follows: (1) First shift a right by 4 bits. (2) Set a number whose lower 4 bits are all 1, and the rest are all 0. Use ~(~0<<4) (3) to perform & operation on the above two.

a=int(input('Enter a number: '))
b=0                 #     0
b=~b                #     1
b=b<<4              # 10000
b=~b                #  1111
c=a>>4
d=c&b
print('a:',bin(a))print('b:',bin(b))print('c:',bin(c))print('d:',bin(d))

Example 055: Invert by bit

**Topic: **Learn to use bitwise inversion~.

**Program analysis: ** ~0=1; ~1=0;

print(~234)print(~~234)

Example 056: Draw a circle

**Topic: ** Draw pictures, learn to use circles to draw circles.

**Program analysis: ** None.

from tkinter import*
canvas=Canvas(width=800,height=600,bg='yellow')
canvas.pack(expand=YES,fill=BOTH)
k=1
j=1for i inrange(26):
 canvas.create_oval(310-k,250-k,310+k,250+k,width=1)
 k+=j
 j+=0.3mainloop()

Example 057: Draw a line

**Topic: ** Draw pictures, learn to draw straight lines with lines.

**Program analysis: ** None.

if __name__ =='__main__':from tkinter import*
 
 canvas =Canvas(width=300, height=300, bg='green')   
 canvas.pack(expand=YES, fill=BOTH)                  
 x0 =263
 y0 =263
 y1 =275
 x1 =275for i inrange(19):
  canvas.create_line(x0,y0,x0,y1, width=1, fill='red')
  x0 = x0 -5
  y0 = y0 -5
  x1 = x1 +5
  y1 = y1 +5
 
 x0 =263
 y1 =275
 y0 =263for i inrange(21):
  canvas.create_line(x0,y0,x0,y1,fill ='red')
  x0 +=5
  y0 +=5
  y1 +=5mainloop()

Example 058: Draw a rectangle

**Topic: ** Draw pictures, learn to draw squares with rectangles.

**Program analysis: ** None.

if __name__ =='__main__':from tkinter import*
 root =Tk()
 root.title('Canvas')
 canvas =Canvas(root,width =400,height =400,bg ='yellow')
 x0 =263
 y0 =263
 y1 =275
 x1 =275for i inrange(19):
  canvas.create_rectangle(x0,y0,x1,y1)
  x0 -=5
  y0 -=5
  x1 +=5
  y1 +=5
        
 canvas.pack()
 root.mainloop()

Example 059: Drawing (ugly)

**Topic: ** Drawing, comprehensive example.

**Program analysis: ** Ugly.

if __name__  =='__main__':from tkinter import*
 canvas =Canvas(width =300,height =300,bg ='green')
 canvas.pack(expand = YES,fill = BOTH)
 x0 =150
 y0 =100
 canvas.create_oval(x0 -10,y0 -10,x0 +10,y0 +10)
 canvas.create_oval(x0 -20,y0 -20,x0 +20,y0 +20)
 canvas.create_oval(x0 -50,y0 -50,x0 +50,y0 +50)import math
 B =0.809for i inrange(16):
  a =2* math.pi /16* i
  x = math.ceil(x0 +48* math.cos(a))
  y = math.ceil(y0 +48* math.sin(a)* B)
  canvas.create_line(x0,y0,x,y,fill ='red')
 canvas.create_oval(x0 -60,y0 -60,x0 +60,y0 +60)for k inrange(501):for i inrange(17):
   a =(2* math.pi /16)* i +(2* math.pi /180)* k
   x = math.ceil(x0 +48* math.cos(a))
   y = math.ceil(y0 +48+ math.sin(a)* B)
   canvas.create_line(x0,y0,x,y,fill ='red')for j inrange(51):
   a =(2* math.pi /16)* i +(2* math.pi /180)* k -1
   x = math.ceil(x0 +48* math.cos(a))
   y = math.ceil(y0 +48* math.sin(a)* B)
   canvas.create_line(x0,y0,x,y,fill ='red')mainloop()

Example 060: String length

**Topic: ** Calculate the length of the string.

**Program analysis: ** None.

s='zhangguang101'print(len(s))

Example 061: Yanghui Triangle

**Title: ** Print out the first ten lines of Yang Hui's triangle.

**Program analysis: ** None.

def generate(numRows):
 r =[[1]]for i inrange(1,numRows):
  r.append(list(map(lambda x,y:x+y,[0]+r[-1],r[-1]+[0])))return r[:numRows]
a=generate(10)for i in a:print(i)

Example 062: Find the string

**Title: ** Find a string.

**Program analysis: ** None.

s1='aabbxuebixuebi'
s2='ab'
s3='xue'print(s1.find(s2))print(s1.find(s3))

Example 063: Draw an ellipse

**Topic: ** Draw an ellipse.

**Program analysis: ** Use tkinter.

if __name__ =='__main__':from tkinter import*
 x =360
 y =160
 top = y -30
 bottom = y -30
    
 canvas =Canvas(width =400,height =600,bg ='white')for i inrange(20):
  canvas.create_oval(250- top,250- bottom,250+ top,250+ bottom)
  top -=5
  bottom +=5
 canvas.pack()mainloop()

Example 64: Draw an ellipse, a rectangle

**Topic: ** Use ellipse and rectangle to draw pictures. .

**Program analysis: ** None.

if __name__ =='__main__':from tkinter import*
 canvas =Canvas(width =400,height =600,bg ='white')
 left =20
 right =50
 top =50
 num =15for i inrange(num):
  canvas.create_oval(250- right,250- left,250+ right,250+ left)
  canvas.create_oval(250-20,250- top,250+20,250+ top)
  canvas.create_rectangle(20-2* i,20-2* i,10*(i +2),10*( i +2))
  right +=5
  left +=5
  top +=10

 canvas.pack()mainloop()

Example 065: Drawing combined graphics

**Title: ** One of the most beautiful patterns.

**Program analysis: ** None.

import math
from tkinter import*classPTS:
 def __init__(self):
  self.x =0
  self.y =0
points =[]

def LineToDemo():
 screenx =400
 screeny =400
 canvas =Canvas(width = screenx,height = screeny,bg ='white')

 AspectRatio =0.85
 MAXPTS =15
 h = screeny
 w = screenx
 xcenter = w /2
 ycenter = h /2
 radius =(h -30)/(AspectRatio *2)-20
 step =360/ MAXPTS
 angle =0.0for i inrange(MAXPTS):
  rads = angle * math.pi /180.0
  p =PTS()
  p.x = xcenter +int(math.cos(rads)* radius)
  p.y = ycenter -int(math.sin(rads)* radius * AspectRatio)
  angle += step
  points.append(p)
 canvas.create_oval(xcenter - radius,ycenter - radius,
      xcenter + radius,ycenter + radius)for i inrange(MAXPTS):for j inrange(i,MAXPTS):
   canvas.create_line(points[i].x,points[i].y,points[j].x,points[j].y)

 canvas.pack()mainloop()if __name__ =='__main__':LineToDemo()

Example 066: Three-number sorting

**Topic: ** Enter 3 numbers a, b, c and output them in order of magnitude.

**Program analysis: ** Same as example 005.

raw=[]for i inrange(3):
 x=int(input('int%d: '%(i)))
 raw.append(x)for i inrange(len(raw)):for j inrange(i,len(raw)):if raw[i]>raw[j]:
   raw[i],raw[j]=raw[j],raw[i]print(raw)

raw2=[]for i inrange(3):
 x=int(input('int%d: '%(i)))
 raw2.append(x)print(sorted(raw2))

Example 067: Exchange location

**Topic: ** Input array, the largest exchange with the first element, the smallest exchange with the last element, output the array.

**Program analysis: ** None.

li=[3,2,5,7,8,1,5]

li[-1],li[li.index(min(li))]=li[li.index(min(li))],li[-1]

m=li[0]
ind=li.index(max(li))
li[0]=li[ind]
li[ind]=m

print(li)

Example 068: Rotating number sequence

**Question: ** There are n integers, so that the previous numbers are moved backward m positions, and the last m numbers become the first m numbers

**Program analysis: ** None.

from collections import*
li=[1,2,3,4,5,6,7,8,9]
deq=deque(li,maxlen=len(li))print(li)
deq.rotate(int(input('rotate:')))print(list(deq))

Example 069: Report the number

**Question: ** There are n people in a circle, arranged in order. Start counting from the first person (from 1 to 3). Anyone who reports to 3 exits the circle and asks which person is the original number left.

**Program analysis: ** None.

if __name__ =='__main__':
 nmax =50
 n =int(input('Please enter the total number of people:'))
 num =[]for i inrange(n):
  num.append(i +1)
 
 i =0
 k =0
 m =0while m < n -1:if num[i]!=0: k +=1if k ==3:
   num[i]=0
   k =0
   m +=1
  i +=1if i == n : i =0
 
 i =0while num[i]==0: i +=1print(num[i])

Example 070: String length II

**Topic: ** Write a function to find the length of a string, enter the string in the main function, and output its length.

**Program analysis: ** None.

def lenofstr(s):returnlen(s)print(lenofstr('tanxiaofengsheng'))

Example 071: Input and output

**Topic: ** Write input() and output() function inputs and output data records of 5 students.

**Program analysis: ** None.

N =3
# stu
# num : string
# name : string
# score[4]: list
student =[]for i inrange(5):
 student.append(['','',[]])
 
def input_stu(stu):for i inrange(N):
  stu[i][0]=input('input student num:\n')
  stu[i][1]=input('input student name:\n')for j inrange(3):
   stu[i][2].append(int(input('score:\n')))
 
def output_stu(stu):for i inrange(N):print('%-6s%-10s'%( stu[i][0],stu[i][1]))for j inrange(3):print('%-8d'% stu[i][2][j])if __name__ =='__main__':input_stu(student)print(student)output_stu(student)

Example 072: Create a linked list

**Subject: ** Create a linked list.

**Program analysis: ** The original text is not very reliable.

classNode:

 def __init__(self, data):
  self.data = data
  self.next = None

 def get_data(self):return self.data

classList:

 def __init__(self, head):
  self.head = head

 def is_empty(self):return self.get_len()==0

 def get_len(self):  
  length =0
  temp = self.head
  while temp is not None:
   length +=1
   temp = temp.next
  return length

 def append(self, node):
  temp = self.head
  while temp.next is not None:
   temp = temp.next
  temp.next = node

 def delete(self, index):if index <1 or index > self.get_len():print("The given location is unreasonable")returnif index ==1:
   self.head = self.head.next
   return
  temp = self.head
  cur_pos =0while temp is not None:
   cur_pos +=1if cur_pos == index-1:
    temp.next = temp.next.next
   temp = temp.next

 def insert(self, pos, node):if pos <1 or pos > self.get_len():print("The location of the inserted node is unreasonable")return
  temp = self.head
  cur_pos =0while temp is not Node:
   cur_pos +=1if cur_pos == pos-1:
    node.next = temp.next
    temp.next =node
    break
   temp = temp.next

 def reverse(self, head):if head is None and head.next is None:return head
  pre = head
  cur = head.next
  while cur is not None:
   temp = cur.next
   cur.next = pre
   pre = cur
   cur = temp
  head.next = None
  return pre

 def print_list(self, head):
  init_data =[]while head is not None:
   init_data.append(head.get_data())
   head = head.next
  return init_data

if __name__=='__main__':
 head=Node('head')
 link=List(head)for i inrange(10):
  node=Node(i)
  link.append(node)print(link.print_list(head))

Example 073: Reverse output linked list

**Title: ** Output a linked list in reverse.

**Program analysis: ** None.

classNode:

 def __init__(self, data):
  self.data = data
  self.next = None

 def get_data(self):return self.data

classList:

 def __init__(self, head):
  self.head = head

 def is_empty(self):return self.get_len()==0

 def get_len(self):  
  length =0
  temp = self.head
  while temp is not None:
   length +=1
   temp = temp.next
  return length

 def append(self, node):
  temp = self.head
  while temp.next is not None:
   temp = temp.next
  temp.next = node

 def delete(self, index):if index <1 or index > self.get_len():print("The given location is unreasonable")returnif index ==1:
   self.head = self.head.next
   return
  temp = self.head
  cur_pos =0while temp is not None:
   cur_pos +=1if cur_pos == index-1:
    temp.next = temp.next.next
   temp = temp.next

 def insert(self, pos, node):if pos <1 or pos > self.get_len():print("The location of the inserted node is unreasonable")return
  temp = self.head
  cur_pos =0while temp is not Node:
   cur_pos +=1if cur_pos == pos-1:
    node.next = temp.next
    temp.next =node
    break
   temp = temp.next

 def reverse(self, head):if head is None and head.next is None:return head
  pre = head
  cur = head.next
  while cur is not None:
   temp = cur.next
   cur.next = pre
   pre = cur
   cur = temp
  head.next = None
  return pre

 def print_list(self, head):
  init_data =[]while head is not None:
   init_data.append(head.get_data())
   head = head.next
  return init_data

if __name__=='__main__':
 head=Node('head')
 link=List(head)for i inrange(10):
  node=Node(i)
  link.append(node)print(link.print_list(head))print(link.print_list(link.reverse(head)))

Example 074: List sorting, connection

**Topic: ** List sorting and connection.

**Program analysis: ** Sorting can use the sort() method, and connection can use the + sign or extend() method.

a=[2,6,8]
b=[7,0,4]
a.extend(b)
a.sort()print(a)

Example 075: I don’t know what to do

**Topic: ** Relax, it's a simple topic.

**Program analysis: ** The ghost knows what it is.

if __name__ =='__main__':for i inrange(5):
  n =0if i !=1: n +=1if i ==3: n +=1if i ==4: n +=1if i !=4: n +=1if n ==3:print(64+ i)

Example 076: Make a function

**Topic: ** Write a function, when the input n is an even number, call the function to find 1/2+1/4+...+1/n, when the input n is an odd number, call the function 1/1+1/3+ ...+1/n

**Program analysis: ** None.

def peven(n):
 i =0
 s =0.0for i inrange(2,n +1,2):
  s +=1.0/ i
 return s
 
def podd(n):
 s =0.0for i inrange(1, n +1,2):
  s +=1.0/ i
 return s
 
def dcall(fp,n):
 s =fp(n)return s
 
if __name__ =='__main__':
 n =int(input('input a number: '))if n %2==0:
  sum =dcall(peven,n)else:
  sum =dcall(podd,n)print(sum)

Example 077: Traverse the list

**Title: ** Circulate output list

**Program analysis: ** None.

l=['moyu','niupi','xuecaibichi','shengfaji','42']for i inrange(len(l)):print(l[i])

Example 078: Dictionary

**Topic: ** Find the oldest person and output it. Please find out what is wrong in the program.

**Program analysis: ** None.

if __name__ =='__main__':
 person ={"li":18,"wang":50,"zhang":20,"sun":22}
 m ='li'for key in person.keys():if person[m]< person[key]:
   m = key
 
 print('%s,%d'%(m,person[m]))

Example 079: String sorting

**Subject: ** String sorting.

**Program analysis: ** None.

l=['baaa','aaab','aaba','aaaa','abaa']
l.sort()print(l)

Example 080: Monkey divides peaches

**Subject: ** There is a pile of peaches on the beach, and five monkeys will divide it. The first monkey divided the pile of peaches into five evenly. One more was added. The monkey threw the more into the sea and took one. The second monkey divided the remaining peaches into five equally, and added one more. It also threw the extra one into the sea and took away one. The third, fourth, and fifth monkeys did the same. Yes, how many peaches are there on the beach?

**Program analysis: ** None.

if __name__ =='__main__':
 i =0
 j =1
 x =0while(i <5):
  x =4* j
  for i inrange(0,5):if(x%4!=0):breakelse:
    i +=1
   x =(x/4)*5+1
  j +=1print(x)for p inrange(5):
  x=(x-1)/5*4print(x)

Example 081: Find the unknown number

Question: ** 809??=800??+9*?? where?? represents two digits, 809*?? is four digits, and the result of 8*?? is two digits, 9*? The result of? Is 3 digits. Find the two digits represented by ?? and the result after 809*??.

**Program analysis: ** None.

a =809for i inrange(10,100):
 b = i * a
 if b >=1000 and b <=10000 and 8* i <100 and 9* i >=100:print(b,' = 800 * ', i,' + 9 * ', i)for i inrange(10,100):if8*i>99 or 9*i<100:continueif809*i==800*i+9*i:print(i)break

Example 082: Convert Octal to Decimal

**Topic: ** Convert octal to decimal

**Program analysis: ** None.

n=eval('0o'+str(int(input('Octal input:'))))print(n)

Example 083: Making odd numbers

**Question: ** Find the odd number that can be composed of 0-7.

**Program analysis: **

The number of digits is 4. 1, 3, 5, 7 end

The 2 digits are 7*4. The first digit cannot be 0

The three-digit number is 784. Random in between

The 4 digits are 788*4.

if __name__ =='__main__':
 sum =4
 s =4for j inrange(2,9):print(sum)if j <=2:
   s *=7else:
   s *=8
  sum += s
 print('sum = %d'% sum)

Example 084: Connection string

**Subject: ** Connection string.

**Program analysis: ** None.

delimiter =','
mylist =['Brazil','Russia','India','China']print(delimiter.join(mylist))

Example 085: Divide

**Question: ** Enter an odd number, and then determine that at least a few 9 divided by the number is an integer.

**Program analysis: ** 999999/13 = 76923.

if __name__ =='__main__':
 zi =int(input('Enter a number:'))
 n1 =1
 c9 =1
 m9 =9
 sum =9while n1 !=0:if sum % zi ==0:
   n1 =0else:
   m9 *=10
   sum += m9
   c9 +=1print('%d 9s can be%d divisible: %d'%(c9,zi,sum))
 r = sum / zi
 print('%d / %d = %d'%(sum,zi,r))

Example 086: Connection string II

**Subject: ** Two string concatenation procedures.

**Program analysis: ** None.

a='guangtou'
b='feipang'print(b+a)

Example 087: Access to class members

**Question: ** Answer result (transmission of structure variable).

**Program analysis: ** None.

if __name__ =='__main__':classstudent:
  x =0
  c =0
 def f(stu):
  stu.x =20
  stu.c ='c'
 a=student()
 a.x =3
 a.c ='a'f(a)print(a.x,a.c)

Example 088: Print an asterisk

**Title: ** Read the integer value of 7 numbers (1-50), each time a value is read, the program prints out the number of the value *.

**Program analysis: ** None.

for i inrange(3):print('*'*int(input('input a number: ')))

Example 089: Decoding

**Topic: ** A company uses public telephones to transmit data. The data is a four-digit integer and is encrypted during the transmission. The encryption rules are as follows: add 5 to each number, and then replace it with the remainder of the sum divided by 10 Number, then swap the first and fourth digits, and swap the second and third digits.

**Program analysis: ** None.

n=input()
n =str(n)
a=[]for i inrange(4):
 a.append((int(n[i])+5)%10)
a[0],a[3]=a[3],a[0]
a[1],a[2]=a[2],a[1]print("".join('%s'%s for s in a))

Example 090: Detailed explanation of the list

**Title: ** Examples of List Usage.

**Program analysis: ** None.

# list  
# New list
testList=[10086,'China Mobile',[1,2,4,5]]  
  
# Access list length
print(len(testList))
# To the end of the list
print(testList[1:])
# Add elements to the list
testList.append('i\'m new here!')print(len(testList))print(testList[-1])
# The last element of the pop-up list
print(testList.pop(1))print(len(testList))print(testList  )
# list comprehension  
# There is an introduction later, just pass by
matrix =[[1,2,3],[4,5,6],[7,8,9]]print(matrix  )print(matrix[1])
col2 =[row[1]for row in matrix]#get a  column from a matrix  
print(col2  )
col2even =[row[1]for row in matrix if  row[1]%2==0]#filter odd item  
print(col2even)

Example 091: time module

**Topic: ** Example 1 of time function.

**Program analysis: ** None.

if __name__ =='__main__':import time
 print(time.ctime(time.time()))print(time.asctime(time.localtime(time.time())))print(time.asctime(time.gmtime(time.time())))

Example 092: time module II

**Topic: ** Time function example 2.

**Program analysis: ** How to waste time.

if __name__ =='__main__':import time
 start = time.time()for i inrange(3000):print(i)
 end = time.time()print(end - start)

Example 093: time module III

**Topic: ** Time function example 3.

**Program analysis: ** How to waste time.

if __name__ =='__main__':import time
 start = time.clock()for i inrange(100):print(i)
 end = time.clock()print('different is %6.3f'%(end - start))

Example 094: time module IV

**Topic: ** Example of time function 4.

**Program analysis: ** How to waste time.

if __name__ =='__main__':import time
 import random
    
 play_it =input('do you want to play it.(\'y\' or \'n\')')while play_it =='y':
  c =input('input a character:\n')
  i = random.randint(0,2**32)%100print('please input number you guess:\n')
  start = time.clock()
  a = time.time()
  guess =int(input('input your guess:\n'))while guess != i:if guess > i:print('please input a little smaller')
    guess =int(input('input your guess:\n'))else:print('please input a little bigger')
    guess =int(input('input your guess:\n'))
  end = time.clock()
  b = time.time()var=(end - start)/18.2print(var)
  # print 'It took you %6.3 seconds'% time.difftime(b,a))ifvar<15:print('you are very clever!')
  elif var<25:print('you are normal!')else:print('you are stupid!')print('Congradulations')print('The number you guess is %d'% i)
  play_it =input('do you want to play it.')

Example 095: Conversion time format

**Topic: ** The string date is converted to a readable date format.

**Program analysis: ** Just look at it, dateutil is a third-party library.

from dateutil import parser
dt = parser.parse("Aug 28 2015 12:00AM")print(dt)

Example 096: Calculate the number of repetitions

**Topic: ** Count the number of occurrences of substrings in a string.

**Program analysis: ** None.

s1='xuebixuebixuebixuebixuebixuebixuebixue'
s2='xuebi'print(s1.count(s2))

Example 097: Disk writing

**Topic: ** Enter some characters from the keyboard, write them to the disk file one by one, until you enter a #.

**Program analysis: ** None.

if __name__ =='__main__':from sys import stdout
 filename =input('Input file name:\n')
 fp =open(filename,"w")
 ch =input('Input string:\n')while ch !='#':
  fp.write(ch)
  stdout.write(ch)
  ch =input('')
 fp.close()

Example 098: Disk Write II

**Topic: ** Input a string from the keyboard, convert all lowercase letters into uppercase letters, and then output to a disk file "test" to save.

**Program analysis: ** None.

if __name__ =='__main__':
 fp =open('test.txt','w')
 string =input('please input a string:\n')
 string = string.upper()
 fp.write(string)
 fp =open('test.txt','r')print(fp.read())
 fp.close()

Example 099: Disk read and write

**Topic: ** There are two disk files A and B, each storing a line of letters. It is required to merge the information in these two files (in alphabetical order) and output to a new file C.

**Program analysis: ** None.

if __name__ =='__main__':import string
 fp =open('test1.txt')
 a = fp.read()
 fp.close()
 
 fp =open('test2.txt')
 b = fp.read()
 fp.close()
 
 fp =open('test3.txt','w')
 l =list(a + b)
 l.sort()
 s =''
 s = s.join(l)
 fp.write(s)
 fp.close()

Example 100: List to dictionary

**Title: ** List converted to dictionary.

**Program analysis: ** None.

i =['a','b']
l =[1,2]print(dict(zip(i,l)))

Sharing or watching is my greatest support

Recommended Posts

100 small Python examples
Python reads .nii format image examples
Analysis of usage examples of Python yield
Python processing PDF and CDF examples
Some examples of python operation redis
Python generates VOC format label examples
Python multithreading
Python FAQ
Python3 dictionary
Python3 module
python (you-get)
Python string
Python basics
Python descriptor
Python basics 2
Python exec
Python notes
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python IO
Python multithreading
Python toolchain
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Python class decorator, use a small demo
Python analytic
Python basics
07. Python3 functions
Python basics 3
Python Romberg method to find integral examples
Python multitasking-threads
Python functions
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
python queue Queue
Python basics 4
Python basics 5
python-Use python to write a small shopping program
Detailed examples of using Python to calculate KS