目录
输出
格式化输出
格式化符号
f-字符串
转义字符
print的结束符
输入
输入功能的语法
输入input的特点
数据类型转换
作用
函数
测试函数
输出
作用:程序输出内容给用户
格式化输出
所谓的格式化输出即按照一定的格式输出类容。
格式化符号
重点掌握前3个%s(字符串)、%d(有符号的十进制整数)、%f(浮点数)。
讲解与联系
'''
1. 准备数据
2. 格式化符号输出数据
'''
age = 18
name = 'TOM'
weight = 75.5
stu_id = 1
# 1. 我今年的年龄是x岁--%d
print('我今年的年龄是%d岁'%age)
# 2. 我的名字是x--%s
print('我的名字是%s'%name)
# 3. 我的体重是x公斤--%f
print('我的体重是%.3f公斤'%weight)
# 4. 我的学号是x--%
print('我的学号是%d'%stu_id)
# 4.1 我的学号是001
print('我的学号是%03d'%stu_id)
# 5. 我的名字是x,今年x岁了
print('我的名字是%s,今年%d岁了'%(name,age))
# 6. 我的名字是x,今年x岁了,体重x公斤,学号是x
print('我的名字是%s,今年%d岁了,体重%f公斤,学号是%03d'%(name,age,weight,stu_id))
输出结果:
我今年的年龄是18岁
我的名字是TOM
我的体重是75.500公斤
我的学号是1
我的学号是001
我的名字是TOM,今年18岁了
我的名字是TOM,今年18岁了,体重75.500000公斤,学号是001
f-字符串
语法:f'{表达式}'
'''
1. 准备数据
2. 格式化符号输出数据
'''
age = 18
name = 'TOM'
weight = 75.5
stu_id = 1
# 6. 我的名字是x,今年x岁了,体重x公斤,学号是x
print('我的名字是%s,今年%d岁了,体重%f公斤,学号是%03d'%(name,age,weight,stu_id))
# 语法:f'{表达式}'
print(f'我的名字是{name},今年{age}岁了,体重{weight}公斤,学号是{stu_id}')
输出结果:
我的名字是TOM,今年18岁了,体重75.500000公斤,学号是001
我的名字是TOM,今年18岁了,体重75.5公斤,学号是1
转义字符
\n:换行
\t:制表符,一个tab键(4个空格)的距离
print('hallo\nworld')
print('hallo\tPython')
输出结果:
hallo
world
hallo Python
print的结束符
默认状态:
print('输出的内容',end='\n')
改变默认状态:
print('hallo world',end=' ')
print('123',end=' ')
输出结果 :
hallo world 123
输入
在Python中,程序接收用户输入的数据的功能即是输入。
输入功能的语法
input('提示信息')
输入input的特点
当程序执行到input,等待用户输入,输入完成之后才继续向下执行
在Python中,input接收用户输入后,一般储存到变量,方便使用
在Python中,input会把接收到的任意用户输入的数据都当做字符串处理
'''
1. 书写input
input('提示信息')
2. 观察特点
'''
password = input('密码:')
print(f'密码是{password}')
print(type(password))
输出结果:
密码:123
密码是123
<class 'str'>
数据类型转换
作用
将用户输入的内容转换格式
函数
'''
1. input
2. 检测类型
3. int()
4. 验证类型
'''
password = input('密码:')
print(f'密码是{password}')
print(type(password))
password = int(password)
print(type(password))
输出结果:
密码:123
密码是123
<class 'str'>
<class 'int'>
测试函数
# float()
from re import T
num1 = 1
str1 = '10'
print(type(float(num1)))
print(type(float(str1)))
print(float(num1))
print(float(str1))
# str()
print(type(str(num1)))
print(float(num1))
# tuple()
list1 = [1,2,3]
print(tuple(list1))
# list()
t1 = (10,20,30)
print(list(t1))
# eval()
str2 = '1'
str3 = '1.1'
str4 = '(1,2,3)'
str5 = '[10,20,30]'
print(type(eval(str2)))
print(type(eval(str3)))
print(type(eval(str4)))
print(type(eval(str5)))
输出结果:
<class 'float'>
<class 'float'>
1.0
10.0
<class 'str'>
1.0
(1, 2, 3)
[10, 20, 30]
<class 'int'>
<class 'float'>
<class 'tuple'>
<class 'list'>