这是我的代码
# Start of functions
# The menu is called exclusively from the main program code
def menu():
print "Please choose an option."
print "1 = User name"
print "2 = Factorial"
print "3 = Quit"
choice=int(raw_input(":"))
# Stars to validate options
while choice <1 or choice >3 :
print "Invalid menu choice"
print "Please choose an option."
print "1 = User name"
print "2 = Factorial"
print "3 = Quit"
choice=int(raw_input(":"))
else:
return choice
def get_initial(name):
# Will remove all letters after the first one in name to get initial
name=name[:1]
return name
def get_last_name(name):
# -1 counts backwards from the end of string and splits off first word
name = str(name.split()[-1])
return name
# Function will produce and give username based off of the full name that was input
def print_username():
full_name = str(raw_input("What is your name?: "))
initial = get_initial(full_name)
last_name = get_last_name(full_name)
username = str(initial) + str(last_name)
# Converts 'username' to lowercase and stores
username = username.lower()
print username
print menu()
# Takes factorial and multiplies it by the number the preceeds it down to 0
def print_factorial():
number = int(raw_input("Enter a number: "))
factorial = 1
counter = number
while counter > 0:
factorial=factorial*counter
print counter,
if counter > 1:
print'*',
counter=counter-1
print '=', factorial
print menu()
# Start of main program
# Result of menu used to create global variable
choice = menu()
while choice != 3:
if choice == 1:
print print_username()
elif choice == 2:
print print_factorial()
else:
choice = menu()
break
我的问题是,一旦我做了阶乘或用户名,我需要它来允许我访问菜单并访问并执行用户名,阶乘或退出功能。但它并没有这样做。
答案 0 :(得分:0)
您的print_username
和print_factorial
功能只能打印 menu()
返回值。他们没有做这些事。在您的顶级while
循环中,如果现有 menu()
既不是1也不是2,而是choice
循环,则只会再次调用while
如果之前选择了3
,则退出。
相反,请每次通过menu
循环调用while
:
# Start of main program
# Result of menu used to create global variable
while True:
choice = menu()
if choice == 1:
print_username()
elif choice == 2:
print_factorial()
else:
break
并从print menu()
和print_username()
函数中移除print_factorial()
行。
以上循环是无穷无尽的(while True:
),但如果menu()
返回1
或2
以外的任何内容,则会发出break
语句,循环退出。此时你的课程也会结束。