前言
python的语法基础(数据类型,输入、输出方法,转义符,结束符)
数据类型
- 整形: int
age = 20
print(type(age)) # int
- 浮点型:float
number = 10086.123
print(type(number)) # float
- 字符串:str
gender = "男"
print(type(gender)) # str
- 布尔:bool
The_sun_is_the_only_one = True # 太阳是唯一的(对)
The_sun_is_not_the_only_one = False # 太阳不是唯一的(错)
print(type(The_sun_is_the_only_one)) # bool
print(type(The_sun_is_not_the_only_one)) # bool
- 集合:set
student_name = {'小明','小猴','小刚'}
print(type(student_name)) # set
- 元组:tuple
animal = ('大象','狮子','老虎')
print(type(animal)) # tuple
- 字典:dict (dictionary)
student = {name:'小明',gender:'男'}
print(type(student)) # dict
- 列表:list
student_name = ['小明','小黄','小兰']
print(type(student_name)) # list
输入方法
input 函数会暂时停止程序的执行,等待用户输入完毕后,才能继续执行后面代码
可以在input前面加数据类型来转换用户输入的数据
user_name = str(input('请输入用户名')) #默认是str可不加
print(user_name)
print(type(user_name)) # str
age = int(input('请输入年龄')) #用户输入的转为int
print(age)
print(type(age)) # int
print('end')
输出方法
name = '张三'
age = 18
print('您的名字是'+name)
# %s 相当于是一个占位符
print('您的名字是%s'% name)
# 太low,而且不方便(不建议使用)
print('您的名字是'+name+',您的年龄是'+str(age))
# 传统的字符串和变量的拼接方式
print('您的名字是%s,你的年龄是%s'%(name,age))
# f 格式化:推荐
print(f'您的名字是{name},你的年龄是{age}')
您的名字是张三
您的名字是张三
您的名字是张三,您的年龄是18
您的名字是张三,你的年龄是18
您的名字是张三,你的年龄是18
price = 1799.5678
# 保留小数点后两位(四舍五入)
print('商品价格是%.2f'%price)
# : 后面叫格式说明符,类似于linux 中的管道符
print(f'商品价格是{price:.2f}')
商品价格是1799.57
商品价格是1799.57
student_id1 = 1
student_id2 = 20
student_id101 = 101
# %.3d: 将变量长度编程3,方式为在变量左侧加上对应个数的字符默认为零(不加.显示空格)
print('你的学号是%.3d'%student_id1)
print('你的学号是%.3d'%student_id2)
print('你的学号是%d'%student_id101)
# 使用f函数补齐
print(f'你的学号是{student_id1:03}') # (加0用0补充)
print(f'你的学号是{student_id1:3}')
你的学号是001
你的学号是020
你的学号是101
你的学号是001
你的学号是 1
转义符
当解释器看到/n时,就会换行输入接下来的内容
print('hello\nworld')
hello
world
当解释器看到/t时,就会连续输出四个空格,然后在输出接下来的内容
print('hello\tworld')
hello world
想输入\n或者\t,不换行,不空格
print(R'hello\nworld')
print(r'hello\tworld')
print('hello\\nworld')
hello\nworld
hello\tworld
hello\nworld
结束符
print 函数的第二个参数,用来设置第一个参数输出后,接着又要输出的内容,默认值 \n
print('hello')
print('hello,end='\n'')
hello
hello
print('hello',end='\t')
print('world',end='|')
print('你好')
hello world|你好