Classic examples of branches and loops in python (with reference answers)
Branches and loops are very flexible in application. They can be used alone or nested in each other. Moreover, for a problem, it is like doing a mathematical problem. Although there is only one answer, there is not only one idea and method to solve the problem. It may not be the best solution 100 years later, The best solution algorithm, so it is also true to write programs. There is not an idea. It is the best way to solve this problem, and it is only the most important of all algorithms at present. Remember, to solve a problem, you must first use the method that can solve the problem (even if the current method is stupid), and then think about a better way to solve the problem on this basis. Don't start to solve it because you are thinking about a "best" solution from the beginning.
If you want to learn programming well, more practice is an indispensable part. Then, open it quickly after learning branches and loops (those you haven't seen) (3 minutes to learn about branches and loops in Python 1) )Of course, there is no lack of practice. Here, I have summarized many classic examples that must be brushed in learning branches and cycles. Let's have a look. You can try to write it first. The reference code is later
1. Sum of 1 to 100
2. Find an integer between 1 and 100 that is a multiple of 3 or 5
3. Input a non negative integer n and output its hierarchy n!
4. Enter two positive integers n and m to find their greatest common factor
5. Use the for loop to print the following styles
* ** *** **** *****
6. Print multiplication table
7. Input n and output n Fibonacci numbers (don't know Baidu Fibonacci numbers)
8. Baiqian white chicken problem
A chicken Weng is worth five, a chicken mother is worth three, and a chicken chick is worth three. If you want to buy a hundred chickens for a hundred dollars, how about a chicken Weng, a chicken mother and a chicken chick?
In human terms, a rooster costs five yuan, a hen costs three yuan, and a chick costs three yuan. How many roosters, hens and chicks can buy with 100 yuan?
- Enter a positive integer to determine whether it is a prime number
10. Enter 10 numbers between 1 and 100, calculate the average of these 10 numbers, and find out the maximum and minimum values
11. Random number guessing game
If the user does not input a random number between 1100 pairs, it is assumed that the machine will output a random number at the end of each guess (if there is no number to be filled in between 1100 pairs)
12. Find the number of daffodils between 100 and 999
The sum of the cubes of each digit is equal to the number itself, which is the daffodil number, such as 153 = 1 ^ 3 + 5 ^ 3 + 3 ^ 3
13. Inversion of numbers
For example, user input 1234 and computer output 4321
14. Find the perfect number of 1-10000
The sum of all factors except yourself is equal to this number. It is a perfect number. For example, the factor 1, 2, 3 of 6 has 1 + 2 + 3 = 6
15. Fish division and summation
A. B, C, D and E, who were fishing at night, were exhausted in the early morning, so they found a place to sleep in the trees by the river. The next day, when the sun rose, a woke up first. He divided the fish into five parts, threw the extra one back into the river, and then took his own part home; B wakes up the second, but he doesn't know that a has taken a fish, so he divides the remaining fish into five parts, throws away the extra one, and then takes only one of his own; Then C, D and e wake up in turn and divide the fish in the same way. How many fish did the five people catch together?
16. Enter the length of the three sides of the triangle. If it is a triangle, calculate its area, otherwise let the user re-enter
(Helen's formula is adopted for the calculated area)
Reference code:
(not necessarily the best, there is a better way to write in the comment area)
1. Sum of 1 to 100
total = 0 # Define a variable total to store and for i in range(1,101): total += i print(f"1-100 The cumulative sum of is{total}")
2. Find an integer between 1 and 100 that is a multiple of 3 or 5
for i in range(1,101): if i % 3 == 0 or i % 5 == 0: print(i)
3. Input a non negative integer n and output its hierarchy n!
n = int(input("Enter a nonnegative integer n: ")) # Receive user entered integers total = 1 # Store accumulation with total for i in range(2, n + 1): total *= i print(f"{n}Class of = {total}")
4. Enter two positive integers n and m to find their greatest common factor
print("Enter two positive integers") n = int(input("Enter a positive integer 1:")) m = int(input("Enter a positive integer 2:")) min = 0 if m > n: min = n else: min = m for i in range(1, min+1): if n % i == 0 and m % i == 0: print(f"Their greatest common factor is{i}") break
There is also a simpler and more efficient algorithm, Euclidean algorithm. The reference code is as follows (it doesn't matter if you can't understand it):
n = int(input("Enter a positive integer 1:")) m = int(input("Enter a positive integer 2:")) m, n = max(m, n), min(m, n)# Find the maximum value between M and N with max function and the minimum value between M and N with min function while m % n != 0: m, n = n, m - n print(f"The maximum common factor is{n}")
5. Use the for loop to print the following styles
* ** *** **** *****
for i in range(1,6): for j in range(1, i + 1): print("*", end='') print()
Simpler writing
n = int(input("input n")) for i in range(1,n + 1): print(f"{i} "* i)
6. Print multiplication table
n = int(input("input n")) # Input · n = 9 for i in range(1, n + 1): for j in range(1, i + 1): print(f"{j} * {i} = {i * j}", end = "\t") # Use \ t to align each column print()
7. Input n and output n Fibonacci numbers (don't know Baidu Fibonacci numbers)
n = int(input("input n")) a = 1 b = 1 if n == 1: print(a) else: print(a, b, end=" ") for _ in range(2,n): # Used when loop variables are not available_ c = a + b print(c, end=' ') a = b b = c
8. Baiqian white chicken problem
A hen is worth five, a hen is worth three, and a chick is worth three, If you want to buy a hundred chickens for a hundred dollars, how about the chicken owner, the chicken mother and the chicken chick?
In human terms, a rooster costs five yuan, a hen costs three yuan, and a chick costs three yuan. How many roosters, hens and chicks can buy with 100 yuan?
for x in range(21): # The range of cocks is 0-21 for y in range(34): # The range of hens is 0-33 z = 100 - x - y # The number of chicks equals 100-x-y if z % 3 == 0 and 5 * x + 3 * y + z // 3 == 100: print(x, y, z)
9. Enter a positive integer to judge whether it is a prime number
int1 = int(input("Enter a positive integer")) flag = True for i in range(2,int1): if int1 % i == 0: flag = False break if flag and int1 > 1: print(f"{int1}Is a prime number") else: print(f"{int1}Not prime")
10. Enter 10 numbers between 1 and 100, calculate the average of these 10 numbers, and find out the maximum and minimum values
max1 = 0 min1 = 101 # Just bigger than 100 total = 0 count = 0 while count < 10: int1 = int(input("Please enter 10 positive integers, one at a time and press enter")) if int1 < 1 or int1 > 100: print("invalid input") continue count += 1 # Judge the maximum value if int1 > max1: max1 = int1 # Judgment minimum if int1 < min1: min1 = int1 # Calculate average total += int1 print(f"The average value is{total/10}, The minimum value is{min1},The maximum value is{max1}")
11. Random number guessing game
The machine generates a random number (assumed to be between 1100). The user inputs a number each time. When it is guessed correctly, it ends. If it is guessed correctly seven times, it outputs "IQ to be recharged"
import random # Import random module, do not know to skip first, as long as you know it is used to generate random numbers ran1 = random.randrange(1,101) # Generates a random integer between 1 and 100 count = 0 while True: count += 1 # The user enters a number guess =int(input("Enter a 1,100 Integer between")) # Judge the relationship between two numbers if guess > ran1: print("smaller one") elif guess < ran1: print("A little bigger") else: print("You guessed right") break if count > 7: print("Insufficient IQ balance")
12. Find the number of daffodils between 100 and 999
The sum of the cubes of each digit is equal to the number itself, which is the daffodil number, such as 153 = 1 ^ 3 + 5 ^ 3 + 3 ^ 3
bit = 0 ten = 0 hundred_bit = 0 t = 0 for i in range(100, 1000): bit = i % 10 hundred_bit = i // 100 t = bit ** 3 + ten ** 3 + hundred_bit ** 3 ten = (i % 100) // 10 if t == i: print(i)
13. Inversion of numbers
For example, user input 1234 and computer output 4321
total = 0 number = int(input("Please enter a number")) while number > 0: a = number // 10 b = number % 10 total = total * 10 + b number = a print(total)
improvement
total = 0 number = int(input("Please enter a number")) while number > 0: total = total * 10 + number % 10 number //= 10 print(total)
14. Find the perfect number of 1-10000
The sum of all factors except yourself is equal to this number. It is a perfect number. For example, the factor 1, 2, 3 of 6 has 1 + 2 + 3 = 6
for i in range(1,10000): j = 1 sum1 = 0 while j < i: if i % j == 0: sum1 += j j += 1 if sum1 == i: print(i)
Improved algorithm
for i in range(2,10000): sum1 = 1 for j in range(2, int(i ** 0.5) + 1): if i % j == 0: sum1 += j if j != i // j: sum1 += i // j if sum1 == i: print(i)
15. Fish division and summation
A. B, C, D and E, who were fishing at night, were exhausted in the early morning, so they found a place to sleep in the trees by the river. The next day, when the sun rose, a woke up first. He divided the fish into five parts, threw the extra one back into the river, and then took his own part home; B wakes up the second, but he doesn't know that a has taken a fish, so he divides the remaining fish into five parts, throws away the extra one, and then takes only one of his own; Then C, D and e wake up in turn and divide the fish in the same way. How many fish did the five people catch together? (hint: enumeration method)
fish = 1 # fish must be equal to 5 x + 1 while True: flag = True # Judge whether the score is enough total = fish for _ in range(5): if (total - 1) % 5 == 0: total = (total - 1) // 5 * 4 else: flag = False break if flag: print(f"At least{fish}Fish) break fish += 1
improvement
fish = 6 # fish must be equal to 5 x + 1 while True: flag = True # Judge whether the score is enough total = fish for _ in range(5): if (total - 1) % 5 == 0: total = (total - 1) // 5 * 4 else: flag = False break if flag: print(f"At least{fish}Fish) break fish += 5
16. Enter the length of the three sides of the triangle. If it is a triangle, calculate its area, otherwise let the user re-enter
(Helen's formula is adopted for the calculated area)
while True: # Enter three edges a = int(input("Enter a value for the first edge")) b = int(input("Enter the value for the second edge")) c = int(input("Enter the value for the 3rd edge")) # Judge whether it is a triangle if a + b > c and b + c > a and c + a > b: p = (a + b + c)/2 s = (p * (p-a) * (p - b) * (p - c)) ** 0.5 print(f"Is a triangle with an area of{s}") break else: print("Not a triangle,Please re-enter")
Such a classic python branch and loop exercise, don't hurry to collect it!
If it helps you, don't forget to like, comment, pay attention and collect