2017-08-16 68 views
0

我想從這個函數date2的追加到如何將變量從另一個功能python3追加

def date_register(): 
    print("Enter date of registration") 
    year = int(input("Enter a year: ")) 
    month = int(input("Enter a month: ")) 
    day = int(input("Enter a day: ")) 
    date1 = datetime.date(year,month,day) 
    date2 = date1 + timedelta(days = 140) 
    print("Check out date:",date2) 

此功能,它出來date2的是沒有定義

def update_A(row): #to update the roomA 
    if len(roomA[row]) < 2: #if roomA is less than 2 
     name = input("Enter your name here: ") 
     print(date_register()) 
     roomA[row].append((name,date2)) 
     print("Your room no. is {} at row {}".format(roomA[row].index((name,date2))+1,row)) 
     print(Continue()) 

尋求幫助,謝謝您

+0

我的朋友,你忘記'返回'函數的結果'date_register'使它在'update_a'中可用。 –

+0

你能否提供解決方案? – Jordan

回答

1

我已經糾正了一個兩個小錯誤。

import datetime 

def date_register(): 
    print("Enter date of registration") 
    year = int(input("Enter a year: ")) 
    month = int(input("Enter a month: ")) 
    day = int(input("Enter a day: ")) 
    date1 = datetime.date(year,month,day) 
    date2 = date1 + datetime.timedelta(days = 140) 
    print("Check out date:",date2) 
    return date2 

def update_A(row): #to update the roomA 
    if len(roomA[row]) < 2: #if roomA is less than 2 
     name = input("Enter your name here: ") 
     checkout_date = date_register() 
     print(checkout_date) 
     roomA[row].append((name,checkout_date)) 
     print("Your room no. is {} at row {}".format(roomA[row].index((name,checkout_date))+1,row)) 

roomA = {1: []} 
update_A(1) 

這是輸出。

Enter your name here: John 
Enter date of registration 
Enter a year: 1954 
Enter a month: 7 
Enter a day: 12 
Check out date: 1954-11-29 
1954-11-29 
Your room no. is 1 at row 1 

顯然你需要弄清楚如何打印結帳日期。

2

date2未定義,因爲它不在update_A的範圍內 有關更多信息,請參閱here範圍信息。

也似乎是混亂和returnprint

update_A,你寫print(date_register())date_register不返回任何內容打印。

print將字符串表示形式發送到控制檯,不能用於分配。而是使用return,它基本上強制函數調用解析爲return語句旁邊的值。 例如:

def foo: 
    return "bar" 
print(foo()) 

foo時被調用時,它將解析爲"bar",然後將其輸出到控制檯。更多關於的print()return的區別和用法見here

update_A使用date2你應該回到它,如下分配給它:

def date_register(): 
    print("Enter date of registration") 
    year = int(input("Enter a year: ")) 
    month = int(input("Enter a month: ")) 
    day = int(input("Enter a day: ")) 
    date1 = datetime.date(year,month,day) 
    date2 = date1 + timedelta(days = 140) 
    print("Check out date:",date2) 
    return date2 
def update_A(row): #to update the roomA 
    if len(roomA[row]) < 2: #if roomA is less than 2 
     name = input("Enter your name here: ") 
     date2 = date_register() #assign date2 returned value 
     print(date2) 
     roomA[row].append((name,date2)) 
     print("Your room no. is {} at row {}".format(roomA[row].index((name,date2))+1,row)) 
     print(Continue()) 
相關問題