Many students still have difficulty using Python flexibly after learning it. I compiled 37 small programs for getting started with Python. Using Python in practice can be much more effective.
Share Github project, which collects Python learning materials github.com/duma-repo/g…
Example 1: Convert Fahrenheit temperature to Celsius temperature
The formula for converting Fahrenheit to Celsius is C = (F-32) / 1.8. This example examines Python’s addition, subtraction, multiplication and division operators.
"" convert Fahrenheit temperature to Celsius temperature. ""
f = float(input('Input Fahrenheit:'))
c = (f - 32) / 1.8
print('%.1F F = %.1F C ' % (f, c))
Copy the code
Example 2: Calculate the circumference and area of a circle
Enter the radius, calculate the radius and area of the circle, circle length 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 the code
Example 3: Implementing a unary once function
F (x) = 2x + 1
"" function of one variable ""
x = int(input('Enter x:'))
y = 2 * x + 1
print('f(%d) = %d' % (x, y))
Copy the code
Example 4: Implementing a binary quadratic function
F (x, y) = 2x^2 + 3y^2 + 4xy
Quadratic function of two variables
x = int(input('Enter x:'))
y = int(input('Enter y:'))
z = 2 * x ** 2 + 3 * y ** 2 + 4 * x * y
print('f(%d, %d) = %d' % (x, y, z))
Copy the code
Example 5: Separate the units digit of an integer
Separates the units digit of a positive integer from all but the units digit. You need the modulo (remainder) operator %, and the divisor operator //
""" Separate the integer single digit ""
x = int(input('Enter an integer:'))
single_dig = x % 10
exp_single_dig = x // 10
print('Single digit: %d' % single_dig)
print('except the one digit: %d' % exp_single_dig)
Copy the code
Example 6: Implementing an accumulator
Implement a simple accumulator that can accept user input of three numbers and add them up. We need the compound assignment operator: +=
""" Accumulator V1.0 ""
s = 0
x = int(input('Enter an integer:'))
s += x
x = int(input('Enter an integer:'))
s += x
x = int(input('Enter an integer:'))
s += x
print('Sum: %d' % s)
Copy the code
Example 7: Determining leap years
Enter the year to check whether it is a leap year. Leap year: divisible by 4, but not by 100; Or it could be divisible by 400. You need both arithmetic and logical operators
""" Judge leap year """
year = int(input('Enter year:'))
is_leap = year % 4= =0 and year % 100! =0 or year % 400= =0
print(is_leap)
Copy the code
Example 8: Determine odd and even numbers
Enter a number and determine whether the cardinality is even, using modular arithmetic and if… The else structure
""" Judge odd even """
in_x = int(input('Enter an integer:'))
if in_x % 2= =0:
print('even number')
else:
print('odd')
Copy the code
Example 9: Guess the size
The user enters an integer between 1 and 6 to be compared with a number randomly generated by the program. You need to use if… elif … The else structure
""" Guess the size """
import random
in_x = int(input('Enter an integer:'))
rand_x = random.randint(1.6)
print('Program random number: %d' % rand_x)
if in_x > rand_x:
print('User wins')
elif in_x < rand_x:
print('Program wins')
else:
print('draw')
Copy the code
Random is a Python module for random numbers. A call to random. Randint generates a random number of type int. Randint (1, 6) represents the random number generated between [1, 6].
Example 10: Determining leap years
This time, we need to print a literal leap year or an ordinary year
""" Judge leap year """
year = int(input('Enter year:'))
if year % 4= =0 and year % 100! =0 or year % 400= =0:
print('leap year')
else:
print('common year')
Copy the code
Example 11: Celsius and Fahrenheit turn each other
We did Fahrenheit to Celsius, and now we have a branching structure that allows them to rotate each other.
""" Celsius is interchangeable with Fahrenheit. """
trans_type = input('Input in Degrees Celsius or Fahrenheit:')
if trans_type == 'Celsius': # Perform the logic of Fahrenheit to Celsius
f = float(input('Input Fahrenheit:'))
c = (f - 32) / 1.8
print('Celsius temperature: %.2F' % c)
elif trans_type == 'Fahrenheit': # Perform the Celsius to Fahrenheit logic
c = float(input('Enter Celsius temperature:'))
f = c * 1.8 + 32
print('Fahrenheit temperature: %.2f' % f)
else:
print('Please enter Fahrenheit or Celsius')
Copy the code
Example 12: Whether to form a triangle
Enter the length of three sides to determine whether they form a triangle. Conditions for forming a triangle: the sum of the two sides is greater than the third side.
""" Does it form a triangle """
a = float(input('Input 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(It doesn't make a triangle.)
Copy the code
Example 13: Output grade levels
Input score, output score corresponding grade.
>=90 get A, B, C, D, E < 60
""" Output grade """
score = float(input('Please enter result:'))
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'E'
print('The grade is :', grade)
Copy the code
Example 14: Calculate commissions
The bonus of an enterprise is calculated as a commission according to the following rules. Enter the sales profit and calculate the bonus.
Profit <= 100,000, bonus can be raised 10%
100,000 < profit <= 200,000, the part higher than 100,000 will be raised 7.5%
200,000 < profit <= 400,000, 5% of the part higher than 200,000
400,000 < profit <= 600,000, 3% for the part higher than 400,000 yuan
If the profit is > 600,000, 1% will be deducted for the portion exceeding 600,000
""" Calculate royalty V1.0 """
profit = float(input('Input sales profit (yuan) :'))
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 the code
Example 15: Implementing a piecewise function
Mathematics often see segment function, with the program to achieve the following segment function
""" piecewise function ""
x = int(input('Enter:'))
if x > 0:
y = 3 * x ** 2 + 4
else:
y = 2 * x + 2
print('f(%d) = %d' % (x, y))
Copy the code
Example 16:1-n summation
Enter a positive integer n to calculate 1 + 2 +… Plus n.
Sum of 1 minus n
n = int(input('Enter n:'))
s = 0
while n >= 1:
s += n
n -= 1
print('1-%d ' % (n, s))
Copy the code
Example 17: Accumulator V2.0
The previous implementation of the accumulator can only support the addition of three numbers, now need to remove this limitation, can be added indefinitely.
""" Accumulator V1.0 ""
s = 0
while True:
in_str = input('Enter an integer (enter q to exit) :')
if in_str == 'q':
break
x = int(in_str)
s += x
print('add: %d' % s)
Copy the code
Example 18: A guessing game
The program randomly generates a positive integer, the user to guess, the program according to the size of the guess to give the corresponding hint. Finally, it outputs how many guesses the user had to make before they were right.
""" Guessing 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 bit bigger')
elif number > answer:
print('A little bit smaller')
else:
print('Got it.')
break
print(F 'guess{counter}Time ')
Copy the code
Example 19: Printing the multiplication table
""" Print the multiplication table """
for i in range(1.10) :for j in range(1, i + 1) :print(f'{i}*{j}={i * j}', end='\t')
Copy the code
Example 20: Is it prime
Enter a positive integer to determine if it is prime. Definition: A natural number greater than 1 that is divisible only by 1 and itself. Such as: 3, 5, 7
""" Determine if it is a prime number """
num = int(input(Please enter a positive integer: '))
end = int(num // 2) + 1 # Only judge whether the first half is divisible. There is no divisible part of the first half. Therefore, there is definitely no divisible part of the second half
is_prime = True
for x in range(2, end):
if num % x == 0:
is_prime = False
break
if is_prime andnum ! =1:
print('prime')
else:
print('Not prime')
Copy the code
Range (2, end) yields 2, 3… End sequence and in turn assign values to the x execution loop. Range is also used in the following ways
Range (10) : generates 0, 1, 2… 9 sequence
Range (1, 10, 2) : generate 1, 3, 5… 9 sequence
Example 21: Fibonacci sequence
Enter a positive integer n to calculate the Fibonacci number of the NTH bit. The number in the current position of the Fibonacci number is equal to the sum of the first two numbers, 1, 1, 2, 3, 5, 8…
""" Fibonacci sequence V1.0 ""
n = int(input('Enter n:'))
a, b = 0.1
for _ in range(n):
a, b = b, a + b
print('the first f{n}The bit Fibonacci numbers are:{a}')
Copy the code
Example 22: Number of daffodils
A daffodil number is a 3-digit number in which the cube sum of the numbers in each bit is exactly equal to itself, for example:
"" number of daffodils """
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 the code
Example 23: Monkeys eat peaches
The monkey picked n peaches on the first day, and ate half of them that day
The next morning he ate half of the remaining peaches and one more
For the rest of the day, I ate half and one each morning.
By the morning of the 10th day, when I wanted to eat again, I had one peach left. How much did you pick the first day?
Reverse thinking: peaches on day n-1 = (peaches on Day NTH + 1) * 2, counting from day 10 to day 1
""" Monkeys eat peaches. """
peach = 1
for i in range(9):
peach = (peach + 1) * 2
print(peach)
Copy the code
Example 24: Print diamonds
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(The '*', end=' ')
for _ in range(blank_num // 2) :print(' ', end=' ')
print(a)for _ in range(7) :print(The '*', end=' ')
print(a)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(The '*', end=' ')
for _ in range(blank_num // 2) :print(' ', end=' ')
print(a)Copy the code
Example 25: Calculate royalty V2.0
Example 14: use a list + loop to calculate the commission, the code is cleaner, and can be handled more flexibly.
""" Calculate royalty V2.0 """
profit = int(input('Input sales profit (yuan) :'))
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 the code
Example 26: Certain day is the day of the year
Enter a date and calculate the day of the year
""" Calculate the number of days in a year that a certain day is """
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 date:'))
if year % 4= =0 and year % 100! =0 or year % 400= =0: Leap year February 29 days
months[2] + =1
for i in range(month):
res += months[i]
print(res+day)
Copy the code
Example 27: Palindrome string
Checks whether a string is a palindrome string. A palindrome string is a string that is identical in both forward and reverse reading, such as level
""" Determine if it is a palindrome string """
s = input('Input string:')
i = 0
j = -1
s_len = len(s)
flag = True
whilei ! = s_len + j:ifs[i] ! = s[j]: flag =False
break
i += 1
j += -1
print('Is a palindrome string' if flag else 'Not a palindrome string')
Copy the code
Example 28: Personal information input and output
You can store personal information in a meta-ancestor without defining a class
students = []
while True:
input_s = input('Enter student information (student id, name and gender) separated by Spaces (enter Q to exit) :')
if input_s == 'q':
break
input_cols = input_s.split(' ')
students.append((input_cols[0], input_cols[1], input_cols[2]))
print(students)
Copy the code
Example 29: Sorting personal information
Personal information is stored in tuples and sorted by student number, name, or gender.
""" Sort personal information """
students = []
cols_name = ['student id'.'name'.'gender']
while True:
input_s = input('Enter student information (student id, name and gender) separated by Spaces (enter Q to exit) :')
if input_s == 'q':
break
input_cols = input_s.split(' ')
students.append((input_cols[0], input_cols[1], input_cols[2]))
sorted_col = input('Input sort attribute:')
sorted_idx = cols_name.index(sorted_col) Get the index of the tuple based on the input attribute
print(sorted(students, key=lambda x: x[sorted_idx]))
Copy the code
Example 30: Deduplicate the input
To delete the input, use the Set Set in Python
"" "heavy "" "
input_set = set(a)while True:
s = input('Enter content (enter q to exit) :')
if s == 'q':
break
input_set.add(s)
print(input_set)
Copy the code
Example 31: Output set intersection
Given the skills required by Python Web engineers and algorithmic engineers, calculate the intersection of the two.
""" Set intersection """
python_web_programmer = set()
python_web_programmer.add('python basis')
python_web_programmer.add('web knowledge')
ai_programmer = set()
ai_programmer.add('python basis')
ai_programmer.add('Machine learning')
inter_set = python_web_programmer.intersection(ai_programmer)
print('Skill Intersection:', end=' ')
print(inter_set)
Copy the code
In addition to computing intersections, Python sets can also compute union and complement sets
Example 32: A guessing game
With the program to achieve rock paper scissors game.
""" The Guessing Game """
# 0 for paper, 1 for scissors, 2 for rock
import random
rule = {'cloth': 0.'scissors': 1.'stone': 2}
rand_res = random.randint(0.2)
input_s = input(Enter rock, Paper, Scissors:)
input_res = rule[input_s]
win = True
if abs(rand_res - input_res) == 2: The difference of 2 indicates that cloth and stone meet, cloth wins
if rand_res == 0:
win = False
elif rand_res > input_res: # The one with the biggest gap of 1 wins
win = False
print(F 'produces:{list(rule.keys())[rand_res]}, type:{input_res}')
if rand_res == input_res:
print(A 'flat')
else:
print('won' if win else 'lost')
Copy the code
Example 33: Dictionary sort
The dictionary key is the name and value is the height. Now we need to reorder the dictionary by height.
""" Dictionary sort """
hs = {'Joe': 178.'bill': 185.'Pockmarked seed': 175}
print(dict(sorted(hs.items(), key=lambda item: item[1)))Copy the code
Example 34: Binary quadratic function V2.0
The binary quadratic function is encapsulated in a function for easy call
Binary 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 the code
Example 35: Fibonacci series V2.0
Fibonacci sequence is generated by recursive function
""" Recursive Fibonacci sequence """
def fib(n) :
return 1 if n <= 2 else fib(n-1) + fib(n-2)
print(F 'Fibonacci number 10 is:{fib(10)}')
Copy the code
Example 36: Factorial
Define a function that implements factorial. The factorial definition of n: 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 the code
Example 37: Implementing the range function
Write a function similar to the Range function in Python
""" range function """
def range_x(start, stop, step) :
res = []
while start < stop:
res.append(start)
start += step
return res
Copy the code