[英]How to make it so if any variable in a list is greater than an integer, it will print out something, else it will print out something else?
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")?我该如何做到这一点,如果 num 中的任何变量大于或等于 7,它将打印(“是”),否则,它将打印(“否”)? Also I'm not sure if I made a list correctly.
另外我不确定我是否正确列出了列表。
Good news - that list looks correct!好消息 - 该列表看起来正确!
What you're looking for is two things - a for loop and a conditional.您正在寻找的是两件事 - for 循环和条件。
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. for 循环将查看列表中的每个项目,条件将检查当前数字是否大于或等于 7。如果是,它可以更新一些值(这里是一个 boolean,它评估一个数字是否为大于 7) 稍后再次检查。 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!如果您不明白其中的任何部分的作用,请询问!
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您可以通过列表中的每个项目对 go 使用for 循环来检查项目是否大于或等于 7。然后使用布尔值打印出正确的 output
isGreaterThan = False
for i in num:
if i >= 7:
isGreaterThan = True
break
if isGreaterThan:
print("Yes")
else:
print("No")
If you use the max() function, you don't need to use any for loops.如果使用 max() function,则不需要使用任何 for 循环。
num = [1, 9, 2, 6, 10]
if max(num) >= 7:
print("Yes")
else:
print("No")
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
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
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:或者,使用另一个答案建议的内置
max
:
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.为了快速测试,我建议您降低列表中的第二个元素,并检查 output 的变化情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.