Basic exercises for getting started with Python

Through the previous two chapters Python-Getting Started Basics and Python-Getting Started Basic Statements, you should already know the basic python statements and functions, and you can use the pycharm compiler to create .py files and run them. Let’s take some today Small exercises to add some fun to boring learning.

  • Check if a number is even
# 定义一个变量
num = 10

# 判断是否为偶数
if num % 2 == 0:
    print(num, "是偶数")
else:
    print(num, "是奇数")
  • Calculates the product of two numbers
# 定义两个变量
a = 3
b = 5

# 计算乘积
result = a * b

# 打印结果
print(a, "和", b, "的乘积是:", result)
  • Print out the numbers 1-10

print numbers in a loop

for i in range(1, 11):
    print(i)
  • guess the number game

Import the random module for generating random numbers

import random

generate a random number

num = random.randint(1, 10)

Guess the numbers in a loop

while True:
    # 提示用户输入数字
    guess = int(input("请猜一个 1-10 之间的整数:"))
    
    # 判断是否猜中了
    if guess == num:
        print("恭喜你,猜中了!")
        break
    elif guess < num:
        print("猜的数字太小了,再试试!")
    else:
        print("猜的数字太大了,再试试!")
  • Calculate factorial
# 定义一个函数,计算阶乘
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

# 调用函数,计算阶乘
num = 5
result = factorial(num)

# 打印结果
print(num, "的阶乘是:", result)

This code defines a function factorial(n) that calculates the factorial, accepts an integer parameter n, and returns its factorial value. When n is equal to 0, the function returns 1; otherwise, the function calculates the factorial value of n by calling itself recursively.

In the main program, the variable num is assigned a value of 5, and then the factorial(num) function is called to calculate the factorial value of num. The final result is stored in the variable result.

Finally, the program prints the result string, and uses string concatenation to output the value of num and the calculation result together.


In detail:
the function factorial(n) first checks whether n is equal to 0. If yes, it returns 1, since the factorial of 0 is 1. If not, it calls itself recursively, taking n-1 as an argument, and multiplying the return value by n to get the factorial of n.

Here, we pass in the parameter 5, factorial(5) will calculate 5 * factorial(4), and factorial(4) will calculate 4 * factorial(3), recursively until factorial(0), here returns 1 directly. The result of each recursive call is then multiplied by the argument of the function that called it, resulting in 120, the factorial of 5.

In the main program, we call factorial(5) and store the result in result, and then use the print statement to print out the string.


ps: When writing code in Python, pay special attention to the indentation rules python indentation rules


  • Count the number of characters in a string
# 定义一个字符串
str = "hello world"

# 计算字符串中字符的个数
count = 0
for char in str:
    count += 1

# 打印结果
print(str, "中字符的个数是:", count)
  • Check if a string is a palindrome
# 定义一个字符串
str = "level"

# 判断是否为回文串
if str == str[::-1]:
    print(str, "是回文串")
else:
    print(str, "不是回文串")
  • Find the greatest common divisor and least common multiple of two numbers
# 定义两个数
a = 12
b = 16

# 计算最大公约数
x = a
y = b
while y != 0:
    r = x % y
    x = y
    y = r
gcd = x

# 计算最小公倍数
lcm = a * b // gcd

# 打印结果
print(a, "和", b, "的最大公约数是:", gcd)
print(a, "和", b, "的最小公倍数是:", lcm)

Replenish:

The function of this code is to calculate the greatest common divisor and least common multiple of two numbers.

  1. First, two integer variables a and b are defined, which are assigned the values ​​12 and 16, respectively.
    a = 12
    b = 16
  2. Next, two variables x and y are defined, and their values ​​are assigned to a and b respectively. x and y will be used to calculate the greatest common divisor.
    x = a
    y = b
  3. Next, two variables x and y are defined, and their values ​​are assigned to a and b respectively. x and y will be used to calculate the greatest common divisor.
while y != 0:
    r = x % y
    x = y
    y = r
gcd = x

Here is the block of code that calculates the greatest common divisor. The condition of the while loop is that y is not equal to 0. If y is equal to 0, then x is the greatest common divisor of a and b. In the while loop, the values ​​of x and y are updated by continuously using the rolling and dividing method until y is equal to 0, and the final x is the greatest common divisor of a and b.
The basic idea of ​​the rolling and dividing method is: suppose x and y are two positive integers, and r is their remainder, then the greatest common divisor of x and y is equal to the greatest common divisor of y and r. In each cycle, by calculating the remainder r of x divided by y, and then assigning x to the original y and y to the original r, the values ​​of x and y are continuously updated until y is equal to 0 and the cycle ends.

lcm = a * b // gcd

This line of code is used to calculate the least common multiple. The lcm variable is assigned the product of a and b divided by their greatest common divisor, that is, the least common multiple is equal to the product of two numbers divided by their greatest common divisor.

print(a, "和", b, "的最大公约数是:", gcd)
print(a, "和", b, "的最小公倍数是:", lcm)

Finally, output the greatest common divisor and least common multiple of a and b through the print statement.

ps:

The greatest common divisor refers to the largest divisor shared by two or more integers; the least common multiple refers to the smallest common multiple of two or more integers. In practical problems, the greatest common divisor and least common multiple are often used to simplify fractions, solve congruence equations, etc.

  • Implement a simple calculator
# 定义一个函数,实现加法
def add(a, b):
    return a + b

# 定义一个函数,实现减法
def subtract(a, b):
    return a - b

# 定义一个函数,实现乘法
def multiply(a, b):
    return a * b

# 定义一个函数,实现除法
def divide(a, b):
    if b == 0:
        return "错误:除数不能为 0"
    else:
        return a / b

# 用户输入操作数和运算符
num1 = float(input("请输入第一个操作数:"))
op = input("请输入运算符:")
num2 = float(input("请输入第二个操作数:"))

# 根据运算符调用相应的函数进行计算
if op == "+":
    result = add(num1, num2)
elif op == "-":
    result = subtract(num1, num2)
elif op == "*":
    result = multiply(num1, num2)
elif op == "/":
    result = divide(num1, num2)
else:
    result = "错误:不支持的运算符"

# 打印结果
print("计算结果是:", result)

For beginners, you can write these small exercises without asking for a deep understanding. After you have accumulated more python knowledge, you will find them very simple. Don’t waste too much time here. Laying a good foundation is the best important!
Finally — Python is a very useful programming language that can be used to solve a wide variety of problems. Its syntax is concise and clear, very easy to use, and there are many rich libraries and tools available, allowing you to develop your own programs more efficiently. Play an important role in future life and work, come oninsert image description here

Guess you like

Origin blog.csdn.net/ultramand/article/details/130253223