简体   繁体   中英

Python Flow control and ifs

Q1. I want to modify below code so that the evens list contains only the even numbers of the numbers list. We don't need to print anything.

numbers = [1,2,3,4,5,6,7,8,9]
evens =[]
for number in numbers:
    evens.append(number)

Q2.Add a clause to the if statement such that if the user's input is "q", your program prints "Quit"

numbers = [1,2,3,4,5,6,7,8,9]
evens = []
running = True
while running:
    evens = [n for n in numbers if n%2==0]
    numbers = []
    print("Evens:", evens)
    
    text = raw_input("Add a number (q to quit): ")
    try:
        if text == "q":
            running = False
        else:
            numbers.append(int(text))
     except:
         print("Please input a valid number.")

It might seem long, but I wanted to have the 100% functionality you asked for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM