Hello everyone, here is the list of code gods (a little boastful, ha ha). It's a newcomer. I hope you can give me more advice.
Many students still find it difficult to use Python flexibly after learning it. I sorted out 37 small programs for getting started with Python. In practice, the application of Python will have twice the result with half the effort. I hope you can like it and support it.
Example 1: conversion from Fahrenheit to Celsius
Formula for Fahrenheit temperature to Celsius temperature: C = (F - 32) / 1.8. This example examines Python's addition, subtraction, multiplication and division operators.
""" Convert Fahrenheit to Celsius """ f = float(input('Enter Fahrenheit temperature: ')) c = (f - 32) / 1.8 print('%.1f Fahrenheit degree = %.1f centigrade' % (f, c))
Example 2: calculate the circumference and area of a circle
Enter the radius and calculate the radius and area of the circle. The formula of circle circumference is 2 π r, and the formula of interview is π * 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('the measure of area: %.2f' % area)
Example 3: implementation of univariate 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))
Example 4: realize binary quadratic function
To 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))
Example 5: separating the single digits of an integer
Separates the single digits of a positive integer and the parts other than the single digits. The modulus (remainder) operator%, and the integer division operator are required//
""" Separate integer digits """ x = int(input('Enter 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)
Example 6: implement an accumulator
Implement a simple accumulator, which can accept the user's input of 3 numbers and accumulate them. Compound assignment operator is required:+=
""" accumulator v1.0 """ s = 0 x = int(input('Enter integer:')) s += x x = int(input('Enter integer:')) s += x x = int(input('Enter integer:')) s += x print('the sum:%d' % s)
Example 7: judging leap years
Enter the year to judge whether it is a leap year. Leap year judgment method: it can be divided by 4, but not 100; Or it can be divided by 400. Arithmetic and logical operators are required
""" Judge leap year """ year = int(input('Enter year: ')) is_leap = year % 4 == 0 and year % 100 != 0 or year % 400 == 0 print(is_leap)
Example 8: judging odd and even numbers
Entering a number to determine whether the cardinality is even or not requires modular operation and if... else structure
""" Judging odd and even numbers """ in_x = int(input('Enter integer:')) if in_x % 2 == 0: print('even numbers') else: print('Odd number')
Example 9: guess the size
The user inputs an integer between 1-6 and compares it with the number randomly generated by the program. The if... elif... else structure is required
""" Guess size """ import random in_x = int(input('Enter 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 win') else: print('Level')
Note: random is the random number module of Python. Calling random.random can generate a random number of type int. randint(1,6) means generating random numbers between [1,6].
Example 10: judging leap years
Before judging whether the leap year is True or False, you need to output the text version of leap year or normal year this time
""" 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('Ordinary year')
Example 11: degrees Celsius and Fahrenheit rotate with each other
We have done the conversion from Fahrenheit to Celsius before, and now we can realize the mutual conversion of the two through the branch structure.
""" Degrees Celsius and Fahrenheit are interchangeable """ trans_type = input('Enter degrees 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 Celsius is:%.2f' % c) elif trans_type == 'Fahrenheit degree': # Execute the logic of Celsius to Fahrenheit c = float(input('Enter Celsius temperature:')) f = c * 1.8 + 32 print('Fahrenheit temperature is:%.2f' % f) else: print('Please enter Fahrenheit or Celsius')
Example 12: does it form a triangle
Enter the length of three edges to judge whether they form a triangle. Conditions for forming a triangle: the sum of two sides is greater than the third side.
""" Does it form a triangle """ a = float(input('Enter 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('Cannot form a triangle')
Example 13: output grade
Enter the score and output the grade corresponding to the score.
=90 points get A, [80, 90) get B, [70, 80) get C, [60, 70) get D, < 60 get E
""" Output grade """ score = float(input('Please enter grade: ')) 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)
Example 14: Calculation of commission
The bonus of an enterprise is calculated according to the following rules according to the sales profit. Enter the sales profit to calculate the bonus.
If the profit is < = 100000, the bonus can be increased by 10% 100000 < profit < = 200000, and the part higher than 100000 will be increased by 7.5% 200000 < profit<=
400000, 5% for the part higher than 200000 yuan < profit < = 600000, 3% for the part higher than 400000 yuan, profit > 600000, and 1% for the part more than 600000 yuan
""" Calculation of commission v1.0 """ profit = float(input('Enter 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)
Example 15: implementing piecewise functions
Piecewise functions are often seen in mathematics. The following piecewise functions are implemented by program
""" Piecewise function """ x = int(input('Input:')) if x > 0: y = 3 * x ** 2 + 4 else: y = 2 * x + 2 print('f(%d) = %d' % (x, y))
Example 16: 1-n summation
Enter a positive integer n to calculate the result of 1 + 2 +... + n.
""" 1-n Sum """ n = int(input('input n: ')) s = 0 while n >= 1: s += n n -= 1 print('1-%d Summation result: %d' % (n, s))
Example 17: accumulator v2.0
The accumulator previously implemented can only support the addition of three numbers. Now it is necessary to remove this limitation and add infinitely.
""" accumulator v1.0 """ s = 0 while True: in_str = input('Enter integer (enter) q,Exit:') if in_str == 'q': break x = int(in_str) s += x print('Add:%d' % s)
Example 18: guessing game
The program randomly generates a positive integer for the user to guess, and the program gives the corresponding prompt according to the size of the guess. Finally, the output shows how many times the user guesses.
""" 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 bigger') elif number > answer: print('A little smaller') else: print('You guessed right') break print(f'Guess together{counter}second') Copy code Example 19: print multiplication formula table """ Print multiplication formula table """ for i in range(1, 10): for j in range(1, i + 1): print(f'{i}*{j}={i * j}', end='\t')
Example 20: is it a prime number
Enter a positive integer to judge whether it is a prime number. Definition of prime number: among natural numbers greater than 1, natural numbers that can only be divided by 1 and itself, such as 3, 5 and 7
""" Judge whether it is prime """ num = int(input('Please enter a positive integer: ')) end = int(num // 2) + 1 # just judge whether the first half can be divided. There is no division in the first half, so there must be no division in the second half ```python 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 prime')
> range(2, end) Can generate 2, 3, ... end Sequence and assign values to x Execute the loop. range There are also the following uses > range(10): Build 0, 1, 2, ... 9 sequence range(1, 10, 2): Generate 1, 3, 5, ... 9 sequence ## Example 21: Fibonacci sequence Enter a positive integer n,Calculation section 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 ... ```python """ 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}')
Example 22: number of daffodils
The daffodil number is a 3-digit number, and the cubic sum of the numbers in each digit is exactly equal to itself, for example:
""" 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)
Example 23: monkeys eat peaches
On the first day, the monkey picked n peaches. He ate half of them that day, but he was not addicted. He ate another one. The next morning, he ate half of the remaining peaches and another one
After that, I ate the remaining half and one of the previous day every morning. When I wanted to eat again on the 10th morning, I left a peach. Ask how many I picked on the first day.
Reverse thinking: peaches on day n-1 = (peaches on day n + 1) * 2. Cycle from day 10 to day 1
""" Monkeys eat peaches """ peach = 1 for i in range(9): peach = (peach + 1) * 2 print(peach)
Example 24: print diamond
Output the following diamond pattern
*** ***** ******* ***** *** ```python
"""
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()
## Example 25: Calculation of commission v2.0 Change example 14: Calculation of commission to list+In the way of loop, the code is more concise and can be handled more flexibly. ```python """ Calculation of commission v2.0 """ profit = int(input('Enter 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)
Example 26: what day of the year is a certain day
Enter a date to calculate 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('particular year: ')) month = int(input('month: ')) day = int(input('What number: ')) if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: # February 29 in leap year months[2] += 1 for i in range(month): res += months[i] print(res+day)
Example 27: palindrome string
Judge whether a string is a palindrome string. The 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 'Not a palindrome string')
Example 28: personal information input and output
If no class is defined, personal information can be saved in Yuanzu
students = [] while True: input_s = input('Enter student information (student number, name, gender) separated by spaces q,Exit:') if input_s == 'q': break input_cols = input_s.split(' ') students.append((input_cols[0], input_cols[1], input_cols[2])) print(students)
Example 29: sorting personal information
Personal information is stored in tuples and sorted by student number, name or gender.
""" Personal information sorting """ students = [] cols_name = ['Student number', 'full name', 'Gender'] while True: input_s = input('Enter student information (student number, name, gender) separated by spaces q,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('Enter sorting properties:') sorted_idx = cols_name.index(sorted_col) # Gets the index of the tuple based on the input attribute print(sorted(students, key=lambda x: x[sorted_idx]))
Example 30: de duplication of input content
The input content is de duplicated and directly implemented with the Set set in Python
""" duplicate removal """ input_set = set() while True: s = input('Input content (input) q,Exit:') if s == 'q': break input_set.add(s) print(input_set)
Example 31: output set intersection
Given the skills required by Python web engineers and Algorithm Engineers, calculate the intersection of the two.
""" set intersection """ python_web_programmer = set() python_web_programmer.add('python Basics') python_web_programmer.add('web knowledge') ai_programmer = set() ai_programmer.add('python Basics') ai_programmer.add('machine learning') inter_set = python_web_programmer.intersection(ai_programmer) print('Skill intersection:', end='') print(inter_set)
Python set can calculate not only intersection, but also Union and complement
Example 32: guessing game
Use the program to realize the stone scissors paper game.
""" Guessing game """ # 0 for cloth, 1 for scissors and 2 for stone import random rule = {'cloth': 0, 'scissors': 1, 'stone': 2} rand_res = random.randint(0, 2) input_s = input('Enter stone, scissors, cloth:') input_res = rule[input_s] win = True if abs(rand_res - input_res) == 2: # The difference of 2 indicates that the cloth meets the stone and the cloth wins if rand_res == 0: win = False elif rand_res > input_res: # Who wins when the difference is 1 win = False print(f'Program output:{list(rule.keys())[rand_res]},Input:{input_res}') if rand_res == input_res: print('flat') else: print('win' if win else 'transport')
Example 33: Dictionary sorting
The key of the dictionary is the name and the value is the height. Now you need to reorder the dictionary according to the height.
""" Dictionary sort """ hs = {'Zhang San': 178, 'Li Si': 185, 'Wang Mazi': 175} print(dict(sorted(hs.items(), key=lambda item: item[1])))
Example 34: Bivariate quadratic function v2.0
The binary quadratic function is encapsulated in the function for easy calling
""" 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)}')
Example 35: Fibonacci sequence v2.0
The Fibonacci sequence is generated in the form of recursive function
""" Recursive Fibonacci sequence """ def fib(n): return 1 if n <= 2 else fib(n-1) + fib(n-2) print(f'The 10th Fibonacci number is:{fib(10)}')
Example 36: factorial
Define a function to implement factorial. Factorial definition of N: n= 123* … n
""" Factorial function """ def fact(n): return 1 if n == 1 else fact(n-1) * n print(f'10! = {fact(10)}')
Example 37: implement the range function
Write a function similar to the range function in Python
```python """ range function """ def range_x(start, stop, step): res = [] while start < stop: res.append(start) start += step return res