python(if)

前言

python 對於運維人員來說十分重要
實驗在pycharm之上完成
重命名:shift + F6

if(單一條件)


  • if condition:
    success thing

      age = 12
      
      if age >= 18:
          print('welcome to netbar')
    

if(if…else…)

  • if condition:
    success thing
    else:
    failed thing

      age = 18
      	
      if age >= 18:
          print('Welcome to netbar')
      else:
          print('Please go home and do homework')
    

if(if…elif…else)

  • 例:
    if c1:
    thing
    elif c2:
    thing

    else:
    thing

      holiday_name = 'a1'
      
      if holiday_name == 'a2':
          print('a2')
      elif holiday_name == 'a3':
          print('a3')
      else:
          print('a4')
    

if(嵌套)

  • 例:

    if c1:
    thing
    if c2:

    else:
    else:

      have_ticket = True
      
      knife_length = 29
      
      if have_ticket:
          print('Please come in')
          if knife_length > 20:
              print('length:%d ;too long,not permitted!' %knife_length)
          else:
              print('length: %d;acceptable long,come in' %knife_length)
      else:
          print('Please buy ticket')
    

    運行結果

      Please come in
      length:29 is too long not permitted!
    

if (and,or)

  • 例:
    and:
    condition1 and condition2
    True False
    or:
    condition1 and condition2
    True False

       python_score = 70
       c_score = 30
      
       if python_score > 60 and c_score >60:
           print('pass')
       else:
           print('failed')
      
      
      value = input('Value:')
      
      if not value:
          print('Check your input!')
    

if(練習)

  • 例:
    “”"
    1.從控制檯輸入要出的拳 —石頭(1)/剪刀(2)/布(3)
    2.電腦隨即出拳–先假定電腦只會出石頭,完成整體代碼功能
    3.比較勝負
    石頭 勝 剪刀
    剪刀 勝 布
    布 勝 石頭
    “”"

      import random
      
      #1.player
      player = int(input('Your Choice:'))
      
      #2.computer
      computer = random.randint(1,3)
      print(computer)
      
      #3.compare
      if((player == 1 and computer == 2) or (player == 2 and computer == 3)
              or (player == 3 and computer == 1)):
    

其他

random

在python中,要使用隨機數,首先需要導入隨即數模塊 – ‘工具包’
導入模塊後,可以直接在模塊名稱後面敲一個.然後Tab鍵,會提示該模塊中>包含的所有函數

  • 例:
    import random
    random.randint(a,b),返回[a b]之間的整數,包含a和b

      random.randint(12,20):生成隨機數n: 12 <= n <= 20
      random.randint(20,20): 結果永遠是20
      random.randint(20,12):結果會報錯:下限必須小於上限
    

後記

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章