10 basic Python grammar exercises

Posted by LoganK on Mon, 17 Jan 2022 22:52:12 +0100

catalogue

1. Digital combination

2. Application of piecewise function

3. Mathematical calculation

4. Judgment date

5. Numerical sorting

6. Fibonacci sequence

7. Time function

8. Draw a diamond

9. Application questions - raw rabbit

10. Output prime

1. Digital combination

Title: there are four numbers 1, 2, 3 and 4. How many three digits can be formed without repeated numbers? Count the number and print it.

Idea: there are only four numbers in this question to form three digits. You can use the exhaustive method to cycle hundreds, tens and single digits respectively, then judge whether there are duplicate numbers, and finally output all the results in the form of list.

list1 = []

# Circular hundreds
for i in range(1, 5):
    # Cycle ten digits
    for j in range(1, 5):
        # Loop bits
        for k in range(1, 5):
            # When the hundreds, tens and individual digits are different, the combined digits are output
            if i != j and i != k and j != k:
                a = 100*i+10*j+k
                list1.append(a)
                continue

# Print list and number of elements
print(list1)
print("In total:{}".format(len(list1)))

# Output results
[123, 124, 132, 134, 142, 143, 213, 214, 231, 234, 241, 243, 312, 314, 321, 324, 341, 342, 412, 413, 421, 423, 431, 432]
Total: 24

2. Application of piecewise function

Title: the bonus paid by the enterprise is based on the profit commission. When the profit (I) is less than or equal to 100000 yuan, the bonus can be increased by 10%;
When the profit is higher than 100000 yuan and lower than 200000 yuan, the part lower than 100000 yuan will be deducted by 10%, and the part higher than 100000 yuan will be deducted by 7.5%; Between 200000 and 400000 yuan, the part higher than 200000 yuan can be deducted by 5%; 3% commission can be given for the part higher than 400000 yuan between 400000 and 600000 yuan; When it is between 600000 and 1 million yuan, the part higher than 600000 yuan can be deducted by 1.5%. When it is higher than 1 million yuan, the part higher than 1 million yuan can be deducted by 1%. Enter the profit I of the current month from the keyboard to calculate the total amount of bonus to be paid?

Idea: typical high school and junior high school piecewise function problems can be completed by using multiple "elif" judgment sentences.

i = int(input("Please enter current month profit:"))
# Less than or equal to 100000
if i <= 100000:
    a = i * 0.1
# Between 100000 and 200000 hours
elif 100000 <= i <= 200000:
    a = 100000 * 0.1 + (i - 100000) * 0.075
# Between 200000 and 400000 hours
elif 200000 <= i <= 400000:
    a = 100000 * 0.1 + 100000 * 0.075 + (i - 200000) * 0.05
# Between 400000 and 600000 hours
elif 400000 <= i <= 600000:
    a = 100000 * 0.1 + 100000 * 0.075 + 200000 * 0.05 + (i - 400000) * 0.03
# Between 600000 and 1 million hours
elif 600000 <= i <= 1000000:
    a = 100000 * 0.1 + 100000 * 0.075 + 200000 * 0.05 + 200000 * 0.03 + (i - 600000) * 0.015
# More than 1 million
else:
    a = 100000 * 0.1 + 100000 * 0.075 + 200000 * 0.05 + 200000 * 0.03 + 400000 * 0.015 + (i - 1000000) * 0.01

print("The bonus payable is:{}".format(a))

3. Mathematical calculation

Title: an integer, which is a complete square number after adding 100, and a complete square number after adding 168. What is the number?

Idea: the number added to this question is only 268 and is an integer. Mathematical thinking can be omitted. Use the exhaustive method to cycle from 1, judge the number that meets the conditions and output it.

n = 1
# loop
while True:
    # Judgment statement: judge whether the square root of n plus 100 (268) is an integer
    if (n+100)**0.5 == int((n+100)**0.5) and (n+268)**0.5 == int((n+268)**0.5):
        print(n)
        break
    else:
        n +=1

# Output results
21

4. Judgment date

Title: enter a certain day of a certain month in a certain year to judge the day of the year?

Idea: to calculate the date, you need to distinguish between large and small months, and February of leap year has 29 days.

year=int(input("Please enter the year:"))
month=int(input("Please enter month:"))
day=int(input("Please enter date:"))

# Determine whether it is a leap year
if year%4==0:
    # Define order list
    list1=[0,31,29,31,30,31,30,31,31,30,31,30,31]
    days=0
    for i in range(month):
        # Cumulative full moon days
        days+=list1[i]
    print(days+day)
    print("This is a leap year")
else:
    list1=[0,31,28,31,30,31,30,31,31,30,31,30,31]
    days=0
    for i in range(month):
        days+=list1[i]
    print(days+day)
    print("This is not a leap year")

5. Numerical sorting

Title: arbitrary input of three numbers, automatic sorting and output.

Idea: using the sorting method of list

x=int(input("Please enter the first number:"))
y=int(input("Please enter the second number:"))
z=int(input("Please enter the third number:"))

# Definition list
list1=[x,y,z]
# List sorting method
list1.sort(reverse=False)
# Convert int type to string type and output
a=map(str,list1)
print(" ".join(a))

6. Fibonacci sequence

Title: Fibonacci sequence, starting from 1,1, each subsequent term is equal to the sum of the first two terms.

Idea: function recursion

# Define function
def fun(n):
    if n==1 or n==2:
        return 1
    else:
        # Function self call
        return fun(n-2)+fun(n-1)
        # fun1 fun2 fun1+fun2 fun2+fun3


list1=[]
# Top 20 outputs
for i in range(1,20):
    list1.append(fun(i))
print(list1)

# Output results
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]

7. Time function

Title: pause output for a few seconds

# Call time library
import time

for i in range(4):
    print(i)
    # Delay 5s output
    time.sleep(5)

8. Draw a diamond

Title: draw a diamond

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

# Output results
    **   
   ****  
  ****** 
   ****  
    **   
       

9. Application questions - raw rabbit

Title: a pair of rabbits give birth to a pair of rabbits every month from the third month after birth. The little rabbit grows to another pair of rabbits every month after the third month. If the rabbits don't die, what is the total number of rabbits every month?

Idea: still using function recursion, the result is similar to Fibonacci sequence

def fun(n):
    if n<=2:
        return 1
    else:
        return fun(n-2)+fun(n-1)
        # fun1 fun2 fun1+fun2 fun2+fun3


list1=[]
for i in range(1,10):
    list1.append(2*fun(i))
print(list1)
# print(fun(10))

# Output results
[2, 2, 4, 6, 10, 16, 26, 42, 68]

10. Output prime

Title: output all primes from 1 to 100

Idea: enumerate the numbers from 1 to 100 to judge whether the number can be divided by 2 to all its integers.

list=[]

# Integer from 1 to 100
for i in range(1,101):
    for j in range(2,i):
        # Judge whether it is prime
        if i%j==0:
            break
    else:
        list.append(i)
print(list)

# Output results
[1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Topics: Python Back-end