Python从零到一: 基本输入和输出

本文详细介绍了Python中的print()函数用于输出文本,支持格式化和多参数处理,以及input()函数用于获取用户输入,包括示例和错误处理。
摘要由CSDN通过智能技术生成


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()函数来实现它们。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值