2017-02-24 16 views
0

我開始說我非常瞭解代碼的初學者,我正在學習一個在線課程。不幸的是,我遇到了一個我無法找到解決辦法的問題。用戶在while循環中輸入後變量迷路了Python 3x

我想從command.txt文件讀取一行,然後將其分配給一個變量。 (cl1 & cl2)然後,我要求用戶輸入,然後(在一個while循環內),如果用戶輸入與該變量匹配以打開另一個文件並執行操作。如果它不再問這個問題。

這是目前我的代碼:

user1 = open ("holiday.txt", "w") 
user1.write ("Holiday Location: " + holiday_loc + "\n") 
user1.write ("Total Price: £" + str(total_price) + "\n") 
user1.write ("Total People: " + str(total_people) + "\n") 
user1.close() 
print ("Here are a list of commands") 
commands = open ("commands.txt", "r") 
# command_line 1 = show data 
# command_line2 = price PP 
command_line1 = commands.readline() 
command_line2 = commands.readline() 
print (command_line1 + command_line2) 
commands.close() 
cl1 = command_line1 
cl2 = command_line2 
answer = input ("What would you like to do? ") 
while answer != "cl1" or answer != "cl2": 
    print("Im sorry, there is no such command") 
    answer = input("What would you like to do? ") 
else: 
    if answer == cl1: 
     show_data = open ("holiday.txt", "r") 
     line1 = show_data.readline() 
     line2 = show_data.readline() 
     line3 = show_data.readline() 
     print (line1 + "\n" + line2 + "\n" + line3) 
    elif answer == cl2: 
     print (line2/line3) 

所以澄清:

什麼,我想的是:

用戶輸入「顯示數據」或「價格PP」,那麼它應該跳過到:

else: 
     if answer == cl1: 
      show_data = open ("holiday.txt", "r") 
      line1 = show_data.readline() 
      line2 = show_data.readline() 
      line3 = show_data.readline() 
      print (line1 + "\n" + line2 + "\n" + line3) 
     elif answer == cl2: 
      print (line2/line3) 

當前,如果用戶輸入「顯示數據」或「價格pp」它只是運行循環:

What would you like to do? show data Im sorry, there is no such command What would you like to do?

在我看來,這個變量賦值相處可能的方式失去了什麼?或者它與絃樂混在一起。我不確定。

香港專業教育學院嘗試的

while answer != "cl1" or answer != "cl2": while answer != cl1 or answer != cl2: while answer != "cl1" and answer != "cl2": while answer != cl1 and answer != cl2:

所有變化如下:while answer != cl1 and answer != cl2:作品,如果用戶輸入CL1或CL2,但我想它的工作,如果用戶鍵入的命令,而不是變量名稱。

我希望能解釋我的問題。

+0

快速澄清的問題:'line2/line3'的預期結果是什麼?這兩個值是字符串,因此不能分開。 – Neelik

+0

這將是另一個命令,ATM它只是作爲一個命令的例子而已 – Gromit

回答

0

while answer != cl1 and answer != cl2:(無cl1和cl2上的「」)應該工作,除非您的commands.txt文件包含字符串「cl1」和「cl2」。你的commands.txt文件是什麼?

+0

兩個字符串「show data」和「price pp」,如果我在打印cl1和cl2之前詢問用戶的輸入,它會顯示它分配然後糾正,但沒有得到在用戶問題 – Gromit