Python'da bir menü yapmak için çalışıyorum:
Python'da yeniyim ve kodda neyi yanlış yaptığımı anlayamıyorum.
Şimdiye kadarki kodum bu:
ans=True
while ans:
print (""""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
"""")
ans=input("What would you like to do?"
if ans=="1":
print("\nStudent Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
elif ans !="":
print("\n Not Valid Choice Try again")
CEVAPLANDI
Görünüşe göre istediği buydu:
menu = {}
menu['1']="Add Student."
menu['2']="Delete Student."
menu['3']="Find Student"
menu['4']="Exit"
while True:
options=menu.keys()
options.sort()
for entry in options:
print entry, menu[entry]
selection=raw_input("Please Select:")
if selection =='1':
print "add"
elif selection == '2':
print "delete"
elif selection == '3':
print "find"
elif selection == '4':
break
else:
print "Unknown Option Selected!"
def my_add_fn():
print "SUM:%s"%sum(map(int,raw_input("Enter 2 numbers seperated by a space").split()))
def my_quit_fn():
raise SystemExit
def invalid():
print "INVALID CHOICE!"
menu = {"1":("Sum",my_add_fn),
"2":("Quit",my_quit_fn)
}
for key in sorted(menu.keys()):
print key+":" + menu[key][0]
ans = raw_input("Make A Choice")
menu.get(ans,[None,invalid])[1]()
Sadece birkaç küçük değişiklik yapılması gerekiyordu:
ans=True
while ans:
print ("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
""")
ans=raw_input("What would you like to do? ")
if ans=="1":
print("\n Student Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
elif ans !="":
print("\n Not Valid Choice Try again")
Dört tırnak işaretini üç olarak değiştirdim (bu çok satırlı tırnak işaretleri için gereken sayıdır), "What would you like to do? "
ifadesinden sonra bir kapama parantezi ekledim ve input ifadesini raw_input olarak değiştirdim.
Bu işe yaramalı. Bir )
eksikti ve sadece """
a ihtiyacınız var, 4 tanesine değil. Ayrıca sonunda bir elif'e de ihtiyacınız yok.
ans=True
while ans:
print("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
""")
ans=raw_input("What would you like to do? ")
if ans=="1":
print("\nStudent Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
ans = None
else:
print("\n Not Valid Choice Try again")