標籤:pts 控制 got 基本 bigger 需求 學習 col 語句
1、Python使用者互動
程式難免會與使用者產生互動。
舉個例子,你會希望擷取使用者的輸入內容,並向使用者列印出一些返回的結果。我們可以分別通過 input() 函數與 print 函數來實現這一需求。
1 #!/user/bin/env ptyhon 2 # -*- coding:utf-8 -*- 3 # Author: VisonWong 4 5 name = input("name:") 6 age = int(input("age:")) 7 job = input("job:") 8 salary = int(input("salary:")) 9 10 info = """11 --------info of {0}-------12 name:{0}13 age:{1}14 job:{2}15 salary:{3}16 """.format(name,age,job,salary)17 18 print(info)
輸出結果:
1 E:\Python\PythonLearing\venv\Scripts\python.exe E:/Python/PythonLearing/test.py 2 name:VisonWong 3 age:27 4 job:code farmer 5 salary:10000 6 7 --------info of VisonWong------- 8 name:VisonWong 9 age:2710 job:code farmer11 salary:1000012 13 14 Process finished with exit code 0
這裡需要注意的是因為年齡與薪金都是數字,所以強制轉化為整形。
2、Python邏輯控制
if語句:
Python 編程中 if 語句用於控製程序的執行,基本形式為:
1 if 判斷條件:2 執行語句……3 else:4 執行語句……
其中"判斷條件"成立時(非零),則執行後面的語句,而執行內容可以多行,以縮排來區分表示同一範圍。
else 為可選語句,當需要在條件不成立時執行內容則可以執行相關語句,具體例子如下:
1 #!/user/bin/env ptyhon 2 # -*- coding:utf-8 -*- 3 # Author: VisonWong 4 5 6 name = input(‘請輸入使用者名稱:‘) 7 pwd = input(‘請輸入密碼:‘) 8 9 if name == "VisonWong" and pwd == "cmd":10 print("歡迎,Vison!")11 else:12 print("使用者名稱和密碼錯誤!")
輸出結果:
1 E:\Python\PythonLearing\venv\Scripts\python.exe E:/Python/PythonLearing/test.py2 請輸入使用者名稱:VisonWong3 請輸入密碼:cmd4 歡迎,Vison!5 6 Process finished with exit code 0
當判斷條件為多個值時,可以使用以下形式:
1 if 判斷條件1:2 執行語句1……3 elif 判斷條件2:4 執行語句2……5 elif 判斷條件3:6 執行語句3……7 else:8 執行語句4……
執行個體如下:
1 #!/user/bin/env ptyhon 2 # -*- coding:utf-8 -*- 3 # Author: VisonWong 4 5 age = 27 6 7 user_input = int(input("input your guess num:")) 8 9 if user_input == age:10 print("Congratulations, you got it !")11 elif user_input < age:12 print("Oops,think bigger!")13 else:14 print("Oops,think smaller!")
輸出結果:
1 E:\Python\PythonLearing\venv\Scripts\python.exe E:/Python/PythonLearing/test.py2 input your guess num:253 Oops,think bigger!4 5 Process finished with exit code 0
Python學習之路3——Python使用者互動及邏輯控制