我是Python的新手。我刚刚学习了if语句和for循环。实际上,在Python控制台中,我试图提出一个项目/任务,但它并不像我一样工作。这是代码:
./*
我得到的是:
PrimList = {"Monday":1, "Tuesday":2, "Wednesday":3, "Thursday":4, "Friday":5}
appt_ = input("Choose an appt date. For Monday enter 1, for Tuesday enter 3. For Wednesday enter 4. For Thursday enter 5, For Friday enter 6")
Choose an appt date. For Monday enter 1, for Tuesday enter 3. For Wednesday enter 4. For Thursday enter 5, For Friday enter 6>? 1
#as user input I entered 1, indicating Monday was the option.
if (appt_ == 1):
PrimList("Monday")
elif (appt_ == 2):
PrimList("Tuesday")
elif (appt_ == 3):
PrimList("Wednesday")
elif (appt_ == 4):
PrimList("Thursday")
elif (appt_ == 5):
PrimsList("Friday")
else:
print("That is not a valid entry.")
我可能将错误的值设置为Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'appts_' is not defined
,使用字典错误。有人可以帮忙吗?
答案 0 :(得分:0)
这可能是您正在查看的内容,您还必须确保将输入类型转换为整数,以便用户无需输入字符串(即"1"
)
PrimList = {1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday"}
appt_ = int(input("Choose an appt date. For Monday enter 1, for Tuesday enter 3. For Wednesday enter 4. For Thursday enter 5, For Friday enter 6"))
#Choose an appt date. For Monday enter 1, for Tuesday enter 3.
#For Wednesday enter 4. For Thursday enter 5, For Friday enter 6>? 1
#as user input I entered 1, indicating Monday was the option.
if appt_ in PrimList:
print(PrimList[appt_])
else:
print("That is not a valid entry.")
答案 1 :(得分:0)
# I have modified your code little bit.
PrimList = {"Monday":1, "Tuesday":2, "Wednesday":3, "Thursday":4, "Friday":5}
# '\n' will add new lines
print("Choose an appt date.\nFor Monday enter 1\nFor Tuesday enter 3\nFor Wednesday enter 4\nFor Thursday enter5\nFor Friday enter 6")
# input reads everything as string. so you need to convert it to int other wise
# your if comparison wont work. >> you are comparing string to int << it wont work as You
# expected.
appt_ = int( input('Your Choice:') )
# dictionary items are accessed by [] bracket not ()
if appt_ == 1:
print( PrimList["Monday"])
elif appt_ == 2:
print(PrimList["Tuesday"])
elif appt_ == 3:
print(PrimList["Wednesday"] )
elif appt_ == 4:
print(PrimList["Thursday"] )
elif appt_ == 5:
print( PrimsList["Friday"] )
else:
rint("That is not a valid entry.")
**OUTPUT**
Choose an appt date.
For Monday enter 1
For Tuesday enter 3
For Wednesday enter 4
For Thursday enter5
For Friday enter 6
Your Choice: 1
1