# 40 Python entry applet

2022-01-30 08:29:13

Many students have finished Python It is still difficult to use it flexibly . I sort out 37 individual Python Entry applet . Application in practice Python There will be a half power effect . Share Github project , There's a collection of Python Learning materials github.com/duma-repo/g…

##### Example 1： Fahrenheit to Celsius

The formula for Fahrenheit to Celsius ：C = (F - 32) / 1.8. This example examines Python The addition, subtraction, multiplication and division operators of .

"""  Convert Fahrenheit to Celsius  """

f = float(input(' Enter Fahrenheit temperature : '))
c = (f - 32) / 1.8
print('%.1f  Fahrenheit  = %.1f  Centigrade ' % (f, c))
Copy code 
##### Example 2： Calculate the circumference and area of a circle

Enter the radius , Calculate the radius and area of the circle , Circumference formula ：2*π*r, Interview formula ：π*r^2

"""  Radius calculates the circumference and area of a circle  """

radius = float(input(' Enter the radius of the circle : '))
perimeter = 2 * 3.1416 * radius
area = 3.1416 * radius * radius
print(' Perimeter : %.2f' % perimeter)
print(' area : %.2f' % area)
Copy code 
##### Example 3： Realize the unary primary function

Realize the unary primary function in Mathematics ：f(x) = 2x + 1

"""  Univariate function  """

x = int(input(' Input x：'))
y = 2 * x + 1
print('f(%d) = %d' % (x, y))
Copy code 
##### Example 4： Realize binary quadratic function

Realize the binary quadratic function in mathematics ：f(x, y) = 2x^2 + 3y^2 + 4xy, Exponential operator is required **

"""  Bivariate quadratic function  """

x = int(input(' Input x：'))
y = int(input(' Input y：'))

z = 2 * x ** 2 + 3 * y ** 2 + 4 * x * y
print('f(%d, %d) = %d' % (x, y, z))
Copy code 
##### Example 5： Separates the single digits of an integer

The single digit of a positive integer , And partial separation except single digits . Need to use  model （ Take the remainder ） Operator %, and  to be divisible by  Operator //

"""  Separate integer and single digits  """

x = int(input(' Input integer ：'))

single_dig = x % 10
exp_single_dig = x // 10

print(' Single digit ： %d' % single_dig)
print(' Except for single digits ： %d' % exp_single_dig)
Copy code 
##### Example 6： Implement an accumulator

Implement a simple accumulator , User input is acceptable 3 A digital , And add it up . Need to use  Compound assignment operator ：+=

"""  accumulator  v1.0 """

s = 0

x = int(input(' Input integer ：'))
s += x

x = int(input(' Input integer ：'))
s += x

x = int(input(' Input integer ：'))
s += x

print(' The sum of the ：%d' % s)
Copy code 
##### Example 7： Judgement of leap year

Year of importation , Determine if it's a leap year . Leap year judgment method ： Can be 4 to be divisible by , But can't be 100 to be divisible by ; Or can be 400 to be divisible by . Need to use  Arithmetic operator  and  Logical operators

"""  Judgement of leap year  """

year = int(input(' Year of importation : '))
is_leap = year % 4 == 0 and year % 100 != 0 or year % 400 == 0
print(is_leap)
Copy code 
##### Example 8： Judge odd even number

Enter a number , Determine whether the cardinality is even , need  model  Operation and if ... else structure

"""  Judge odd even number  """

in_x = int(input(' Input integer ：'))

if in_x % 2 == 0:
print(' even numbers ')
else:
print(' Odd number ')
Copy code 
##### Example 9： Guess the size

The user enters a 1-6 Integer between , Compare with the number randomly generated by the program . Need to use if ... elif ... else structure

"""  Guess the size  """

import random

in_x = int(input(' Input integer ：'))
rand_x = random.randint(1, 6)
print(' Program random number ： %d' % rand_x)

if in_x > rand_x:
print(' User win ')
elif in_x < rand_x:
print(' The program won ')
else:
print(' Strike a level ')
Copy code 

explain ：random yes Python Random number module , call random.randint You can generate a random number , The type is int.randint(1, 6) To generate [1, 6] Random number between .

##### Example 10： Judgement of leap year

Before judging leap year is output True or False, You need to output the text version this time  Leap year  or  Ordinary year

"""  Judgement of leap year  """

year = int(input(' Year of importation : '))
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print(' Leap year ')
else:
print(' Ordinary year ')
Copy code 
##### Example 11： Degrees Celsius and Fahrenheit rotate with each other

I've done Fahrenheit to Celsius before , Now through  Branching structure  Realize the mutual transformation of the two .

"""  Degrees Celsius and Fahrenheit are interchangeable  """

trans_type = input(' Enter Celsius or Fahrenheit ：')

if trans_type == ' Centigrade ':  #  Execute the logic of Fahrenheit to Celsius
f = float(input(' Enter Fahrenheit temperature ：'))
c = (f - 32) / 1.8
print(' The temperature in centigrade is ：%.2f' % c)
elif trans_type == ' Fahrenheit ':  #  Execute the logic of Celsius to Fahrenheit
c = float(input(' Enter the temperature in centigrade ：'))
f = c * 1.8 + 32
print(' The temperature in Fahrenheit is ：%.2f' % f)
else:
print(' Please enter   Fahrenheit   or   Centigrade ')
Copy code 
##### Example 12： Whether it forms a triangle

Enter the length of the three edges , Judge whether a triangle is formed . The conditions for forming a triangle ： The sum of the two sides is greater than that of the third side .

"""  Whether it forms a triangle  """
a = float(input(' Enter the three sides of the triangle ：\n a = '))
b = float(input(' b = '))
c = float(input(' c = '))
if a + b > c and a + c > b and b + c > a:
print(' Can form a triangle ')
else:
print(' Can't make a triangle ')
Copy code 
##### Example 13： Output grade

Enter score , Output the grade corresponding to the score .

>=90 get a share A,[80, 90) have to B,[70, 80) have to C,[60, 70) have to D,< 60 have to E

"""  Output grade  """

score = float(input(' Please enter the grade : '))
if score >= 90:
elif score >= 80:
elif score >= 70:
elif score >= 60:
else:
Copy code 
##### Example 14： Calculate the Commission

The bonus of an enterprise is calculated according to the following rules according to the sales profit . Enter sales profit , Calculate the bonus .

profits <= 10 ten thousand , Bonus can be raised 10%

10 ten thousand < profits <= 20 ten thousand , Higher than 10 The part of Wan 7.5%

20 ten thousand < profits <= 40 ten thousand , Higher than 20 The part of ten thousand yuan is withdrawn 5%

40 ten thousand < profits <= 60 ten thousand , Higher than 40 The part of ten thousand yuan is withdrawn 3%

profits > 60 ten thousand , exceed 60 The part of Wan 1%

"""  Calculate the Commission  v1.0 """

profit = float(input(' Enter sales profit （ element ）： '))

if profit <= 100000:
bonus = profit * 0.1
elif profit <= 200000:
bonus = 100000 * 0.1 + (profit - 100000) * 0.075
elif profit <= 400000:
bonus = 100000 * 0.1 + 200000 * 0.075 + (profit - 200000) * 0.05
elif profit <= 600000:
bonus = 100000 * 0.1 + 200000 * 0.075 + 400000 * 0.05 + (profit - 400000) * 0.03
else:
bonus = 100000 * 0.1 + 200000 * 0.075 + 400000 * 0.05 + 600000 * 0.03 + (profit - 600000) * 0.01

print(' Bonus ：%.2f' % bonus)
Copy code 
##### Example 15： Implement piecewise functions

Piecewise functions are often seen in Mathematics , The following piecewise functions are implemented by program

$f(x) = \begin{cases} 3x^2 + 4 & (x \gt 0) \\ 2x + 2 & (x \le 0) \end{cases}$
"""  Piecewise functions  """

x = int(input(' Input ：'))

if x > 0:
y = 3 * x ** 2 + 4
else:
y = 2 * x + 2

print('f(%d) = %d' % (x, y))
Copy code 
##### Example 16：1-n Sum up

Enter a positive integer n, Calculation 1 + 2 + ... + n Result .

""" 1-n Sum up  """

n = int(input(' Input n：'))

s = 0
while n >= 1:
s += n
n -= 1

print('1-%d  Summation result ： %d' % (n, s))
Copy code 
##### Example 17： accumulator v2.0

The accumulator previously implemented can only support 3 Add up the numbers , Now you need to remove this restriction , Can add up indefinitely .

"""  accumulator  v1.0 """

s = 0
while True:
in_str = input(' Input integer （ Input q, The exit ）：')

if in_str == 'q':
break

x = int(in_str)
s += x
print(' Add and ：%d' % s)
Copy code 
##### Example 18： Guess the game

The program randomly generates a positive integer , Users guess , The program gives the corresponding prompt according to the guessed size . Last , The output user guessed how many times to guess .

"""  Guess the game  """

import random

answer = random.randint(1, 100)
counter = 0
while True:
counter += 1
number = int(input(' Guess a number （1-100）: '))
if number < answer:
print(' A little bigger. ')
elif number > answer:
print(' A little smaller ')
else:
print(' Guessed it ')
break

print(f' Guess together {counter} Time ')
Copy code 
##### Example 19： Print multiplication table
"""  Print multiplication table  """

for i in range(1, 10):
for j in range(1, i + 1):
print(f'{i}*{j}={i * j}', end='\t')
Copy code 
##### Example 20： Is it a prime

Enter a positive integer , Judge whether it is a prime number . Definition of prime number ： Greater than 1 Of the natural number , Can only be 1 And the natural number divisible by itself . Such as ：3、5、7

"""  Judge whether it is a prime number  """

num = int(input(' Please enter a positive integer : '))
end = int(num // 2) + 1  #  Just judge whether the first half can be divided , The first half has nothing divisible, so , The second half must not

is_prime = True
for x in range(2, end):
if num % x == 0:
is_prime = False
break
if is_prime and num != 1:
print(' prime number ')
else:
print(' Not primes ')
Copy code 

range(2, end) Can generate 2, 3, ... end Sequence , And assign values to x Execute loop .range There are also the following uses

range(10)： Generate 0, 1, 2, ... 9 Sequence

range(1, 10, 2)： Generate 1, 3, 5, ... 9 Sequence

##### Example 21： Fibonacci sequence

Enter a positive integer n, Computation first n Fibonacci number of bits . The number of the current position of the Fibonacci sequence is equal to the sum of the first two numbers ,1 1 2 3 5 8 ...

"""  Fibonacci sequence  v1.0 """

n = int(input(' Input n： '))
a, b = 0, 1
for _ in range(n):
a, b = b, a + b

print(f' The first  {n}  The Fibonacci number is ：{a}')
Copy code 
##### Example 22： Narcissistic number

The number of daffodils is a 3 digit , The cube sum of the number in each bit of the number is exactly equal to itself , for example ：

$153=1^3+5^3+3^3$
"""  Narcissistic number  """

for num in range(100, 1000):
low = num % 10
mid = num // 10 % 10
high = num // 100
if num == low ** 3 + mid ** 3 + high ** 3:
print(num)
Copy code 
##### Example 23： Monkeys eat peaches

The monkey picked it on the first day n A peach , I ate half that day , It's not addictive , Another one

The next morning I ate half of the rest of the peaches , Another one

After that, I ate half and one of the rest of the day before every morning .

To the first 10 When I want to eat again in the morning , There's a peach left . Ask how much you picked on the first day .

Think in reverse ： The first n-1 Heaven's peach = ( The first n Tiantao + 1) * 2, from The first 10 The first day of the day cycle can be

"""  Monkeys eat peaches  """

peach = 1
for i in range(9):
peach = (peach + 1) * 2
print(peach)
Copy code 
##### Example 24： Print diamond

Output the following diamond pattern

***

*****

*******

*****

***

"""  Output diamond  """

for star_num in range(1, 7, 2):
blank_num = 7 - star_num
for _ in range(blank_num // 2):
print(' ', end='')
for _ in range(star_num):
print('*', end='')
for _ in range(blank_num // 2):
print(' ', end='')
print()

for _ in range(7):
print('*', end='')

print()

for star_num in range(5, 0, -2):
blank_num = 7 - star_num
for _ in range(blank_num // 2):
print(' ', end='')
for _ in range(star_num):
print('*', end='')
for _ in range(blank_num // 2):
print(' ', end='')
print()
Copy code 
##### Example 25： Calculate the Commission v2.0

take  Example 14： Calculate the Commission  Use list instead + The way of circulation , The code is simpler , And can handle more flexibly .

"""  Calculate the Commission  v2.0 """

profit = int(input(' Enter sales profit （ element ）： '))
bonus = 0
thresholds = [100000, 200000, 400000, 600000]
rates = [0.1, 0.075, 0.05, 0.03, 0.01]

for i in range(len(thresholds)):
if profit <= thresholds[i]:
bonus += profit * rates[i]
break
else:
bonus += thresholds[i] * rates[i]

bonus += (profit - thresholds[-1]) * rates[-1]
print(' Bonus ：%.2f' % bonus)
Copy code 
##### Example 26： One day is the day of the year

Enter a date , The day of calculation is the day of the year

"""  Calculate the day of the year  """

months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
res = 0
year = int(input(' year : '))
month = int(input(' month : '))
day = int(input(' What's the number : '))

if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: #  February of leap year  29  God
months += 1

for i in range(month):
res += months[i]

print(res+day)
Copy code 
##### Example 27： Palindrome string

Determine whether a string is  Palindrome string , Palindrome string is a string with the same forward reading and reverse reading , Such as ：level

"""  Determine whether it is a palindrome string  """

s = input(' Input string ：')

i = 0
j = -1
s_len = len(s)
flag = True

while i != s_len + j:
if s[i] != s[j]:
flag = False
break
i += 1
j += -1

print(' It's a palindrome string ' if flag else ' It's not a palindrome string ')
Copy code 
##### Example 28： Personal information input and output

Without defining a class , Personal information can be saved in Yuanzu

students = []
while True:
input_s = input(' Input student information （ Student number   full name   Gender ）, The blank space to separate （ Input q, The exit ）：')

if input_s == 'q':
break

input_cols = input_s.split(' ')
students.append((input_cols, input_cols, input_cols))

print(students)
Copy code 
##### Example 29： Sort personal information

Personal information is stored in tuples , And according to the student number 、 Sort by name or gender .

"""  Sort personal information  """

students = []
cols_name = [' Student number ', ' full name ', ' Gender ']
while True:
input_s = input(' Input student information （ Student number   full name   Gender ）, The blank space to separate （ Input q, The exit ）：')

if input_s == 'q':
break

input_cols = input_s.split(' ')
students.append((input_cols, input_cols, input_cols))

sorted_col = input(' Enter the sort attribute ：')
sorted_idx = cols_name.index(sorted_col)  #  Get the index of the tuple according to the input attribute

print(sorted(students, key=lambda x: x[sorted_idx]))
Copy code 
##### Example 30： De duplication of input

De duplication of input , Direct use Python in Set Set implementation

"""  duplicate removal  """

input_set = set()

while True:
s = input(' Input content （ Input q, The exit ）：')

if s == 'q':
break

print(input_set)
Copy code 
##### Example 31： Output set intersection

Given Python web The engineer  and  Algorithm engineer  Skills needed , Calculate the intersection of the two .

"""  set intersection  """

python_web_programmer = set()

ai_programmer = set()
ai_programmer.add(' machine learning ')

inter_set = python_web_programmer.intersection(ai_programmer)
print(' Skill intersection ：', end='')
print(inter_set)
Copy code 

Python set In addition to calculating the intersection , You can also calculate Union 、 Complement set

##### Example 32： Guessing game

Use the program to realize the stone scissors paper game .

"""  Guessing game  """

# 0 For cloth ,1 Represents scissors ,2 It stands for stone
import random

rule = {' cloth ': 0, ' scissors ': 1, ' stone ': 2}

rand_res = random.randint(0, 2)
input_s = input(' Enter the stone 、 scissors 、 cloth ：')
input_res = rule[input_s]
win = True

if abs(rand_res - input_res) == 2:  #  Difference between 2 It means that cloth meets stone , The one who gives the cloth wins
if rand_res == 0:
win = False
elif rand_res > input_res:  #  Difference between 1 Who is the bigger and who wins
win = False

print(f' Program out ：{list(rule.keys())[rand_res]}, Input ：{input_res}')

if rand_res == input_res:
print(' flat ')
else:
print(' win ' if win else ' transport ')
Copy code 
##### Example 33： Dictionary sort

Dictionary key It's the name ,value It's height , Now you need to reorder the dictionary by height .

"""  Dictionary sort  """

hs = {' Zhang San ': 178, ' Li Si ': 185, ' Wang Ma Zi ': 175}

print(dict(sorted(hs.items(), key=lambda item: item)))
Copy code 
##### Example 34： Bivariate quadratic function v2.0

Encapsulate bivariate quadratic functions in functions , Convenient to call

"""  Bivariate quadratic function  v2.0 """

def f(x, y):
return 2 * x ** 2 + 3 * y ** 2 + 4 * x * y

print(f'f(1, 2) = {f(1, 2)}')
Copy code 
##### Example 35： Fibonacci sequence v2.0

Use the form of recursive function to generate Fibonacci sequence

"""  Recursive Fibonacci sequence  """

def fib(n):
return 1 if n <= 2 else fib(n-1) + fib(n-2)

print(f' The first  10  The Fibonacci number is ：{fib(10)}')
Copy code 
##### Example 36： Factorial

Define a function , Realize factorials .n Factorial definition of ：n! = 1*2*3* ... n

"""  Factorial function  """

def fact(n):
return 1 if n == 1 else fact(n-1) * n

print(f'10! = {fact(10)}')
Copy code 
##### Example 37： Realization range function

Write a program similar to Python Medium range Function of function

""" range function  """

def range_x(start, stop, step):
res = []
while start < stop:
res.append(start)

start += step
return res
Copy code