Python基本输入和输出

Python 输出

在 Python 中,我们可以简单地使用 print() 函数来打印输出。例如:

print('Python is powerful')

# Output: Python is powerful

这里,print() 函数显示了用单引号括起来的字符串。

print() 的语法

在上面的代码中,print() 函数只接受一个参数。

然而,print 函数的实际语法接受 **5** 个参数

print(object= separator= end= file= flush=)

这里,

  • object - 要打印的值
  • sep(可选) - 允许我们分隔 print() 内部的多个 对象
  • end(可选) - 允许我们添加特定值,如换行符 "\n"、制表符 "\t"
  • file(可选) - 值打印的位置。其默认值为 sys.stdout(屏幕)
  • flush(可选) - 布尔值,指定输出是刷新还是缓冲。默认值:False

示例 1:Python Print 语句

print('Good Morning!')
print('It is rainy today')

输出

Good Morning!
It is rainy today

在上面的示例中,print() 语句只包含要打印的 对象。这里没有使用 end 的值。因此,它采用默认值 '\n'

所以我们得到两行不同的输出。


示例 2:带 end 参数的 Python print()

# print with end whitespace
print('Good Morning!', end= ' ')

print('It is rainy today')

输出

Good Morning! It is rainy today

请注意,我们在第一个 print() 语句的末尾包含了 end= ' '

因此,我们得到一行用空格分隔的输出。


示例 3:带 sep 参数的 Python print()

print('New Year', 2023, 'See you soon!', sep= '. ')

输出

New Year. 2023. See you soon!
 

在上面的示例中,print() 语句包含多个用逗号分隔的

请注意,我们在 print() 语句中使用了可选参数 sep= ". "

因此,输出包含用 . 而不是逗号分隔的项。


示例:打印 Python 变量和字面量

我们还可以使用 print() 函数来打印 Python 变量。例如:

number = -10.6

name = "Programiz"

# print literals     
print(5)

# print variables
print(number)
print(name)

输出

5
-10.6
Programiz

示例:打印连接的字符串

我们还可以将两个 字符串 连接在 print() 语句中。例如:

print('Programiz is ' + 'awesome.')

输出

Programiz is awesome.

这里,

  • + 运算符连接两个字符串 'Programiz is ''awesome.'
  • print() 函数打印连接后的字符串

输出格式化

有时我们希望格式化输出以使其更具吸引力。这可以通过使用 str.format() 方法来完成。例如:

x = 5
y = 10

print('The value of x is {} and y is {}'.format(x,y))

这里,大括号 {} 用作占位符。我们可以通过使用数字(元组索引)来指定它们的打印顺序。

要了解有关格式化输出的更多信息,请访问 Python 字符串 format()


Python 输入

在编程时,我们可能希望从用户那里获取输入。在 Python 中,我们可以使用 input() 函数。

input() 的语法

input(prompt)

这里,prompt 是我们希望在屏幕上显示的字符串。它是可选的。


示例:Python 用户输入

# using input() to take user input
num = input('Enter a number: ')

print('You Entered:', num)

print('Data type of num:', type(num))

输出

Enter a number: 10
You Entered: 10
Data type of num: <class 'str'>

在上面的示例中,我们使用 input() 函数从用户那里获取输入,并将用户输入存储在 num 变量中。

需要注意的是,输入的值 10 是一个字符串,而不是一个数字。因此,type(num) 返回 <class 'str'>

要将用户输入转换为数字,我们可以使用 int()float() 函数,如下所示:

num = int(input('Enter a number: '))

这里,用户输入的 数据类型 从字符串转换为整数。

视频:Python 获取用户输入

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战