How to print the string or value held as True

人走茶凉 提交于 2019-12-25 00:45:31

问题


Say, I have a function in Python where

if (age<20):
    young=True
if (age>80):
    old=True

My question is, if I want to call or print the values which are held as True. I want to write this line: The person wasn't selected for the job because he was old/young etc. One person could also violate many criteria. How would I do that?


回答1:


To be sure: you want to print something if old or height is True.

   # This is needed if you want to check if old = false or true
   old = False
   height = False

Your begin is correct.

   if age>20: 
      old=True
   if height>90:
      tall=True

After this, you want to check if old or height is True, so

   if old:
       print("<Here your output>")
   if height:
       print("<Here your output>")

You can also combine height and old with and, or, not.

However, if you want to print "you're too old", you can also use

   if age>20: 
      print("<text>")
   if height>90:
      print("<text>")



回答2:


Use a dictionary or a custom class. For an isolated call, a dictionary works fine. Here's an example where we initialize values for pre-specified keys as False:

# some arbitrary inputs
age, height = 25, 80

# create dictionary with "old" & "tall" keys with values to set to False
flags = dict.fromkeys(('old', 'tall'), False)

# set dictionary values to True conditionally
if age > 20:
    flags['old'] = True
if height > 90:
    flags['tall'] = True

# use list comprehension to iterate dictionary key-value pairs and 
# return list of keys where value is True
true_keys = [k for k, v in flags.items() if v]

print(true_keys)

['old']



回答3:


In addition to jpp great answer, you can replace if statements like this:

age, height = 25, 80

flags = dict.fromkeys(('old', 'tall'), False)

flags['old'] = age > 20
flags['tall'] = height > 90

true_keys = [k for k, v in flags.items() if v]

print(true_keys)


来源:https://stackoverflow.com/questions/53154850/how-to-print-the-string-or-value-held-as-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!