Noob Python脚本 - 减少脚本堆

Mic*_*ael -1 python optimization

Python noob在这里,我只是想知道是否有人可以帮助我减少这个脚本.

我试过了:

if letter == 'A' or 'B' or 'C' 但它似乎没有用.

因此,如果字母是A,B或C打印"Hello"
或者如果字母是D,E或F打印再见.

任何帮助都会很棒.

干杯

if letter == 'A':
    print "Hello"
if letter == 'B':
    print "Hello"
if letter == 'C':
    print "Hello"              
if letter == 'D':
    print "GoodBye"
if letter == 'E':
    print "GoodBye"       
if letter == 'F':
    print "GoodBye"
Run Code Online (Sandbox Code Playgroud)

nne*_*neo 5

要减少重复,请使用in:

if letter in ('A', 'B', 'C'):
    print "Hello"
elif letter in ('D', 'E', 'F'):
    print "GoodBye"
Run Code Online (Sandbox Code Playgroud)


Pad*_*ham 5

if letter  in 'ABC': # if letter is in ABC we will print Hello and go no further
    print "Hello"             
elif letter in 'DEF': # if letter is not in ABC we will get here 
    print "GoodBye"
else:  # else it is in neither string 
    print "letter not in any string"
Run Code Online (Sandbox Code Playgroud)

elif's仅在前面的if语句是时才进行评估False,使用in我们可以将每个结果的检查缩短为一个语句,如果我们没有匹配ABCDEF我们将在 中结束else并让用户知道该字母不在ABC或 中DEF

if letter == 'A' or 'B' or 'C' 需要是:

`if letter == 'A' or  letter == 'B' or letter =='C'` 
Run Code Online (Sandbox Code Playgroud)

你的情况if letter == 'A' or 'B' or 'C'会一直True这么信是否ABC与否你会print Hello

你可能想使用if letter.upper()情况下也用户输入ab等。