为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

qq_花开花谢_0 2022-05-24 10:38:38
我正在尝试打印您有资格获得的东西,如果您没有资格获得其中任何一项,我正在尝试打印您没有资格获得其中任何一项。但是使用此代码,它总是将 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 <= 7solder = gender == 'f' and age >= 20 and age <= 30 and repute <= 7 and children == 0sargent = 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')
查看完整描述

3 回答

?
暮色呼如

TA贡献1853条经验 获得超9个赞

使用最终if条件来检查是否没有任何条件匹配,而不是else:


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')

if not (member or solder or sargent or captain or commander or president): 

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

编辑:修改为打印所有符合条件的职位。


查看完整回答
反对 回复 2022-05-24
?
互换的青春

TA贡献1797条经验 获得超6个赞

你可以替换


else: 

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


if all([not cond for cond in [member, soldier, sargent, captain, commander, president]]):

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

甚至按照评论的建议,使用生成器表达式,以获得理论上更好的性能


if all(not cond for cond in [member, soldier, sargent, captain, commander, president]):

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


查看完整回答
反对 回复 2022-05-24
?
aluckdog

TA贡献1847条经验 获得超7个赞

只是多了一个选项,因此,如果您必须添加更多可能性,您只需将它们插入中间,而不必更改任何其他语句。


msg = []

if member:

  msg.append('Member')

if solder:

  msg.append('Soldier')

..

..

if new_possibility:

   msg.append('blah')


if msg:

   print print '\n'.join(msg)

else:

   print 'Not elligible'


查看完整回答
反对 回复 2022-05-24
  • 3 回答
  • 0 关注
  • 149 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信