04 Python语法之用户交互与基本运算符
一、与用户交互
1、接收用户输入
python3中的input会把用户输入的所有内容都存成str类型
age = input("请输入您的年龄: ") # "内容"
print(age,type(age))
age=int(age)
print(age > 10) # "18" > 10
补充:int可以把纯数字组成的字符串转换整型
int("31") # ok
res = int(" 31 ") # ok
res = int("3 1") # no
print(res,type(res))
python2(***)
raw_input()与python3的input一模一样
input()要求用户必须输入一个明确的数据类型,输入什么类型就存成什么类型
2、输出
print("hello1",end='*')
print("hello2",end='*')
print("hello3",end='*')
msg = "my name is %s my age is %s" % ("egon", "18")
msg = "my name is %s my age is %d" % ("egon", 18)
msg = "my name is %s my age is %s" % ("egon", 18)
msg = "my name is %s my age is %s" % ("egon", [1,2,3])
print(msg)
二、基本运算符
1 算术运算符
x = 10
y = 20
print(x + y)
print(10 + 20)
print(10 // 3)
print(10 / 3)
print(10 % 3)
print(10 ** 2)
print(10 + 3.1)
了解:+与*
print("abc"+"def")
print([1,2,3]+[3,4,5])
print("abc"*3)
print([1,2,3]*3)
补充:python是一门解释型、强类型、动态语言(数据类型的概念比教强硬,严格,数据类型不能混用,所以是强类型;数据类型在代码运行时才知道,所以称为动态语言)
补充:go是一门编译型、强类型、静态语言
"18" + 10
x = 10
2. 比较运算符
判断是否相等,没有类型限制
print("abc" == 10) # 判断的是值及其类型是否相等
print("abc" != 10) # 判断的是值及其类型是否相等
> >= < <=:主要用于数字类型
print(10 > 3.1)
了解:> >= < <=也可以给其他类型用,但仅限于同类型之间
x = "abcdefg"
y = "abz"
print(x > y)
x = [111, 'abcdefg', 666]
y = [111,'z']
print(x > y)
3.赋值运算符
3.1 增量赋值
age = 18
age += 1 # age = age + 1
age -= 1 # age = age - 1
print(age)
3.2 链式赋值
x = y = z = 100
3.3 交叉赋值
x = 100
y = 200
temp = x
x = y
y = temp
del temp
x,y=y,x
print(x) # 200
print(y) # 100
3.4.解压赋值
salaries = [11, 22, 33, 44, 55]
mon1 = salaries[0]
mon2 = salaries[1]
mon3 = salaries[2]
mon4 = salaries[3]
mon5 = salaries[4]
mon1, mon2, mon3, mon4, mon5 = salaries
mon1, mon2, mon3, mon4, mon5 ,mon6= salaries # 错误
mon1, mon2, mon3, mon4 = salaries # 错误
print(mon1, mon2, mon3, mon4, mon5)
mon1,mon2,*_ ,last = salaries
print(mon1)
print(mon2)
print(_)
_,*x,_ = salaries
print(x)
了解:
x, y, z = {'k1': 111, 'k2': 222, 'k3': 3333}
x, y, z = "abc"
print(x,y,z)
4 逻辑运算符
逻辑运算符是用来运算条件的,那什么是条件???
只要结果为布尔值的都可以当做条件
总结:逻辑运算符,算的是显式的布尔值或者隐式的布尔值
4.1 not:取反
print(not 10 > 3)
print(not False)
print(not 123)
4.2 and: 链接多个条件,多个条件必须同时成立,最终结果才为True
print(10 > 3 and True and 'xx' == 'xx')
print(10 > 3 and False and 'xx' == 'xx')
print(10 > 3 and None and 'xx' == 'xx')
print(10 > 3 and True and 'xx' == 'xx' and 111)
4.3 or: 链接多个条件,多个条件但凡有一个成立,最终结果就为True
print(10 > 3 or False or 'xx' == 'xx')
print(0 or None or "" or 1 or True or 10 > 3)
强调:优先级not>and>or
print(3 > 4 and 4 > 3 or 1 == 3 and not 'x' == 'x' or 3 > 3)
(3 > 4 and 4 > 3) or (1 == 3 and not 'x' == 'x') or 3 > 3
ps:短路运算-》偷懒原则
5.成员运算符
print("abc" in "xxxabcxxxxx")
print(111 in [222,333,1111])
print('k1' in {'k1':111,'k2':222}) # 字典的成员运算判断的是key
print('k3' not in {'k1': 111, 'k2': 222}) # 推荐
print(not 'k3' in {'k1': 111, 'k2': 222}) # 不推荐
6. 身份运算符:is判断的是id是否一样
x = 100
y = x
print(x is y)
print(x == y)
总结:==成立is不一定成立,但是is成立==一定成立
id不同的情况下,值有可能相同,即2块不同的内存空间里可以存相同的值
id相同的情况下,值一定相同。x is y 成立===>x=y,必然成立
l1 = [111]
res=l1.append(222)
print(res == None) # 可以,但是不够好
print(res is None) # 推荐