python基礎之流程控制(if判斷和while、for循環)

程序執行有三種方式:順序執行、選擇執行、循環執行java

1、if條件判斷

一、語句  python

  (1)簡單的 if 語句
  (2)if-else 語句
  (3)if-elif-else 結構
  (4)使用多個 elif 代碼塊if-elif-elif-...-else(elif可使用多個)
  (5)省略 else 代碼塊if-elif-elif(else能夠省去)
  (6)測試多個條件(簡單if語句)運維

二、注意:dom

  (1)if 語句能夠相互嵌套;oop

  (2)if嵌套,能夠嵌套多層,可是通常嵌套兩層就好了,若是嵌套多層的話不便維護代碼,若須要嵌套多層,確定能夠用其它方式代替多層嵌套這種方式。測試

三、實例1:雲計算

#if嵌套用法
names = ["李國祥","任彥忠","畢洪態","張立佳"]
password = 123
name = input("請輸入您的名字:")
if name in names:
    passwd = int(input("請輸入密碼:"))
    if passwd == password:
        print("歡迎光臨!")
    else:
        print("密碼錯誤,請從新輸入!")
elif name == "遊客":
    print("歡迎加入!")
else:
    print("請輸入正確的用戶名!")
print("人生苦短,我學python!") 

四、實例2:猜年齡spa

#在程序裏設定好你的年齡,而後啓動程序讓用戶猜想,用戶輸入後,根據他的輸入提示用戶輸入的是否正確,若是錯誤,提示是猜大了仍是小了
my_age = 18
guess_age = int(input("請猜想個人年齡:"))
if guess_age == my_age:
    print("恭喜您纔對了!獎勵大大滴")
elif guess_age <= my_age:
    print("猜小了,人家已經成年了")
else:
    print("猜大了,我有那麼老麼?")

外層變量,能夠被內層代碼使用;code

內存變量,不該被外層代碼使用。orm

2、while循環

通常狀況下,須要屢次重複執行的代碼,均可以用循環的方式來完成

循環不是必需要使用的,可是爲了提升代碼的重複使用率,因此有經驗的開發者都會採用循環

實例1:1~100的累加求和

#計算1~100的累計和
i = 1
sum = 0
while i <= 100:
   sum = sum + i
   i += 1
print("1~100的累積和爲:%d"%sum)

實例2:99乘法表

i = 1
while i <= 9:
    j = 1
    while j <= i:
        print("%d*%d=%d\t"%(j,i,i*j),end="")
        j +=1
    print("")
    i +=1

實例3:打印1~100之間的偶數

#輸出1-100之間的全部偶數
i = 1
while i <= 100:
    if i%2 == 0:
        print("i==%d"%i)
    i += 1

實例4:猜年齡,只有3次機會

my_age = 18
count = 0
while count < 3:
    guess_age = int(input("請猜想個人年齡:"))
    if guess_age == my_age:
        print("恭喜您纔對了!獎勵大大滴")
        break
    elif guess_age < my_age:
        print("猜小了,人家已經成年了")
    else:
        print("猜大了,我有那麼老麼?")
    count += 1
else:
    print("猜這麼屢次都沒纔對,你個笨蛋")

實例5:

count = 0
while True:
    print("你是風兒我是沙,纏纏綿綿到天涯...",count)
    count +=1
    if count == 100:
        print("去你媽的風和沙,大家這些脫了褲子是人,穿上褲子是鬼的臭男人..")
        break

3、for循環

  像while循環同樣,for能夠完成循環的功能。
  在Python中 for循環能夠遍歷任何序列的項目,如一個列表、字符串、元組等等。
  for循環的格式:
  for 臨時變量 in 列表或者字符串等:
    循環知足條件時執行的代碼
  else:
    循環不知足條件時執行的代碼

實例1:遍歷

name = "python"
for i in name:
    print("----------------------")
    print(i)

實例2:continue、break

continue的做用:用來結束本次循環,緊接着執行下一次的循環

break的做用:用來結束整個循環

for i in range(10):
    if i<5:
        continue #不往下走了,直接進入下一次loop
    print("loop:", i )
------------------------------------------------------------------
loop: 5
loop: 6
loop: 7
loop: 8
loop: 9
for i in range(10):
    if i>5:
        break #不往下走了,直接跳出整個loop
    print("loop:", i )
------------------------------------------------------------------
loop: 0
loop: 1
loop: 2
loop: 3
loop: 4
loop: 5
#pass,continue,break

#continue跳過本次循環進入下一次循環
 count = 0
 while count <= 5 :
     count += 1
     if count == 3:
         continue
     print("Loop", count)

#breck跳出循環體
 count = 0
 while count <= 5 :
     count += 1
     if count == 3:
         break
     print("Loop", count)

# pass用來佔位的%s,%d,{}
 count = 0
 while count <= 5 :
     count += 1
     if count == 3:
         pass
     print("Loop", count)

實例3:猜拳遊戲

#猜拳遊戲
import random
win = 0
lose = 0
ping = 0
while True:
    print('=====歡迎來猜拳=====')
    print('勝:{}   敗:{}   平:{}'.format(win, lose, ping))
    print('1.石頭   2.剪刀   3.布   4.退出')
    computer = random.choice(['石頭','剪刀','布'])
    hum = input('==>:')
    #贏
    if (hum == '1' and computer == '剪刀') or (hum == '2' and computer =='布') or (hum == '3' and computer == '石頭'):
        print('挺牛逼!')
        win += 1

    #輸
    elif hum == '3' and computer == '剪刀' or hum == '1' and computer =='布' or hum == '2' and computer == '石頭':
        print('菜雞!')
        lose += 1
    #平
    elif hum == '2' and computer == '剪刀' or hum == '3' and computer =='布' or hum == '1' and computer == '石頭':
        print('不要走,決戰到天亮')
        ping += 1
    elif hum == '4':
        break
    else:
        print('別瞎輸入!!')
    print()
    print()
    print()
    print()

實例4:用戶登陸驗證

第一種方法:
#輸入用戶名和密碼,認證成功後顯示歡迎信息,輸錯三次後鎖定
user_info = {'任彥忠':'123','ryz':'123','renyz':'ryz'} count = 0 while count < 3: user_name = input("請輸入您的用戶名:").strip() if user_name in user_info.keys(): twice_count = count while twice_count < 3: pass_word = input("請輸入您的密碼:").strip() if pass_word == user_info.get(user_name): print("歡迎登錄") exit() else: print("密碼錯誤,請從新輸入") twice_count += 1 count = twice_count else: print('請輸入正確的用戶名!') count += 1 continue else: print("您已經輸錯三次了,請稍後重試")
第二種方法:
count = 1 # 定義循環的次數,初始值爲1 user = 'test' pwd = '123' while True: # 當循環的次數等於4時,結束循環。count的值通過自加1操做後將會依次走1,2,3這三個數的變化,這就是3次了。 if count == 4: print('Too many times!') # 當超過3次了,提示用戶超過嘗試登錄次數過多了。 break username = input('Please enter your username:').strip() # 去除用戶輸入時字符串兩邊的空格 password = input('Please enter your password:').strip() # 去除用戶輸入的字符串兩邊的空格 # 若是用戶輸入的內容有值時進行如下判斷 if username or password: # 當判斷用戶名和密碼都正確時結束循環。 if username == user and password == pwd: print('Login successfully!') exit() # 當用戶名和密碼匹配成功時退出程序 # 當判斷用戶名或密碼不正確時走else下的條件。 else: print('Login failed,you have %s more chances' % (3 - count)) # 若是用戶輸入的值爲None時,則執行如下打印操做。 else: print('Please enter your user name and password before landing') continue # 當用戶輸入爲空時,跳出本次循環,繼續執行以下。 # 讓每一次循環都進行自加1操做。 count += 1

實例五:多級菜單

#三級菜單,可依次選擇進入各子菜單
data = { "北京":{ "昌平":{ "沙河":{"oldboy","test"}, "天通苑":{"鏈家地產","我愛我家"} }, "朝陽":{ "望京":{"奔馳","陌陌"}, "國貿":{"CICC","HP"}, "東真門":{"Advent","飛信"}, }, "海淀":{ "運維":{"計算機","IP"}, "雲計算":{"python","java"}, "工程師":{"技術大牛","管理"}, }, }, "山東":{ "德州":{"1","2"}, "青島":{"3","4"}, "濟南":{}, }, "山西":{ "太原":{}, "大同":{}, "晉中":{}, }, } exit_flag = False while not exit_flag: for i in data: print(i) choice = input("選擇進入1>>:") if choice in data: while not exit_flag: for i2 in data[choice]: print("\t",i2) choice2 = input("選擇進入2>>:") if choice2 in data[choice]: while not exit_flag: for i3 in data[choice][choice2]: print("\t\t",i3) choice3 = input("選擇進入3>>:") if choice3 in data[choice][choice2]: for i4 in data[choice][choice2][choice3]: print("\t\t\t",i4) choice4 = input("最後一層,按b返回>>:") if choice4 == "b": pass elif choice4 == "q": exit_flag = True if choice3 == "b": break elif choice3 == "q": exit_flag = True if choice2 == "b": break elif choice2 == "q": exit_flag = True
相關文章
相關標籤/搜索