简单编程例子怎么做的好

时间:2025-01-25 01:38:22 游戏攻略

Hello World程序

目的:在屏幕上输出“Hello, World!”。

编程语言:几乎所有编程语言。

示例代码

```python

print("Hello, World!")

```

计算器程序

功能:接受两个数字输入,执行加、减、乘、除运算,并输出结果。

编程语言:Python。

示例代码

```python

def calculator():

num1 = float(input("请输入第一个数字:"))

num2 = float(input("请输入第二个数字:"))

operation = input("请输入运算符(+、-、*、/):")

if operation == "+":

print(num1 + num2)

elif operation == "-":

print(num1 - num2)

elif operation == "*":

print(num1 * num2)

elif operation == "/":

print(num1 / num2)

else:

print("无效的运算符")

calculator()

```

猜数字游戏

功能:计算机随机生成一个数字,玩家猜测,程序给出提示,直到猜对为止。

编程语言:Python。

示例代码

```python

import random

def guess_number():

number = random.randint(1, 100)

attempts = 0

while True:

guess = int(input("请输入你猜的数字:"))

attempts += 1

if guess == number:

print(f"恭喜你,猜对了!数字是 {number},你猜了 {attempts} 次。")

break

elif guess < number:

print("猜小了,请再试一次。")

else:

print("猜大了,请再试一次。")

guess_number()

```

倒计时程序

功能:接受输入的时间(秒),显示剩余时间,倒计时结束后给出提示。

编程语言:Python。

示例代码

```python

import time

def countdown(seconds):

while seconds > 0:

mins, secs = divmod(seconds, 60)

timer = '{:02d}:{:02d}'.format(mins, secs)

print(timer, end="\r")

time.sleep(1)

seconds -= 1

print("时间到!")

time_seconds = int(input("请输入倒计时秒数:"))

countdown(time_seconds)

```

简单的绘图程序 (基于图形库):

功能:使用基本的绘图函数绘制直线、圆、矩形等图形。

编程语言:Python(使用Tkinter库)。

示例代码

```python

import tkinter as tk

from tkinter import Canvas

def draw_shape(canvas, shape, color):

if shape == "rectangle":

canvas.create_rectangle(50, 50, 200, 100, fill=color)

elif shape == "circle":

canvas.create_oval(150, 50, 250, 100, fill=color)

elif shape == "line":

canvas.create_line(50, 150, 200, 150, fill=color)

def main():

root = tk.Tk()

canvas = Canvas(root, width=300, height=200)

canvas.pack()

draw_shape(canvas, "rectangle", "red")

draw_shape(canvas, "circle", "blue")

draw_shape(canvas, "line", "green")

root.mainloop()

if __name__ == "__main__":

main()

```

这些例子涵盖了不同的编程语言和不同的应用领域,适合初学者入门和练习编程基本概念。