如果没有一个if是真的,我如何打印else?

我正在尝试打印您有资格获得的东西,如果您没有资格获得其中任何一项,我正在尝试打印您没有资格获得其中任何一项。但是使用此代码,它总是将 else 与 if 一起打印


PS:我1个月前开始编程。


print('Task 2')

print()

name = str(input('Navn: '))

age = int(input('Age: '))

gender = str(input('Gender (f for female, m for male): '))

children = int(input('How many children: '))

repute = int(input('repute, on a scale from 1(bad) to 9(immaculate): '))

record = str(input('record (done time/convicted/suspect/clean): '))

seniority = int(input('seniority (years): '))

print()

member = gender == 'f' and age >= 20 and repute <= 7

solder = gender == 'f' and age >= 20 and age <= 30 and repute <= 7 and children == 0

sargent = gender == 'f' and age >= 20 and age <= 30 and repute <= 7 and children == 0 and seniority >= 4 and record != 'clean'

captain = gender == 'f' and age >= 20 and age <= 40 and repute <= 7 and seniority >= 6 and record == ('done time' or 'convicted')

commander = gender == 'f' and age >= 20 and age <= 40 and repute <= 3 and seniority >= 6 and record == ('done time' or 'convicted')

president = gender == 'f' and age >= 20 and age <= 40 and repute <= 2 and seniority >= 8 and record == ('done time' or 'convicted') and name != 'kim'

print('You are eligible to become:')

if member == True:

    print('Member')

if solder == True:

    print('Solder')

if sargent == True:

    print('Sargent')

if captain == True:

    print('Captain')

if commander == True:

    print('Commander')

if president == True:

    print('President')

else: 

    print('You are not eligible to be a member')


qq_花开花谢_0
浏览 150回答 3
3回答

暮色呼如

使用最终if条件来检查是否没有任何条件匹配,而不是else:if member == True:&nbsp; &nbsp; print('Member')if solder == True:&nbsp; &nbsp; print('Solder')if sargent == True:&nbsp; &nbsp; print('Sargent')if captain == True:&nbsp; &nbsp; print('Captain')if commander == True:&nbsp; &nbsp; print('Commander')if president == True:&nbsp; &nbsp; print('President')if not (member or solder or sargent or captain or commander or president):&nbsp;&nbsp; &nbsp; print('You are not eligible to be a member')编辑:修改为打印所有符合条件的职位。

互换的青春

你可以替换else:&nbsp;&nbsp; &nbsp; print('You are not eligible to be a member')和if all([not cond for cond in [member, soldier, sargent, captain, commander, president]]):&nbsp; &nbsp; print('You are not eligible to be a member')甚至按照评论的建议,使用生成器表达式,以获得理论上更好的性能if all(not cond for cond in [member, soldier, sargent, captain, commander, president]):&nbsp; &nbsp; print('You are not eligible to be a member')

aluckdog

只是多了一个选项,因此,如果您必须添加更多可能性,您只需将它们插入中间,而不必更改任何其他语句。msg = []if member:&nbsp; msg.append('Member')if solder:&nbsp; msg.append('Soldier')....if new_possibility:&nbsp; &nbsp;msg.append('blah')if msg:&nbsp; &nbsp;print print '\n'.join(msg)else:&nbsp; &nbsp;print 'Not elligible'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python