简体   繁体   中英

Python if userinput is less than every int in list print "you've picked the smallest number"

So I'm trying to create a simple code that requests a user input number, compares it to a existing list of 'ints' and adds all numbers smaller than user input from list a to list b and prints list a. However, I want to make it so that if the user inputs a number smaller than every number in the existing list( in this example only 0), I want to print("you have picked the smallest number).

I got it to run but it gives the string for everytime x is > num. Instead I want it to only print the string once if it sees that x > num every time. How do I go about this. This is the code:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = []

num = input("give a number from 0-100:""")

try:
    num = int(num)
    for x in a:
        if x > num:
            print("you've picked the smallest number")
        elif x < num:
            b.append(x)
            print(b)
except ValueError:
    print("not a number")

You just need to break out of the loop when x > num condition is satisfied:

for x in a:
    if x > num:
        print("you've picked the smallest number")
        break
    elif x < num:
        b.append(x)
        print(b)

that is because the

print("you've picked the smallest number")

inside the for look along with the other condition. Try to take it out of that statement and add it in the end.

(or)

Use the break function to break after the printing statement.

That will give the output you are looking 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