Home > Enterprise >  How to make it so if any variable in a list is greater than an integer, it will print out something,
How to make it so if any variable in a list is greater than an integer, it will print out something,

Time:01-21

one = int(input("Type a number"))
two = int(input("Type a second number"))
three = int(input("Type a third number"))
four = int(input("Type fourth number"))
num = [one,two,three,four]

How do I make it so if any variable in num is greater than or equal to 7, it will print ("yes") and else, it will print ("no")? Also I'm not sure if I made a list correctly.

CodePudding user response:

Good news - that list looks correct!

What you're looking for is two things - a for loop and a conditional.

The for loop will look over each item in the list, and the conditional will check to see if the current number is greater than or equal to 7. If so, it can update some value (here, a boolean that evaluates whether a number was greater than 7) that is checked again later. Here is my solution to your problem!

# Assume all of the stuff from your question goes here.
isGreaterThan = False
for number in num:
    if number >= 7:
        isGreaterThan = True
        break
if isGreaterThan:
    print("Yes!")
else:
    print("No.")

If you don't get what any part of this does, please ask!

CodePudding user response:

You can use a for loop to go through each item in the list to check whether an item is greater or equal to 7. Then use Booleans to print out the proper output

isGreaterThan = False
for i in num:
     if i >= 7:
        isGreaterThan = True
        break
    
if isGreaterThan:
    print("Yes")
else:
    print("No")

CodePudding user response:

If you use the max() function, you don't need to use any for loops.

num = [1, 9, 2, 6, 10]

if max(num) >= 7:
    print("Yes")
else:
    print("No")

CodePudding user response:

for n in num: # loop through all the elements in the list
if(n > 7): # each element is in the "n" variable - cehck if n>7
    print("yes") # if yes, then pront it
    break # break the loop and stop looking

CodePudding user response:

    one = int(input("Type a number"))
two = int(input("Type a second number"))
three = int(input("Type a third number"))
four = int(input("Type fourth number"))
num = [one,two,three,four]
x= 1
for i in num:
    if i>x:
        print(f"your  {i}th number is grater than {i} ")
    else:
        pass
    x = x  1

CodePudding user response:

Here's the shorthand way:

num = [1, 9, 2]

print("Yes" if any(n >= 7 for n in num) else "No")

Alternatively, using the builtin max as suggested by another answer:

print("Yes" if max(num) >= 7 else "No")

For a quick test, I'd encourage you to lower the 2nd element in the list, and check how the output changes.

  •  Tags:  
  • Related