二、python的输入与输出

目录

一、python的输入

1.输入的意义

2.在python中的实现方式(input函数)

3.input函数的更多细节

1.函数的返回类型

2.改变返回类型

3.提示字

二、python的输出

1.意义

2.在python中的实现方式(print函数)

3.print函数格式化输出(五种方式)

1.百分号输出    

2.format函数

3.简化版的format

4. 使用 + 连接  

5.通过可变参数传值

4.print函数的参数

0.转义字符

1.end参数

2.sep参数


输入与输出的意义:建立现实世界与计算机世界的信息传输或交换的一种桥梁

一、python的输入

1.输入的意义

        将现实世界的信息传入计算机世界中。

2.在python中的实现方式(input函数)

通过input函数实现

语法:

input()

3.input函数的更多细节

1.函数的返回类型

 通常使用一个变量进行接受。

代码:

a = input()

input函数通过接收你在终端输入的信息,并将该信息作为字符串类型反回给变量a。

为什么是字符串呢?

通过type函数及可判断。

代码:

a = input()
print(type(a))

运行结果:

1
<class 'str'>

第一行是我们通过终端输入的值,第二行是通过print函数输出的结果。

2.改变返回类型

通过eval函数可以,让程序自动判断输入的类型。

代码:

a = eval(input())
print(type(a))

运行结果:

1.2
<class 'float'>

3.提示字

代码:

a = input("请你输入1-9的任意一个数字:")

运行结果:

请你输入1-9的任意一个数字:

此时,我们只需要在  :后输入及可。

注意:

input(' ') 与 input(" ") 没有区别。

二、python的输出

1.意义

将计算机世界中程序计算的结果返回给现实世界中。

2.在python中的实现方式(print函数)

通过print函数实现。

基础语法:

print(13)

运行结果:
13

3.print函数格式化输出(五种方式)

1.百分号输出    

语法:print("%格式" % 变量名)

代码:

name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))

运行结果:

My name is Alice and I am 25 years old.

2.format函数

语法:   print("".format(变量名))

代码:

name = "Bob"
age = 30
print("My name is {} and I am {} years old.".format(name, age))

运行结果:

My name is Bob and I am 30 years old.

3.简化版的format

语法:    print(f"{变量名}")

代码:

name = "Charlie"
age = 35
print(f"My name is {name} and I am {age} years old.")

运行结果:

My name is Charlie and I am 35 years old.

4. 使用 + 连接  

语法:    print("" + 变量名)

代码:

name = "David"
age = 40
print("My name is " + name + " and I am " + str(age) + " years old.")

运行结果:

My name is David and I am 40 years old.

注意:使用+连接时,所有变量必须先转换为字符串类型(如str(age)

5.通过可变参数传值

语法:     print(变量1,变量2,变量3)

代码:

name = "Eve"
age = 45
print("My name is", name, "and I am", age, "years old.")

运行结果:

My name is Eve and I am 45 years old.

4.print函数的参数

0.转义字符

\t : 制表符,一个tab键(四个空格)的距离。

\n:换行符。

1.end参数

print函数中的end参数控制输出是以什么结束,默认值为换行符(\n)。

代码:

print("Hello", end=" ")
print("World")

运行结果:
 

Hello World

解释:

在这个例子中,end=" "将两个print语句的输出连接在一起,并在它们之间添加了一个空格。

2.sep参数

sep参数在python格式输出(通过可变参数传值)中起作用,用来控制个值是如何分割的,默认值为一个空格。

代码:
 

print("Python", "is", "awesome", sep="-")

输出结果:

Python-is-awesome

作者:是意

物联沃分享整理
物联沃-IOTWORD物联网 » 二、python的输入与输出

发表回复