python语法入门之与用户交互以及运算符

与用户交互

  1、什么是用户交互

    用户交互就是人往计算机里输入数据,计算机输出的结果

  2、为什么要与用户交互

    为了让计算机能够像人一样与用户沟通交流

  3、怎么使用

    3.1、输入(input)      

username = input('请输入您的用户名:')

#解释:将input获取到的用户输入绑定给变量名username,并且input获取到的用户输入全部都会转换成字符串

    3.2、输出(print)

      1、格式为print(),其中打印多个元素时,需要用逗号隔开。

      2、默认print功能有一个end参数,该参数的默认值为“\n”(代表换行),可以将end参数的值改成任意其他字符

print('hello',end='')
print('world')
#得到helloworld

print('hello',end='*')
print('world')
#得到hello*world

格式化输出

  1、概念

    将字符串中某些内容替换掉再输出就是格式化输出

  2、使用

    占位符%s:表示可以接受任意类型的值

    占位符%d:只能接受数字

    使用方式为:先使用占位符占位,在使用%按照位置一一替换

  参考一

name = input("name:")
age = input("age:")
sex = input("sex:")
job = input("job:")
msg = """
name : %s
age : %s
sex : %s
job : %s
    """
print(msg% (name, age, sex, job))

  参考二

res = '亲爱的%s你好!你%s月的话费是%s,余额是%s'
print(res % ('tom', 11, 100, 0))
print(res % ('jon', 11, 300, 20))
print(res % ('jake', 11, 500, -20))

基本运算符

  算术运算符

   比较运算符

   赋值运算符

    1、增量运算符

     2、链式赋值

x=10
y=10
z=10
x=y=z=10

    3、交叉赋值

m = 1
n = 2
#m和n的值做交换
#方法一:
x = m
m = n
n = x
print(m,n)
#得出m=2,n=1
#方法二:
m,n = n,m
print(m,n)
#得出m=2,n=1

    4、解压赋值

muns = [111, 222, 333, 444, 555]
# 常规操作
a = muns[0]
b = muns[1]
c = muns[2]
d = muns[3]
e = muns[4]
# 解压赋值
a, b, c, d, e, = muns[0][1][2][3][4]
# 进阶
a, *_ = muns
a, *_, e = muns

    注:当元素比较多,而我们只想取一两个值时,可以用 *_ 匹配

      字符串、字典、列表、元组、集合类型都支持解压赋值

  逻辑运算符

     :当三个逻辑运算符混合使用时,是有优先级的。三者的关系是not>and>or,同一级默认从左往右计算。但是我们在编写的时候最好人为的规定好优先级

    连续多个and

2 > 1 and 1 != 1 and True and 3 > 2 # 判断完第二个条件,就立即结束,得的最终结果为False
False

    连续多个or

2 > 1 or 1 != 1 or True or 3 > 2 # 判断完第一个条件,就立即结束,得的最终结果为True
True

    三个混合使用

3>4 and 4>3 or 1==3 and 'x' == 'x' or 3 >3
False


(3>4 and 4>3) or (1==3 and 'x' == 'x') or 3 >3
False

  成员运算

 

     注意:虽然下面两种判断可以达到相同效果,但是推荐使用第二种,因为not in语义更加明确

not 'lili' in ['jack','tom','robin']
True
'lili' not in ['jack','tom','robin']
True

  身份运算

   判断两个数据,值和内存地址是否相等。其中符号==只判断值,is判断内存地址

     注意:值相等内存地址不一定相等,内存地址相等值一定相等

 

posted @ 2021-11-03 17:22  那就凑个整吧  阅读(119)  评论(0编辑  收藏  举报