写一个Python入门的简单例子。
时间: 2024-04-30 13:22:58 浏览: 18
以下是一个Python入门的简单例子,可以实现输入两个数并计算它们的和。
```
num1 = int(input("请输入第一个数:")) # 输入第一个数并转换为整数
num2 = int(input("请输入第二个数:")) # 输入第二个数并转换为整数
sum = num1 + num2 # 计算两个数的和
print("两个数的和为:", sum) # 输出结果
```
执行结果:
```
请输入第一个数:3
请输入第二个数:4
两个数的和为: 7
```
相关问题
python入门字典例子
Python中的字典是一种无序的数据结构,它使用键值对的方式存储和操作数据。以下是一个入门级的字典例子:
假设我们要创建一个存储学生信息的字典。我们先定义一个空字典:
students = {}
接下来,我们添加一些学生的信息进去。每个学生的信息可以使用字典中的一个键值对来表示,其中键表示某个特定的属性,比如姓名、年龄或者成绩。例如,我们添加两个学生的信息:
students["Emily"] = 18
students["Tom"] = 20
现在,字典students中存储了两个学生的信息,其中"Emily"是一个键,18是它对应的值;"Tom"是另一个键,20是它对应的值。
我们可以通过键来访问字典中的值。例如,如果我们想查找"Emily"的年龄,可以使用下面的代码:
age = students["Emily"]
print(age)
运行结果将输出18,即"Emily"的年龄。
我们还可以使用for循环来遍历整个字典,并访问其中的键值对。比如,我们可以使用如下代码来遍历并打印所有学生的信息:
for student, age in students.items():
print(student, "的年龄是:", age)
运行结果将输出:
Emily 的年龄是: 18
Tom 的年龄是: 20
这只是一个简单的字典例子,但希望可以帮助你对Python中的字典有一个初步的了解。
python入门程序有趣例子
以下是几个有趣的Python入门程序示例:
1. 猜数字游戏
```
import random
number = random.randint(1, 100)
guess = int(input("猜猜数字是多少(1-100):"))
while guess != number:
if guess < number:
print("猜小了")
else:
print("猜大了")
guess = int(input("再猜一次:"))
print("恭喜你,猜对了!")
```
2. 打字游戏
```
import time
word = "Hello, world!"
print("请在三秒内尽可能快地输入以下内容:", word)
start_time = time.time()
user_input = input()
end_time = time.time()
if user_input == word:
print("输入正确,用时:", end_time - start_time, "秒")
else:
print("输入错误")
```
3. 简单的计算器
```
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("请选择操作:")
print("1.加")
print("2.减")
print("3.乘")
print("4.除")
choice = input("请选择(1/2/3/4):")
num1 = float(input("请输入第一个数字:"))
num2 = float(input("请输入第二个数字:"))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("输入错误")
```
希望这些示例可以帮助您入门Python编程!
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)