2017-09-30 27 views
0

有沒有辦法將「if direction == north:」連接到「if direction = south」,而不必複製粘貼代碼兩次並佔用更多行?在Python 3中連接代碼

direction = input('do you want to travel north or south?') 

if direction =='north': 
    print('You chose North') 
    print('An iron gate block your path') 
    print('You need a bronze key to open it') 
    print('You will have to go South') 

if direction == 'south': 
    print('You chose South') 
    time.sleep(1) 
    print('The path leads you to the Deep woods of Mirkwood') 
+0

當方向是北方時比南方時有不同的動作。只有一個共同的聲明,你想要連接它,因爲它?或者你想達到什麼目的? –

+0

我想連接它們,因爲通過重複刪除代碼會更容易 –

+0

如果操作完全不同,則您必須有兩個if語句。 –

回答

0

您可能需要定義「連接」的含義。也許提供一個輸出爲特定路徑提供的例子。

如果你想顯示南方路,他們選擇了北方之後,你可以添加類似:

print('You will have to go South') 
direction = 'south' 

否則,如果你希望用戶選擇北後再次選擇方向,將選擇成爲類似於以下的迴路:

while True: 
    direction = input('do you want to travel north or south?') 

    if direction == 'north': 
     #print statements 
     continue 

    if direction == 'south': 
     #print statements 
     break