[python programming design exercises]

 1. Write a program to generate 10 random integers, add the odd numbers among them, add the even numbers, and output two sums as a result.

import random
number = random.sample(range(1,100),10)
print(number)
even,odd = [],[]
for x in number:
    if x % 2 == 0:
        even.append(x)
    elif x % 2 != 0:
        odd.append(x)
print(
f"""
奇数和:{sum(odd)}
偶数和:{sum(even)}
"""
)

2. Enter 10 numbers from the keyboard, and program to sort them.

raw = []
for i in range(10):
    x = int(input('第%d个数: ' % (i+1)))
    raw.append(x)

for i in range(len(raw)):
    for j in range(i, len(raw)):
        if raw[i] > raw[j]:
            raw[i], raw[j] = raw[j], raw[i]
print('从小到大排序为:',raw)

3. Input a three-digit number from the keyboard to determine whether it is the number of daffodils. If yes, the program terminates; if not, continue to enter the next three digits.

while 1:
    num_sum = 0
    num = input('请输入一个三位数:').strip()
    if num.isdecimal() is True:
        if len(num) != 3:
            print("不是水仙花")
        else:
            for i in num:
                num_sum += int(i) ** 3
            if num_sum == int(num):
                print(num,'是水仙花')
                break
            else:
                print(num,'不是水仙花')
    elif num.upper() == 'Q':
        break
    else:
        print("您输入的不是三位数字,请重新输入")

4. Write a guessing program: randomly generate an integer, and then input an integer from the keyboard. If the two integers are equal, the guess is correct, otherwise continue to input integers to guess the number until the guess is correct.

import random
print("下面是猜数字游戏环节!")
while 1:
    random_num = random.randint(1, 100)
    # print(random_num)
    while True:
        guess_num = int(input("请输入你要猜的数字:"))
        if guess_num > random_num:
            print("您猜的数字大了,请重新猜测!")
        elif guess_num < random_num:
            print("您猜的数字小了,请重新猜测!")
        elif guess_num == random_num:
            print("恭喜您答对了,正确的数字为%d!" % random_num)
            break
    else:
        print("您已经没有机会了,游戏失败!")
    print("按任意键结束游戏,按空格键继续游戏:")
    select = input("请输入你的选择:")
    if select != " ":
        break

Guess you like

Origin blog.csdn.net/long_0901/article/details/122015639