【有意思的python】几个适合初学者的有趣python小程序

知识点包括随机数生成、循环、条件语句、列表操作、函数调用等,下面是几个小代码示例。

  1. 猜数字游戏:
import random

number = random.randint(1, 100)
guess = 0

while guess != number:
    guess = int(input("猜一个1到100之间的数字:"))
    if guess < number:
        print("猜的数字太小了!")
    elif guess > number:
        print("猜的数字太大了!")

print("恭喜你猜对了!")
  1. 打印乘法口诀表:
for i in range(1, 10):
    for j in range(1, i+1):
        print(f"{j}*{i}={i*j}\t", end="")
    print()
  1. 绘制彩色螺旋线:
import turtle

turtle.bgcolor("black")
turtle.pensize(2)
turtle.speed(0)

colors = ["red", "yellow", "blue", "green"]

for x in range(400):
    turtle.pencolor(colors[x%4])
    turtle.forward(2*x)
    turtle.left(91)

turtle.exitonclick()
  1. 计算平均数:
num_list = []

while True:
    num = input("请输入一个数字,按 q 键退出输入:")
    if num == "q":
        break
    num_list.append(int(num))

avg = sum(num_list) / len(num_list)
print(f"这些数字的平均数是:{avg}")

你可能感兴趣的:(python,开发语言,青少年编程,pycharm)