我正在尝试创建一个功能,其中用户给出1-7的数字,该数字对应于一周中的一天,否则会有一条消息说:'抱歉这不是正确的数字'
我的代码:
def num_day():
user_number = int(input('Please enter a number between 1 & 7: '))
if user_number == 1:
print('The number 1 corresponds to Monday')
if user_number == 2:
print('The number 2 corresponds to Tuesday')
if user_number == 3:
print('The number 3 corresponds to Tuesday')
if user_number == 4:
print('The number 4 corresponds to Tuesday')
if user_number == 5:
print('The number 5 corresponds to Tuesday')
if user_number == 6:
print('The number 6 corresponds to Tuesday')
if user_number == 7:
print('The number 7 corresponds to Tuesday')
else:
print('Sorry, that is not a valid number.')
num_day()
它会使if语句正确,但继续投掷'抱歉,这不是有效数字'
答案 0 :(得分:1)
正如评论中所提到的,这会失败,因为每个if
都是它自己的逻辑语句。您想使用if..elif..else
代替if..if..else
。
if user_number == 1:
print('The number 1 corresponds to Monday')
elif user_number == 2:
print('The number 2 corresponds to Tuesday')
elif user_number == 3:
print('The number 3 corresponds to Tuesday')
elif user_number == 4:
print('The number 4 corresponds to Tuesday')
elif user_number == 5:
print('The number 5 corresponds to Tuesday')
elif user_number == 6:
print('The number 6 corresponds to Tuesday')
elif user_number == 7:
print('The number 7 corresponds to Tuesday')
else:
print('Sorry, that is not a valid number.')
这将它们全部合并为一个逻辑语句,然后else
是所有测试的全能,而不仅仅是最后一个。
也就是说,对于像这样的初学者问题,一些过度工程总是很有趣。对于工作日数据结构,您对Enum
感觉如何?
import enum
class Weekday(enum.Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
def __str__(self):
return self.name.title()
user_number = int(input("Enter a number: "))
try:
weekday = Weekday(user_number)
print(f"The number {user_number} corresponds to {weekday}")
except ValueError:
print("Sorry, that is not a valid number.")
答案 1 :(得分:0)
我做这样的事情:
success.user