[英]Why does function keep repeating text after I end while loop and exit?
要重現該問題,請在repl.it中運行它,並在出現提示時輸入“ cNOT”(不帶引號)。 此后,它應該詢問您想要第二個qubit的門,取而代之的是,它再次詢問您給“ cNOT”作為答案的相同問題。
import numpy as np
def target(qstat):
typegat2 = input("Which gate is this target qubit for? See list of two qubit gates at the top.")
if typegat2 == "cNOT":
carray = np.array([[0,1],[1,0]])
if np.array_equal(mem1, [0,1]) == True:
return qstat
elif np.array_equal(mem1, [1,0]) == True:
return np.dot(qstat,carray)
else:
print("superposition...not implemented")
return qstat
else:
print("other gates not yet implemented")
return qstat
qubits = 2
qstat = {1:[0,1],2:[0,1]}
done = "n"
singates = {"target":target}
x=1
while x <= qubits:
while done == "n":
print("this is qubit #",x)
fstgat = "target"
print("first gate is target")
if fstgat in singates:
#checks if there is an error from mem1 being undefined (control/target out of order)
while True:
try:
qstat[x]=singates[fstgat](qstat[x])
break
except NameError:
print("switching qubits - we'll come back to this one")
#error here -> keeps saying "which gate is this target qubit for"
done = "y"
done = input("Done with your qubit? y or n: ")
else:
print("sorry, that functionality is not yet implemented, try custom gate")
done ="y"
x+=1
done = "n"
print("result for qubit",1,qstat[0])
print("result for qubit",2,qstat[1])
減少了代碼的數量,但這只是為了模擬理想的量子計算機。 “ qstat”是每個量子位狀態的字典。 它可能不必一定是字典,但是它在實際程序中的方式很好,因此我保留了它。 無論如何,“ qubits”是系統中的qubit數,通常它可以是用戶輸入的任何整數。 函數“目標”是cNOT門中的目標量子位。 代碼中存在“ try ... except”部分的原因是,有時用戶會在“ control”之前輸入“ target”,並且由於需要檢查控制qubit以確定如何處理目標qubit,所以輸出一個NameError,因此我將其設置為在當前正在編碼的列表中記錄該量子位,以“重新計算”該列表中的每個量子位。
“完成”是一種檢查用戶是否完成了每個量子位的方法,並且由於它處於while循環中,所以我認為在“ except”語句之后將其設置為“ y”將結束while循環並移至下一個量子位,但由於某種原因,它停留在函數內部-一遍又一遍地重復同一行。 如果您想退出該函數,則必須鍵入一些亂碼,因為它對應於最后的else語句,如果typegat2不等於“ cNOT”,它將返回qstat(未更改)並繼續。 因此很明顯,該函數不會由於錯誤或任何原因而返回任何內容。 但是,問題就變成了,如何使它退出功能?
任何幫助,將不勝感激。 我很樂意回答您對代碼有任何疑問; 我試圖盡可能減少它。
擺脫while True:
循環,這將導致代碼在NameError
異常發生時重復執行。
同樣,將done
的輸入移動到try
塊中。 否則,該輸入將覆蓋except
塊中的done = "y"
語句。
while x <= qubits:
while done == "n":
print("this is qubit #",x)
fstgat = "target"
print("first gate is target")
if fstgat in singates:
#checks if there is an error from mem1 being undefined (control/target out of order)
try:
qstat[x]=singates[fstgat](qstat[x])
done = input("Done with your qubit? y or n: ")
except NameError:
print("switching qubits - we'll come back to this one")
#error here -> keeps saying "which gate is this target qubit for"
done = "y"
else:
print("sorry, that functionality is not yet implemented, try custom gate")
done ="y"
x+=1
done = "n"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.