2014-12-05 113 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

相關問題