输入输出与基本运算符

输入与输出

在python3中的input会将用户输入的任何内容都存成str类型

name=input("请输入您的用户名: ")     name="egon"
pwd=input("请输入您的密码: ")         pwd='123'

if name == 'egon' and pwd == '123':
    print('登陆成功')
else:
    print('用户名或者密码输错了傻叉')
View Code

了解:
在python3中只有一个input,而python2中有input和raw_input
1.其中python2的raw_input与python3的input是一样
2 不一样的是:python2的input要求使用者必须输入一个明确的数据类型,输入什么类型就存成什么类型

age=input('>>>: ')      age="18"
print(age,type(age))
age=int(age) #age=int("18")      age=18
print(age > 30)

name=input('请输入您的用户名: ')
age=input('请输入您的年龄: ')

print('my name is my age is ',name,age)
print('my name is ',name,'my age is ',age)

print('my name is %s my age is %s' %(name,age))
print('my name is %s my age is %s' %([1,2,3],18))                   %s可以收任意类型的值
print('my name is %s my age is %d' %('egon',18))
print('my name is %s my age is %d' %('egon','18'))                %d只能接收整型
View Code

基本运算符

1 算术运算
print(10 + 1.1)
print(10 / 3) 有整数部分有余数部分
print(10 // 3) 去掉小数部分
print(10 % 3) 取余
print(2 ** 3)

2 比较运算
比较运算只能在同类型之间进行,其中int与float同属于数字类型
print(10 > 3.1)
print(10 >= 10)

了解
msg1='abcdefg'
msg2='abce'
print(msg2 > msg1)

list1=['a',1,'b']
list2=['a',2]
list2=['a','b']
list2=['c','b']
print(list2 > list1)

赋值运算

增量赋值

age=18
age=age + 1
age+=1 # age=age+1
print(age)
View Code

链式赋值

x=10
y=x
print(x is y)
a=b=c=d=e=111
print(a is b is c is d is e)
View Code

交叉赋值

x=10
y=20

temp=x
x=y
y=temp

x,y=y,x        #  比上面的利用中间量简单很多
print(x,y)
View Code

解压赋值

nums=[1,2,3,4,5]
a=nums[0]
b=nums[1]
c=nums[2]
d=nums[3]
e=nums[4]
a,b,c,d,e=nums
print(a,b,c,d,e)

a,b,c,_,_=nums          #  变量和_等于5个,对应列表五个元素
print(a,b,c)
print(_)

a,b,*_=nums        #只要列表的前两个值,*_相当于多个_号
print(a,b)
View Code

逻辑运算:and,or,not

and:连接左右两个条件,两个条件必须都成立,最后结果才为True,一旦左边条件为假则最终结果就为假,没有必要再去计算右面条件的值
print(1 > 2 and 3 > 1)

or:连接左右两个条件,两个条件但凡有一个成立,结果就为True,一旦左边条件为True则最终结果就为True,没有必要再去计算右面条件的值, 一旦左边条件为False,还需要去计算右面条件的值,如果为True,最终也True

not:取反
print(not 1 > 2 or 3 > 1)
print(not 1 > 2)
print((True and (False or True)) or (False and True))

python运算符优先级

以下运算符优先级顺序依次递增:

Lambda  #运算优先级最低
逻辑运算符: or
逻辑运算符: and
逻辑运算符:not
成员测试: in, not in
同一性测试: is, is not
比较: <,<=,>,>=,!=,==
按位或: |
按位异或: ^
按位与: &
移位: << ,>>
加法与减法: + ,-
乘法、除法与取余: *, / ,%
正负号: +x,-x
View Code
原文地址:https://www.cnblogs.com/596014054-yangdongsheng/p/9641637.html