提示用户在控制台输入个人信息,包括:姓名、年龄、住址,把用户信息保存到一个字典中;封装一个打印用户 信息的函数 print_user_info ,在函数中遍历字典中的键和值,并打印。
时间: 2024-04-11 16:31:01 浏览: 11
你可以使用以下代码来提示用户在控制台输入个人信息并保存到一个字典中,并封装一个函数来打印用户信息:
```python
def get_user_info():
user_info = {}
name = input("请输入您的姓名:")
age = input("请输入您的年龄:")
address = input("请输入您的住址:")
user_info["姓名"] = name
user_info["年龄"] = age
user_info["住址"] = address
return user_info
def print_user_info(user_info):
for key, value in user_info.items():
print(key + ":" + value)
# 测试代码
info = get_user_info()
print_user_info(info)
```
当你运行上述代码时,它将提示用户输入姓名、年龄和住址,并将这些信息保存到字典中。然后,它将调用 `print_user_info` 函数来打印用户信息。
相关问题
从控制台输入学生的姓名,年龄,住址保存到student.txt文件中
以下是Python代码实现:
```python
name = input("请输入学生姓名:")
age = input("请输入学生年龄:")
address = input("请输入学生住址:")
with open("student.txt", "w") as f:
f.write(f"姓名:{name}\n")
f.write(f"年龄:{age}\n")
f.write(f"住址:{address}\n")
print("保存成功!")
```
说明:
1. 使用`input()`函数获取用户输入的姓名、年龄和住址。
2. 使用`with`语句打开文件`student.txt`,并以写入模式(`"w"`)写入数据。
3. 使用`write()`方法将学生信息写入文件中,其中使用了f-string格式化字符串。
4. 关闭文件。
5. 输出保存成功的消息。
Java从控制台输入学生的姓名,年龄,住址保存到student.txt文件中
可以使用Java的IO流来实现将控制台输入的学生信息保存到文件中。具体实现步骤如下:
1. 创建Scanner对象并从控制台读取学生信息。
```java
Scanner scanner = new Scanner(System.in);
System.out.print("请输入学生姓名:");
String name = scanner.nextLine();
System.out.print("请输入学生年龄:");
int age = scanner.nextInt();
scanner.nextLine(); // 清除缓冲区
System.out.print("请输入学生住址:");
String address = scanner.nextLine();
```
2. 创建FileWriter和BufferedWriter对象,将学生信息写入文件。
```java
FileWriter fw = new FileWriter("student.txt", true); // true表示追加写入
BufferedWriter bw = new BufferedWriter(fw);
bw.write(name + "," + age + "," + address);
bw.newLine(); // 换行
bw.close();
fw.close();
```
完整代码如下:
```java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入学生姓名:");
String name = scanner.nextLine();
System.out.print("请输入学生年龄:");
int age = scanner.nextInt();
scanner.nextLine(); // 清除缓冲区
System.out.print("请输入学生住址:");
String address = scanner.nextLine();
FileWriter fw = new FileWriter("student.txt", true); // true表示追加写入
BufferedWriter bw = new BufferedWriter(fw);
bw.write(name + "," + age + "," + address);
bw.newLine(); // 换行
bw.close();
fw.close();
System.out.println("学生信息已保存到student.txt文件中。");
}
}
```
需要注意的是,如果要多次保存学生信息,应该将FileWriter和BufferedWriter对象的创建放在循环外面,避免重复创建对象。同时,每次写入学生信息时需要在末尾加上换行符,否则所有信息会写在同一行。