python編程基礎(六):input 輸入 & while 循環處理列表及字典

一、input() 函數

1、input() 基本用法

 input() 函數讓程序暫停運行,等待用戶輸入一些文本。不管輸入的是什麼內容,程序通過 input() 得到的始終是 字符串 類型,使用方法如下:

message = input('Tell me something, and I will repeat it to you:')
print(message)


結果:
Tell me something, and I will repeat it to you:hello everyone
hello everyone

注意:在使用 input()  函數的時候,最終的目的是通過提示讓用戶輸入我們想要的內容,因此,我們需要把要求寫的清楚一點

Tips: 在 input() 的提示末尾加一個空格,將提示與輸入內容分開,讓用戶知道自己的輸入始於何處。

2、input() 多行提示

有時候我們

prompt = "If you tell us who you are, wo can personalize the maeeage you see"
prompt += "\nWhat is your frist name? "  # 用 += 實現連接;在結尾加一個空格

name = input(prompt)
print('\nHello, '+name+"!")


結果:
If you tell us who you are, wo can personalize the maeeage you see
What is your frist name? chen

Hello, chen!

3、獲得數值型的輸入

不管輸入的是啥,最終通過  input()  函數得到的都是字符串類型的變量,加入我們輸入 66,想以數值的方式去使用,那我們應該怎實現?

首先,肯定還是用 input 函數來獲取,得到的是字符串

隨後,我們再用  int()  函數實現強制類型轉換即可得到相應的數值類型

height = input('How tall are you, in inches? ')
height = int(height)

if height >= 36:
    print('\nYou are tall enough to ride!')
else:
    print('\nYou will be able to ride when you are a little older.')


結果:
How tall are you, in inches? 71

You are tall enough to ride!

二、while循環處理列表及字典

1、在列表之間移動元素

假設有個列表包含的新註冊但是沒有通過認證的網站用戶,在驗證完成之後需要把這個用戶移動到其他列表中:

# 首先創建一個待驗證的用戶列表
# 以及一個存儲已驗證用戶的空列表
unconfirmed_users = ['aaa','bbb','ccc']
confirmed_users = []

# 驗證每個用戶,直到遍歷完
while unconfirmed_users:    # 判斷條件直接用列表,當列表變空時,也就是循環條件爲 0
    current_user = unconfirmed_users.pop()
    
    print('Verifying user: '+current_user.title())
    confirmed_users.append(current_user)

print('\nThe follwing users have been confirmed: ')
for confirmed_user in confirmed_users:
    print(confirmed_user.title())   



結果:
Verifying user: Ccc
Verifying user: Bbb
Verifying user: Aaa

The follwing users have been confirmed: 
Ccc
Bbb
Aaa

2、刪除包含特定值的所有列表元素

在之前學習列表的時候 如果不知道元素的位置,只知道元素的值,想要刪除這個元素的時候我們可以使用  remove() 函數來實現

pets = ['dog','cat','dog','glodfish','cat','rabbit','cat']

while 'cat' in pets:
    pets.remove('cat')

print(pets)


結果:
['dog', 'dog', 'glodfish', 'rabbit']

 

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