python-if判斷

1. python 條件語句
  Python條件語句是經過一條或多條語句的執行結果(True或者False)來決定執行的代碼塊。
  能夠經過下圖來簡單瞭解條件語句的執行過程:

  Python程序語言指定任何非0和非空(null)值爲true,0 或者 null爲false。
  Python 編程中 if 語句用於控制程序的執行,基本形式爲:python

if 判斷條件:
    執行語句……
else:
    執行語句……

  其中"判斷條件"成立時(非零),則執行後面的語句,而執行內容能夠多行,以縮進來區分表示同一範圍。編程

  else 爲可選語句,當須要在條件不成立時執行內容則能夠執行相關語句,具體例子以下:
2. 場景1、用戶登陸驗證spa

案例1:
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# Author:shichao
# File: .py

import getpass

_username = 'alex'
_password = 'abc123'
username = input("username:")
password = input("password:")

if _username == username and _password == password:
    print("Welcome user {name} login..." .format(name=username))
else:
    print("Invalid username or password")

 

案例2:3d

#!/usr/bin/env python
# -*- coding: encoding -*-

# 提示輸入用戶名和密碼

# 驗證用戶名和密碼
# 若是錯誤,則輸出用戶名或密碼錯誤
# 若是成功,則輸出 歡迎,XXX!


import getpass


name = raw_input('請輸入用戶名:')
pwd = getpass.getpass('請輸入密碼:')

if name == "alex" and pwd == "cmd":
  print("歡迎,alex!")
else:
  print("用戶名和密碼錯誤")

 

3. 場景2、猜年齡遊戲
  在程序裏設定好你的年齡,而後啓動程序讓用戶猜想,用戶輸入後,根據他的輸入提示輸入的是否正確,若是錯誤,提示是猜大了仍是小了code

my_age = 29

user_input = int(input("input your guess num:"))

if user_input == my_age:
    print("Congratulations, you got it !")
elif user_input < my_age:
    print("Oops,think bigger !")
else:
    print("think smaller !")
相關文章
相關標籤/搜索