python 3学習ノート6--条件判断if文

3319 ワード

  • 簡単な例
  • cars = ['audi','bmw','toyota']
    
    for car in cars:
        if car == 'bmw':
            print(car.upper())
        else:
            print(car.title())
  • 条件テスト
  • 各if文のコアは、条件テストと呼ばれるTrueまたはFalseの値を持つ式です.
    1、等しいかチェック
    変数の現在の値を特定の値と比較します.
    2、等しいかどうかをチェックするときは大文字と小文字を考慮しない
    大文字と小文字が重要でない場合は、変数の値を小文字に変換して比較します.
    3、等しくないかチェックする
    2つの値が等しくないかどうかを判断するには、感嘆符と等号(!=);!いいえ.
    4、数字の比較
    age = 18
    if age == 18:
        print(age == 18)

    5、複数の条件をチェックする
    and or 
    6、特定の値がリストに含まれているかどうかを確認する
    requested_toppings = ['mushrooms', 'onions', 'pineapple']
    if 'mushrooms' in requested_toppings:
        print('mushrooms' in requested_toppings)

    7、特定の値がリストに含まれていないかどうかをチェックする
    not in
    banned_users = ['andrew', 'carolina', 'david']
    user = 'marie'
    
    if user not in banned_users:
        print(user.title() + ",you can post a response if you wish.")

    8、ブール式
    条件付きテストの別名
    if文
    age = 19
    if age >= 18:
        print("You are old enough to vote!")
        print("Have you registered to vote yet?")
    age = 17
    if age >= 18:
        print("You are old enough to vote!")
        print("Have you registered to vote yet?")
    else:
        print("Sorry, you are too young to vote.")
        print("Please register to vote as soon as you turn 18!")
    age = 12 
    if age < 4: 
        print("Your admission cost is $0.") 
        
    elif age < 18: 
        print("Your admission cost is $5.") 
    else:
        print("Your admission cost is $10.")
  • if文処理リスト
  • を用いる
    1、特殊要素を検査する
    requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
    for requested_topping in requested_toppings:
        if requested_topping == 'green peppers':
            print("Sorry, we are out of green peppers right now.")
        else:
            print("Adding " + requested_topping + ".")
    print("
    Finished making your pizza!")

    2、確定リストが空ではない
    requested_toppings = [] 
    if requested_toppings: 
        for requested_topping in requested_toppings: 
            print("Adding " + requested_topping + ".") 
        print("
    Finished making your pizza!") else: print("Are you sure you want a plain pizza?")

    3、複数のリストを使う
    available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
    requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
    for requested_topping in requested_toppings:
        if requested_topping in available_toppings:
            print("Adding " + requested_topping + ".")
        else:
            print("Sorry, we don't have " + requested_topping + ".")
    print("
    Finished making your pizza!")
  • if文のフォーマット
  • を設定する
    条件テストのフォーマットにおいて、PEP 8が提供する唯一の提案は、==、>=、<=などの比較演算子の両側にスペースを1つずつ追加することであり、例えばif
    age<4:if age<4:よりいいです.このようなスペースはPythonのコードの解読に影響を与えず、コードを読みやすくするだけです.