2015-04-26 64 views
0

我正在編寫一個腳本,要求用戶輸入兩個數字作爲時間表的最大值,然後使用我已經定義的兩個函數繪製表格。但是,我不知道如何將所有東西結合在一起來完成這個任務。以下是我有:使用已定義函數的腳本

print("What is the maximum value for the first factor?") 
number1 = input() 
print("What is the maximun value for the second factor?") 
number2 = input() 
print("Here is your times table:") 
def times_table(times,factor): 
    """takes two positive integers and returns a list of lists 

    int, int -> list of lists""" 
    table = [[0]*(factor+1)] 
    for i in range(1,times+1): 
     table.append(list(range(0,i*factor+1,i))) 
    return table 


def print_table(listx): 
    """takes a list of lists of numbers and displays them on the screen 

    list of numbers -> numbers""" 
    for x in listx: 
     for y in x: 
      print('{0:<10}'.format(y), end='') 
     print() 

回答

1

有兩件事情是你必須做。首先你必須調用你定義的函數。其次,您將得到一個從輸入函數返回的字符串,您需要將其轉換爲整數才能在代碼使用它時使用它。

還有其他一些有用的事情可以做。輸入函數的目的是爲您打印提示,所以不要使用print(後跟input()),只需使用帶有參數的輸入。然後,如果先定義所有函數,然後再執行代碼,則它更容易閱讀。您可以擁有將直接分散在整個代碼中的語句,但這使得難以遵循。

def times_table(times,factor): 
    """takes two positive integers and returns a list of lists 

    int, int -> list of lists""" 
    table = [[0]*(factor+1)] 
    for i in range(1,times+1): 
     table.append(list(range(0,i*factor+1,i))) 
    return table 


def print_table(listx): 
    """takes a list of lists of numbers and displays them on the screen 

    list of numbers -> numbers""" 
    for x in listx: 
     for y in x: 
      print('{0:<10}'.format(y), end='') 
     print() 

number1 = int(input("What is the maximum value for the first factor?")) 
number2 = int(input("What is the maximun value for the second factor?")) 
print("Here is your times table:") 
table = times_table(number1, number2) 
print_table(table) 
0

假設number1number2將提供作爲參數times_table(),你只是缺少兩個函數調用:

# Calls times_table function providing number1 and number2 as arguments 
# And assigns the returned variable to my_list 
my_list = times_table(number1,number2) 
# Call print_table function providing the list created in times_table function 
print_table(my_list) 
+0

這是否在腳本的末尾? – holaprofesor

+0

是的,在函數定義之後 – ODiogoSilva

相關問題