![](/img/trans.png)
[英]How can I adjust this Newton-Raphson for loop to include a range of values for my initial guess so that it prints the number of iterations for each?
[英]How do I get this while loop to update my initial input so I can apply the if statements to new values in python
我想每次輸入一個新數字,將 integer 再次與當前變量進行比較,但也保存在原始變量之上,這樣我就可以輸入另一個數字再次進行比較。
我不確定為什么我不能用我輸入的變量更新當前變量。 我將如何實現這一目標。
我當前的代碼是:
print("give the first number: ", end = "")
g = input()
x = int(g)
finished = False
while not finished:
print("enter the next number: ", end = "")
k = input()
h = int(k)
if h == x and h != 0:
print("same")
elif h > x and h != 0:
print("up")
elif h < x and h != 0:
print("Down")
elif h != 0:
h = x
else:
h == 0
finished = True
如果程序正常工作,它將看起來像這樣:
Enter the first number: 9
Enter the next number (0 to finish): 9
Same
Enter the next number (0 to finish): 8
Down
Enter the next number (0 to finish): 5
Down
Enter the next number (0 to finish): 10
Up
Enter the next number (0 to finish): 10
Same
Enter the next number (0 to finish): 0
每個條目都應替換下一個條目將與之進行比較的變量。 任何幫助,將不勝感激。 謝謝!
您必須更新x
變量,而不是h
變量。 另外,我修復了代碼中的其他問題(見評論)
print("give the first number: ", end = "")
g = input()
x = int(g)
finished = False
while not finished:
print("enter the next number: ", end = "")
k = input()
h = int(k)
if h == 0:
# Priority to the finish condition
finished = True
elif h == x:
# No need to check that h != 0 because it's in the elsif
print("same")
elif h > x:
print("up")
elif h < x:
print("Down")
# Update the x variable, regardless of conditions.
x = h
這給出了您期望的 output。
give the first number: 9
enter the next number: 9
same
enter the next number: 8
Down
enter the next number: 5
Down
enter the next number: 10
up
enter the next number: 10
same
enter the next number: 0
您必須在 if 語句之外更新它。 所以而不是這個
elif h != 0:
h = x
您可以像h = x
一樣在循環之外執行此操作,但沒有 if 語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.