注:同一优先级计算顺序从右往左
成员运算符用于在指定的序列中查找某个值是否存在。
n = [1,2,3,4,5,'a'] if 'a' in n: print('IN') if 'a' not in n: print('IN') else: print('NOT IN') # 输出: # IN # NOT IN测试两个变量是否指向同一对象
n = [1,2,3] m = n if n is m: print('同一对象') else: print('不是同一对象') # 输出:同一对象 m = [2,2,2] if n is m: print('同一对象') else: print('不是同一对象') # 输出:不是同一对象格式:
表达式1 if 表达式 else 表达式2先求if后面表达式的值,如果为True,则求表达式1,并以表达式1的值作为条件运算的结果,如果为False,以表达式2的值作为条件运算符结果。
x,y = 40,50 z = x if x==y else y print('%06.2f'%(z)) #输出:050.00最后一个else 可以不写
还有其他的就省略了
输入一个整数,判断它是否为水仙花数。所谓水仙花数,指这样的一些3位整数:各位数字的立方和等于该数本身,例如153 = 1^3 + 5^3 + 3^3 ,因此153是水仙花数。
def fun(): x = int(input("请输入一个3位数整数")) # input 函数返回值为字符串,所以需要强制转换 x1 = x % 100 x2 = (x / 10) % 10 x3 = x % 10 if(x == x1**3 + x2**3 + x3**3): print('{}水仙花数'.format(x)) else: print('{}不是水仙花数'.format(x)) return 0 def main(): fun() main() 输入:请输入一个3位数整数153 输出:153不是水仙花数输入一个时间(小时:分钟:秒),输出该时间经过5分30秒后的时间。
def fun(hour,minute,second): second +=30 if second > 60: second -= 60 minute +=1 minute +=5 if second > 60: minute -=60 hour +=1 while hour > 24: hour -= 24 print('{}:{}:{}'.format(hour,minute,second)) def main(): hour = int(input("请输人小时:")) minute = int(input("请输入分钟:")) second = int(input("请输入秒:")) fun(hour,minute,second) main() # 输入: # 请输人小时:8 # 请输入分钟:12 # 请输入秒:56 # 输出: # 8:18:26(1)工作时间超过120小时,超过部分加发15% (2)工作时间低于60小时,扣发700元 (3)其余按84元每小时计发。
输入员工的工号和该员工的工作时数,计算应发工资:
def fun(gh,gz): sum = 0 if gz > 120: sum += (gz-120)*84*1.15 + gz*84 else: if gz>=60: sum = gz*84 else: sum = gz*84 -700 print("{}号职工应发工资{}".format(gh,sum)) def main(): gh,gz = eval(input("分别输入工号和工作时长,以逗号分隔")) fun(gh,gz) main() #输入: # 分别输入工号和工作时长110,60 #110号职工应发工资5040输入年月,求该月的天数 每年 1 3 5 7 8 10 12月有31天,4 6 9 11月有30天,闰年2月29天,平年2月28天 年份能被4整除,但不能被100整除,或者能被400整除的年均是闰年
def fun(year,month): _31 = [1,3,5,7,8,10,12] _30 = [4,6,9,7] if month in _31: print("{}月有31天".format(month)) return 0 if month in _30: print("{}与有30天".format(month)) return 0 flag = (year % 4) == 0 and (year % 100) != 0 or year % 400 == 0 print("2月有{}天".format( 29 if flag else 28 )) def main(): year = int(input("year=")) month = int(input("month=")) fun(year,month) main() # 输入: # year=2014 # month=12 # 输出: # 12月有31天 # 输入: # year=2000 # month=2 # 输出: # 2月有29天