用Python写创建空字典,让用户输入三个学生的姓名年龄存入字典,输出字典中的内容
时间: 2024-05-24 08:11:26 浏览: 14
dict = {}
for i in range(3):
name = input("请输入第{}个学生的姓名:".format(i+1))
age = input("请输入第{}个学生的年龄:".format(i+1))
dict[name] = age
print(dict)
相关问题
python (1)创建字典dic_student,由用户一次输入五名学生的姓名和年龄,存入字典,输出字典中的内容,格式为
好的,以下是Python代码实现您的需求:
```python
# 创建一个空的字典
dic_student = {}
# 循环5次,每次获取用户输入的姓名和年龄,存入字典
for i in range(5):
name = input("请输入第{}个学生的姓名:".format(i+1))
age = input("请输入第{}个学生的年龄:".format(i+1))
dic_student[name] = age
# 输出字典中的内容
print("字典中的内容为:")
for name, age in dic_student.items():
print("{}的年龄是{}".format(name, age))
```
运行以上代码,您可以输入五个学生的姓名和年龄,程序会将其存入字典`dic_student`中,并按照指定格式输出字典中的内容。
创建空字典,有用户依次输入五名学生的姓名和年龄,存入字典dic_student,然后输出字典dic_student的内容。
好的,我理解了您的要求。以下是 Python 代码实现:
```python
dic_student = {}
for i in range(5):
name = input("请输入第%d名学生的姓名:" % (i+1))
age = int(input("请输入第%d名学生的年龄:" % (i+1)))
dic_student[name] = age
print("字典dic_student的内容为:")
print(dic_student)
```
当您运行该代码时,可以依次输入五名学生的姓名和年龄,然后程序将其存入字典 `dic_student` 中,并最终输出字典内容。注意,输入的年龄需要转换为整型。