Python-布尔交叉检查

时间:2016-09-29 15:30:59

标签: python boolean

我有一个关于在这个问题上使用ONLY布尔语句的作业:“我今天可以注册吗?学生可以在周一注册,如果是高级,周二注册少年,周三注册大二,周四注册大一新生。”

是否有一种简单的方法可以在不使用if / else语句的情况下交叉检查每一天和状态以查看它们是True还是False?如果是这样,代码将如何显示?

2 个答案:

答案 0 :(得分:1)

这是使用Python字典和布尔比较的解决方案。

我们使用字典创建学生状态星期几关联。 然后获取用户输入并使用布尔表达式进行比较。

from datetime import date
import calendar

my_dict = {'Senior' : 'Monday',
           'Junior' : 'Tuesday',
           'Sophomore' : 'Wednesday',
           'Freshman' : 'Thursday'
           }


my_date = date.today()

my_status = (raw_input("Enter your enrollment status: ")) #Student current status

today = calendar.day_name[my_date.weekday()]  #Day or week

reg_status = today == my_dict[my_status]   

#who can register today
who_can_register = my_dict.keys()[my_dict.values().index(today)] 

print "Can you register=", reg_status 
print "Today is  ", today , " Only ", who_can_register, "can register"

输出:

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
Enter your enrollment status: Senior
Can you register= False
Today is   Thursday  Only  Freshman can register
>>> ================================ RESTART ================================
>>> 
Enter your enrollment status: Junior
Can you register= False
Today is   Thursday  Only  Freshman can register
>>> ================================ RESTART ================================
>>> 
Enter your enrollment status: Sophomore
Can you register= False
Today is   Thursday  Only  Freshman can register
>>> ================================ RESTART ================================
>>> 
Enter your enrollment status: Freshman
Can you register= True
Today is   Thursday  Only  Freshman can register
>>>

答案 1 :(得分:0)

也许是这样的事情?

from datetime import datetime

def options():
  print """
Are you a? [Enter 0-4]
0) Senior
1) Junior
2) Sophomore
3) Freshman
4) quit
"""


print "Can I register today?"
while True:
  options()
  selection = raw_input("Enter status: ")
  try:
    selection = int(selection)
  except ValueError:
    print "Invalid entry please try again"
    continue
  # if you can't use any if statements
  # replace the if statement with a print statement saying to exit using control c
  # or above the while loop, create the variable selection = None
  # change the while loop from a while True to while selection != 4:
  # I leave it up to you :-)
  if selection == 4:
    break
  # 0 is monday
  weekday = datetime.today().weekday()
  print
  print "reply: {0}".format(selection == weekday)