Python 条件if语句:
score = 90 if score >= 90: # 一般格式,多重分支 print('优秀') elif score >= 80: print('良') elif score >= 60: print('及格') else: print('不及格') result = '及格' if score >= 60 else '不及格' # 三元运算 print(result) def add(x): print(x + 10) def default_method(x): print('什么都不做') operation = { 'add': add, 'update': lambda x: print(x * 2), 'delete': lambda x: print(x * 3) } operation.get('add', default_method)(10) operation.get('delet', default_method)(10)
Python while循环语句:
x = 'youpinketang' while x: # x为真true,循环;x为空字符串,为faulse停止循环 print(x, end=' ') x = x[1:] print('\n') x = 10 while x: x -= 1 if x % 2 != 0: continue print(x, end=' ') while True: name = input('请输入您的姓名:') if name == 'stop': break age = input('请输入您的年龄:') print('您好:{},您的年龄是:{},欢迎学习Pythpn'.format(name, age)) print('循环结束')
Python for循环语句:
for x in [1, 2, 3, 4]: # in 序列里面遍历 print(x, end=' ') lsum = 0 for x in [1, 2, 3, 4, 5]: lsum += x print(lsum) print('\n') emp = { 'name': 'Tom', 'department': 'tech', 'job': 'develop', 'salary': 9000.00 } for key in emp: print('{}=>{}'.format(key, emp[key])) s1 = 'youpinketang' s2 = 'coderoomg' result = [] for x in s1: if x in s2: result.append(x) print(result) l = [x for x in s1 if x in s2] print(l) for x in range(0, 101, 3): # range是生成器对象,不是函数返回序列 print(x) s = 'youpinkecheng' # 遍历输出每个字母及其索引位置序号 for idx, item in enumerate(s): # (idx, item)构成元组,括号可省略 print('{}=>{}'.format(idx + 1, item))