繁体   English   中英

关于 if-elif 语句格式的快速问题

[英]Quick question regarding format of if-elif statements

如果我想要一组 if elif 语句以单个顺序执行; 例如:

if int(one[1]) == solution:

if int(two[1]) == solution:

执行单个语句:

print "Hello World"

输入这个的最佳格式和语法正确的方法是什么?

我试过了:

if int(two[1]) == solution::
    elif int(one[1]) == solution:
        print "Hello World"

和其他变体,但无法将我的身材放在正确的方式上。 温柔一点 StackOverflow,我编程时间不长。

我正在编程的语言是 Python。 谢谢!

更新:

我认为这是正确的答案,而不是 AND Abdul Kader。 不过还是谢谢你们。 在 Python 我想我会输入:

if (int(one[1]) == solution OR int(two[1])== solution)):
         print "Hello World"

如果要在两个条件都为真时打印它,则必须使用and

if (int(one[1]) == solution) and (int(two[1]) == solution):
    print "Hello, world"

如果您想在一个或多个条件为真时打印它,您必须使用or以相同的方式

if (int(one[1]) == solution) or (int(two[1]) == solution):
    print "Hello, world" 

你不应该使用elif 至少如果我理解你的话。

如果if语句中的条件为假, elif用于测试不同的条件,请考虑这种模式

if spam:
    do_eggs() # We arrive here if spam is true
elif ham:
    do_sausages() # Here if spam was false but ham is true
else:
    print "Camelot!" # And here if both were false

PS:

if spam:
    do_eggs()
elif ham:
    do_eggs()

if spam or ham: do_eggs()确实是一种扭曲的方式,但它确实很丑陋。 你不敢用这个,否则你会被炸成碎片

if int(one[1]) == solution or int(two[1]) == solution:
    print "Hello world"
if (int(one[1]) == solution) and (int(two[1]) == solution):
   print 'Helloworld'

您所需要的只是它们之间的 OR:

if (int(one[1]) == solution) or (int(two[1]) == solution)):
    print "Hello World"

您也可以使用列表来代替“或”,这在有很多选择时很方便。

if solution in [int(one[1]), int(two[1]), int(three[0])]: 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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