python入門-WHILE迴圈

來源:互聯網
上載者:User

標籤:選擇   als   print   ase   nis   tin   nconf   number   response   

1 使用while迴圈

current_number= 1while current_number <= 5:    print(current_number)    current_number += 1

 

2 讓使用者選擇退出

prompt = "tell me somthing, and i will repeat it back to you"prompt = "\nEnter ‘quit‘ to end the program"message = ""while message != ‘quit‘:    message=input(prompt)    if message!=‘quit‘:        print(message)

 

3 使用標誌

prompt = "tell me somthing, and i will repeat it back to you"prompt = "\nEnter ‘quit‘ to end the program"active = Truewhile active:    message = input(prompt)    if message == ‘quit‘:        active = False    else:        print(message)

 

4 使用break退出迴圈

prompt = "\nPlease enter the name of a city you have visited:"prompt += "\n(enter ‘quit‘ when you are finished.)"while True:    city = input(prompt)    if city == ‘quit‘:        break    else:        print("I‘d love to go to" + city.title() + "!")

 

5 在迴圈中使用continue

current_number = 0while current_number < 10:    current_number += 1    if current_number % 2 ==0:        continue    print(current_number)

 

6 使用while迴圈來處理列表和字典

unconfirmed_users = [‘alice‘,‘brian‘,‘candace‘]confirmed_users = []while unconfirmed_users:    current_user = unconfirmed_users.pop()    print("verifying user:" + current_user.title())    confirmed_users.append(current_user)print("\n the following users have been confirmed:")for confirmed_user in confirmed_users:    print(confirmed_user.title())

 

7 刪除特定的列表元素

pets = [‘dog‘,‘cat‘,‘dog‘,‘goldfish‘,‘cat‘,‘rabbit‘,‘cat‘]print(pets)while ‘cat‘ in pets:    pets.remove(‘cat‘)print(pets)

 

8使用使用者輸入來填充字典

responses = {}polling_active = Truewhile polling_active:    name = input("\n what is your name?")    response = input("which mountain would you like to climb someday")    responses[name] = response    repeat = input("would you like to let another person respond?(yes or no")    if repeat == ‘no‘:        polling_active = Falseprint("\n --poll results--")for name,response in responses.items():    print(name + "would like to climb" + response + ".")

 

python入門-WHILE迴圈

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.