Python提供了基本的输入和输出功能,这些功能通常是通过内置的input()
函数(用于输入)和print()
函数(用于输出)来实现的。以下是这两个函数的详细描述和示例:
1. print()
函数(输出)
print()
函数用于在控制台输出文本或其他类型的数据。它可以接受多个参数,并使用空格将它们分隔开,或者你可以使用sep
参数来指定分隔符。此外,你还可以使用end
参数来指定在每行末尾添加的字符(默认为换行符)。
示例:
# 输出字符串 | |
print("Hello, World!") | |
# 输出: Hello, World! | |
# 输出多个值,默认使用空格分隔 | |
print("Hello", "World") | |
# 输出: Hello World | |
# 输出多个值,并使用逗号作为分隔符 | |
print("Hello", "World", sep=", ") | |
# 输出: Hello, World | |
# 输出而不换行(使用end参数) | |
print("Hello", end="") | |
print("World") | |
# 输出: HelloWorld | |
# 注意:这里是在同一行输出,因为第一个print没有换行 | |
# 输出变量 | |
name = "Alice" | |
age = 30 | |
print("My name is", name, "and I'm", age, "years old.") | |
# 输出: My name is Alice and I'm 30 years old. | |
# 输出格式化字符串(使用format方法) | |
print("My name is {} and I'm {} years old.".format(name, age)) | |
# 输出: My name is Alice and I'm 30 years old. | |
# 使用f-string(Python 3.6+) | |
print(f"My name is {name} and I'm {age} years old.") | |
# 输出: My name is Alice and I'm 30 years old. |
2. input()
函数(输入)
input()
函数用于从控制台获取用户的输入。它接受一个可选的字符串参数作为提示信息,并返回用户输入的字符串(所有输入都被视为字符串类型)。
示例:
# 获取用户输入(无提示) | |
user_input = input() | |
print("You entered:", user_input) | |
# 假设用户输入 "test" | |
# 输出: You entered: test | |
# 获取用户输入并显示提示信息 | |
name = input("Please enter your name: ") | |
print("Hello,", name) | |
# 假设用户输入 "Bob" | |
# 输出: Hello, Bob | |
# 将用户输入转换为其他类型(例如整数) | |
try: | |
age = int(input("Please enter your age: ")) | |
print("You are", age, "years old.") | |
except ValueError: | |
print("Invalid input. Please enter an integer.") | |
# 假设用户输入 "25" | |
# 输出: You are 25 years old. | |
# 如果用户输入的不是整数(如 "twenty five") | |
# 输出: Invalid input. Please enter an integer. |
以上就是Python中基本的输入和输出功能,以及如何使用print()
和input()
函数来实现它们。