2014-12-05 88 views
-2

这里是我的代码在用python运行之后访问其他函数?

# 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

您的print_usernameprint_factorial函数只有印刷menu()返回值。他们对此没有做任何事情。在顶层while循环你永远只能再次拨打menu()如果现有choice既不是1也不是2,但你的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_username()print_factorial()功能删除print menu()线。

上面的循环是无止境的(while True:),但如果menu()返回以外的任何其他12那么break声明将达到并退出循环。那时你的程序也结束了。

+0

太棒了,我现在正在工作。谢谢您的帮助。 :) – location201 2014-12-05 11:10:17

相关问题