Home > other >  Python if userinput is less than every int in list print "you've picked the smallest numbe
Python if userinput is less than every int in list print "you've picked the smallest numbe

Time:08-21

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")

CodePudding user response:

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)

CodePudding user response:

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.

  • Related