背景昨天,为小朋友介绍了 什么是变量、什么是运算符以及运算符的优先级、什么是数据类型以及类型之间的相互转换。 今天,为小朋友介绍程序设计语言中最常见的两种语句,第一种是条件语句,第二种是循环语句。
Python 基本语法1. 条件语句 if 语句 if expression: expr_true_suite
if 2 > 1 and not 2 > 3: print('Correct Judgement!')
else 语句 if expression: expr_true_suite else expr_false_suite
temp = input("不妨猜一下小哥哥现在心里想的是那个数字:") guess = int(temp) if guess == 8: print("你是小哥哥心里的蛔虫吗?") print("哼,猜对也没有奖励!") else: print("猜错了,小哥哥现在心里想的是8!") print("游戏结束,不玩儿啦!")
例子1 hi = 6 if hi > 2: if hi > 7: print('好棒!好棒!') else: print('切~')
例子2 temp = input("不妨猜一下小哥哥现在心里想的是那个数字:") guess = int(temp) if guess > 8: print("大了,大了") else: if guess == 8: print("你是小哥哥心里的蛔虫吗?") print("哼,猜对也没有奖励!") else: print("小了,小了") print("游戏结束,不玩儿啦!")
elif 语句 if expression1: expr1_true_suite elif expression2: expr2_true_suite . . elif expressionN: exprN_true_suite else: expr_false_suite
temp = input('请输入成绩:') source = int(temp) if 100 >= source >= 90: print('A') elif 90 > source >= 80: print('B') elif 80 > source >= 60: print('C') elif 60 > source >= 0: print('D') else: print('输入错误!')
assert 关键词 assert 3 > 7
2. 循环语句 while 循环 while expression: suite_to_repeat
count = 0 while count < 3: temp = input("不妨猜一下小哥哥现在心里想的是那个数字:") guess = int(temp) if guess > 8: print("大了,大了") else: if guess == 8: print("你是小哥哥心里的蛔虫吗?") print("哼,猜对也没有奖励!") count = 3 else: print("小了,小了") count = count + 1 print("游戏结束,不玩儿啦!")
for 循环 for iter_var in interables: suite_to_repeat
例子1 for i in 'ILoveLSGO': print(i, end=' ') #不换行输出
例子2 member = ['张三', '李四', '刘德华', '刘六', '周润发'] for each in member: print(each)
for i in range(len(member)): print(member[i])
range() 函数 range([start,] stop[, step=1])
例子1 for i in range(2, 9): #不包含9 print(i)
例子2 for i in range(1, 10, 2): print(i)
break 语句 import random secret = random.randint(1, 10) #[1,10]之间的随机数
while True: temp = input("不妨猜一下小哥哥现在心里想的是那个数字:") guess = int(temp) if guess > secret: print("大了,大了") else: if guess == secret: print("你是小哥哥心里的蛔虫吗?") print("哼,猜对也没有奖励!") break else: print("小了,小了") print("游戏结束,不玩儿啦!")
continue 语句 for i in range(10): if i % 2 != 0: print(i) continue i += 2 print(i)
pass 语句 def a_func():
# SyntaxError: unexpected EOF while parsing
def a_func(): pass
3. 综合例子 passwdList = ['123', '345', '890'] valid = False count = 3 while count > 0: password = input('enter password:') for item in passwdList: if password == item: valid = True break
if not valid: print('invalid input') count -= 1 continue else: break
总结好了,到此为止有关于条件和循环语句的内容就介绍完了。小朋友们要刻意练习哦,基于这些语句,我们后面能做很炫的游戏来玩儿!是不是有些小期待!
相关图文:
经过8年多的发展,LSGO软件技术团队在「地理信息系统」、「数据统计分析」、「计算机视觉」等领域积累了丰富的研发经验,也建立了人才培养的完备体系,由于自己准备在「量化交易」领域精进技能,如果大家对这个领域感兴趣可以与我联系,加入我们的量化学习群一起学习探讨。
在这个领域我已做了以下积累: 策略部分: 数据部分: 自动化交易部分:
|