四、格式化输出与基本运算符

1、格式化输出

  程序中经常会有这样的场景:要求用户输入信息,然后打印成固定的格式。

  比如要求用户输入用户名和年龄,然后打印如下格式:

  My name is xxx,my age is xxx.

  很明显,用逗号进行字符拼接,只能把用户输入的名字和年龄放到末尾,无法放到指定的xxx位置,而且数字也必须经过str(数字)的转换才能与字符串进行拼接。

  这就用到了占位符,如:%s,%d。

1.1、%s字符串占位符;可以接受字符串,也可以接收数字。例如:

print('My name is %s,My age is %s'%('egon',18))

1.2、%d字符串占位符;只能接收数字。例如:

print('My name is %s,My age is %d')%('egon',18)

print('My name is %s,My age is %s')%('egon',18)    #age为字符串类型,无法传给%d,所以会报错

1.3、接收用户指定输入,打印成指定格式

name=input('your name:')

age=input('your age:')     #用户输入18,会被存成字符串18,无法传给%d。

print('My name is %s,My age is %s'%(name,age))

2、基本运算符

  计算机科技进行的运算有很多种,可不只加减乘除这么简单,运算按照种类可以分成:数学运算,比较运算,逻辑运算,赋值运算,成员运算,身份运算,位运算。

2.1、算术运算

  假设变量:a=10,b=20

运算符 描述 实例
= 简单赋值运算符 c=a+b
+= 加法赋值运算符 c+=a等效于c=c+a
-= 减法赋值运算符 c-=a等效于c=c-a
*= 乘法赋值运算符 c*=a等效于c=c*a
/= 除法赋值运算符 c/=a等效于c=c/a
%= 取余数赋值运算符 c%=a等效于c=c%a
**= 幂赋值运算符 c**=a等效于c=c**a
//= 取整除赋值运算符 c//=a等效于c=c//a

2.2、逻辑运算

运算符 描述 实例
and “与”门, x为false,或者x和y都是false,输出x的值,否则返回y值 (a and b)返回true
or “或”门, x为true,输出x的值,否则返回y值 (a or b)返回true
not “非”门, x为true,输出x为false,x为false,输出x为true not(a and b)返回true

2.2.1、三者的优先级关系:not>and>or,同一级别默认从左往右计算。

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

2.2.2、最好用括号来区别优先级,其实意义与上面一样

原理为:
2.2.2.1、not的优先级最高,就是把紧跟其后的那个条件结果取反,所以not与紧跟其后的条件不可分割

2.2.2.2 、如果语句中全部是用and连接,或者全部用or连接,那么按照从左到右的顺序依次计算即可

2.2.2.3、如果语句中既有and也有or,那么先用括号把and的左右两个条件给括起来,然后再进行运算

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

Flase

2.2.3、短路运算:逻辑运算的结果一旦可以确定,那么就以当前计算到的值作为最终的结果返回。

>>> 10 and 0 or '' and 0 or 'abc' or 'egon' == 'dsb' and 333 or 10 > 4
我们用括号来明确一下优先级
>>> (10 and 0) or ('' and 0) or 'abc' or ('egon' == 'dsb' and 333) or 10 > 4
短路:       0          ''                  'abc'
                 假         假                  真

返回:                                       'abc'

2.2.4、短路运算面试题:
>>> 1 or 3                               #1
>>> 1 and 3                            #3
>>> 0 and 2 and 1                  #1 
>>> 0 and 2 or 1                     #1
>>> 0 and 2 or 1 or 4              #1
>>> 0 or False and 1               #False
2.2.5、身份运算

  is比较的是id

  而==比较的是值

posted @ 2020-02-27 22:31  疏星淡月  阅读(169)  评论(0编辑  收藏  举报