pyhton基礎知識——用戶輸入/if語句/while循環

1. if語句

1.1 if-elif-else結構

>>> age=12
>>> if age < 4:
...     price = 0
... elif age < 18:
...     price = 5
... else:
...     price = 10
... 
>>> price
5
  • 可省略else代碼塊

1.2 使用if判斷列表是否爲空

>>> str = []
>>> if str:
...     a = 1
... else:
...     a = 0
... 
>>> a
0

2. 用戶輸入

2.1 input()的簡單使用

  • >>> message = input("please input your name: ")
    please input your name: Jack
    >>> message
    'Jack'
    >>> message = "please input something.\nName: "
    >>> name = input(message)
    please input something.
    Name: Jack
    >>> name
    'Jack'
  • 使用函數input()時,python將用戶輸入解讀爲字符串。可以使用函數int(),將數字的字符串表示轉換爲數值表示
  • >>> age = input("How old are you? ")
    How old are you? 12
    >>> age
    '12'
    >>> age = int(age)
    >>> age
    12

3. while語句

3.1 使用while循環處理列表和字典

  • for循環能夠遍歷列表,但在for循環中不該修改列表,不然將致使python難以跟蹤其中的元素。要在遍歷列表的同時對其進行修改,可以使用while循環
  • >>> a = ['alice', 'brian', 'candace']
    >>> b = []
    >>> while a:
        name = a.pop(0)
        print(name)
        b.append(name)
    
        
    alice
    brian
    candace
    >>> b
    ['alice', 'brian', 'candace']
  • 利用while和remove()函數來刪除列表中全部包含特定值的元素
  • >>> pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
    >>> while 'cat' in pets:
        pets.remove('cat')
    
        
    >>> pets
    ['dog', 'dog', 'goldfish', 'rabbit']
相關文章
相關標籤/搜索