Python基础语法(一):输入输出(格式化输出、format())、注释、变量与数据类型、运算符

一、输入输出

第一个Python程序

# 注释格式

print("Hello,World!",end='')
print(54 + 7)
# 使用end=''可以更改print自动添加的换行符,常用来设置不换行
# 字符串拼接
print("It is " + "my world.")

循环输出

print("字符串" * 循环次数)

显示Python内置函数

dir(__builtins__) # 在IDLE Shell中运行该语句可以显示Python中的内置函数

格式化输出

第一种使用%,与数据类型有关
%c 字符
%s 字符串
%d 有符号十进制整数
%u 无符号十进制整数
%o 八进制整数
%x 十六进制整数(小写)
%f 索引符号

保留n位小数使用%.nf的语法(会进行四舍五入)

name = '小明'
classPro = '台州学院19化学1班'
age = 14
weight = 43.7375
print("name: %s"% name)
print("class: %s Age:%d" % (classPro, age))
print("weight:%.2f" %weight)

第二种使用.format()方法,不需要考虑数据类型

name = '佳怡'
classPro = '上海职业技术学院20物流1班'  # String type
weight = 65.34  # float type

print("姓名:{}".format(name))
print("班级:{}  体重:{}".format(classPro, weight))

input( ) 输入函数

input("字符串")

打印字符串并获取字符串后面输入的内容(String类型
数据类型转换函数

# 数据类型转换语法:   数据类型(变量名)
# 例如
age = int(ageStr)
weight = float(weiStr)

示例:

name = input("input your name:")
classPro = input("input your class:")
weight = input("input your weight:")
weight2 = float(weight)  #input输入获取的值都是String类型,必要时需要进行数据类型转换
    
print("name:{}".format(name))
print("class:%s"% classPro)
print("weight:%f" % weight2)
# 如果直接执行 print("weight:%f" % weight) 会报错

二、变量定义

变量名必须以字母或下划线开头
区分大小写
Python关键字不能作为变量名

a = 10
a1, a2 = 11, 12  # 将11赋值给a1,12赋值给a2
print("a =", a)  # 输出时变量a的前面自动添加一个空格符

b = 25
b = b + 3
print("b=", b)

c = 24.35
print(type(c))  # type(变量名) 返回该变量的数据类型
c2 = True       # 布尔类型的值首字母要大写
print(type(c2))

命名规范(便于开发者代码的管理与维护)

  • 形式一:userName、helloWorld
  • 形式二:UserName、HelloWorld
  • 形式三:user_name、hello_world

三、高级数据类型的变量定义

# 元组类型tuple
t1 = ()
print(type(t1))

# 列表类型list
l1 = []
print(type(l1))

# 字典类型dict
d1 = {}
print(type(d1))

五、运算符

算术运算符

a = 3
b = 7

print("a+b =", a + b)
print("a-b =", a - b)
print("a*b =", a * b)
print("a**b=", a ** b)  # a的b次幂
print("a/b =", a / b)  # 除法,包含小数
print("a%b =", a % b)  # 取余数
print("a//b=", a // b)  # 地板除,忽略小数,只保留整数位

'''运行结果
a+b = 10
a-b = -4
a*b = 21
a**b= 2187
a/b = 0.42857142857142855
a%b = 3
a//b= 0
'''

比较运算符

  • 等于:==
  • 不等于:!=
  • 大于:>
  • 小于:<
  • 大于等于:>=
  • 小于等于:<=

逻辑运算符

and,or,not
运算优先级:() > not > and > or

a, b, c, d = 34, 23, 5, 32

print(a + b > c and c < d)  # 与
print(a + b > c or c > d)  # 或
print(not a + b > c)  # 非

print(2 > 1 and 1 < 4 or 2 < 3 and 9 > 6 or 2 < 4 and 3 < 2)
print(
    (2 > 1 and 1 < 4) or
    (2 < 3 and 9 > 6) or
    (2 < 4 and 3 < 2)
)
# 多个逻辑运算尽量使用括号和换行缩进,使结构更清晰

赋值运算符

= , += , -= , *= , /= , %= , **= , //=

cc, aa = 1, 2
cc += aa
print(cc)  # 3
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晚风也很浪漫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值