python 入门条件与循环
条件语句
-
if
- if语句
- if表达式:代码块
- if语句还可以和else、elif(else if)语句组合构成更复杂的判断
- if表达式:代码块 elif 表达式:代码块 else:代码块
- if语句
-
练习
- chinese_zodiac = ‘鼠牛虎兔龙蛇马羊猴鸡狗猪’
- chinese_zodiac2 = ‘????????????’
- chinese_zodiac3 = ‘猴鸡狗猪鼠牛虎兔龙蛇马羊’
- year = int(input(‘请用户输入出生年份’))
- if (chinese_zodiac3[year % 12]) == ‘鼠’:
- print (‘?年运势???’)
for循环
- 循环语句
- while语句
- while 表达式:代码块
- for语句
- for迭代变量 in 可迭代对象 : 代码块
- while语句
- 练习
for cz in chinese_zodiac2: print (cz)
for i in range(1,13): print (i)
for year in range(2000, 2019) : print ('%s 年的生肖是 %s' %(year, chinese_zodiac2[year % 12]))
while循环
- 死循环
- while True: print (‘a’)
- while True: print (‘a’) break
- 练习
-
num = 5
while True:
print (‘a’)
num = num + 1
if num > 10 :
break -
import time
num = 5
while True:
num = num + 1
if num == 10 :
continueprint (num)
time.sleep(1)
-
for循环语句中的if嵌套
zodiac_name = (u’摩羯座’, u’水瓶座’, u’双鱼座’, u’白羊座’, u’金牛座’, u’双子座’, u’巨蟹座’, u’狮子座’, u’处女座’, u’天秤座’, u’天蝎座’, u’射手座’)
zodiac_name2 = (u’♑️’, u’♒️’, u’♓️’, u’♈️’, u’♉️’, u’♊️’, u’♋️’, u’♌️’, u’♍️’, u’♎️’, u’♏️’, u’♐️’)
zodiac_days = ((1,20), (2,19), (3,21), (4,21), (5,21), (6,22), (7,23), (8,23), (9,23), (10,23), (11,23), (12,23))
- 用户输入月份和日期
int_month = int(input(“请输入月份:”))
int_day = int(input(“请输入日期:”))
for zd_num in range(len(zodiac_days)) :
if zodiac_days[zd_num] >= (int_month, int_day):
print (zodiac_name[zd_num])
break
elif int_month == 12 and int_day > 23 :
print (zodiac_name[0])
break
while循环语句中的if嵌套
zodiac_name = (u’摩羯座’, u’水瓶座’, u’双鱼座’, u’白羊座’, u’金牛座’, u’双子座’, u’巨蟹座’, u’狮子座’, u’处女座’, u’天秤座’, u’天蝎座’, u’射手座’)
zodiac_name2 = (u’♑️’, u’♒️’, u’♓️’, u’♈️’, u’♉️’, u’♊️’, u’♋️’, u’♌️’, u’♍️’, u’♎️’, u’♏️’, u’♐️’)
zodiac_days = ((1,20), (2,19), (3,21), (4,21), (5,21), (6,22), (7,23), (8,23), (9,23), (10,23), (11,23), (12,23))
-# 用户输入月份和日期
int_month = int(input(“请输入月份:”))
int_day = int(input(“请输入日期:”))
n = 0
while zodiac_days[n] < (int_month, int_day) :
if int_month == 12 and int_day > 23:
break
n += 1
print (zodiac_name[n])