简单 Python 快乐之旅之:Python 基础语法之输入输出操作专题

1. 打印到控制台输出

你可以使用 print() 函数来打印或回显数据到控制台。

# How to Print to Console in Python
print("Hello World! Welcome to Python Examples.")
print(10)

执行和输出:
打印到控制台输出.png
你可以传入一个字符串,或者一个数字,或者任意的其他数据类型。
在打印的结尾会自动追加换行。

1.1. 打印字符串到控制台

本示例中我们简单打印一个字符串到控制台输出。将字符串作为参数传给 print() 函数。

# Print String to Console
print("Hello World!")

执行和输出:
打印字符串到控制台.png

1.2. 打印数字到控制台

将数字作为参数传递给 print() 函数。

# Print number to console
print(526)

执行和输出:
打印数字到控制台.png

1.3. 打印变量到控制台

我们可以提供多个变量作为参数传给 print() 函数。它们将默认以单个空格作为分隔符打印到控制台。

# Print Variable to Console
x = "pi is"
y = 3.14
print(x, y)

执行和输出:
打印变量到控制台.png

1.4. 以特定分隔符进行打印

你可以传递特定的分隔符给 sep 参数。

# Python Print with a Specific Separator
x = "pi is"
y = 3.14
print(x, y, sep=" : ")

执行和输出:
以特定分隔符进行打印.png

1.5. 以特定结尾进行打印

在 Python 中,print() 函数默认使用换行符作为结束符。我们可以传递特定结束符给 end 参数对其进行重写。

# Python Print with a Specific End
print("Hello", end="-")
print("World", end=".\n")

执行和输出:
以特定结尾进行打印.png

2. 控制台读取数字

你可以使用 input() 函数在控制台读取一个用户输入的数字。实际上 Python3 并不会区分你的输入是字符串还是数字。无论你输入什么,它都当做是一个字符串。
要将输入当做一个数字的话,需要将其进行强制转换为一个整数类型。

# Read Number from Console
n = int(input("Type a number: "))
print(n)

执行和输出:
控制台读取数字.png
你可以使用一些数学运算来检验其是否是一个数字。

# Check if it is a number by performing some arithmetic operations
n = int(input("Type a number: "))
print(n)
print(n + 7)

执行和输出:
使用一些数学运算来检验其是否是一个数字.png

3. 控制台读取字符串

你可以使用 input() 函数从控制台读取一个字符串作为你的程序的输入。

# Read String from Console
inputStr = input("Enter a string: ")
print(inputStr)

执行和输出:
控制台读取字符串.png
input() 函数将返回你在控制台输入的字符串。

4. 多次打印之间不换行

print() 函数默认使用换行符作为打印的结束符,要在 Python 中的多次打印之间不换行的话,你可以对 print() 函数的 end=’’ 参数进行设置。
本示例来看一下如何在多次执行 print() 时不换行。

# Print without new line
print("Hello", end='')
print(" World.", end='')
print(" Welcome to", end='')
print(" defonds.net")

执行和输出:
多次打印之间不换行.png

参考资料

发布了273 篇原创文章 · 获赞 1324 · 访问量 649万+

猜你喜欢

转载自blog.csdn.net/defonds/article/details/100399380
今日推荐