2016-09-27 114 views
-1

我想用這個邏輯編寫一個程序。編寫一個簡單的循環程序

A value is presented of the user. 
Commence a loop 
    Wait for user input 
    If the user enters the displayed value less 13 then 
     Display the value entered by the user and go to top of loop. 
    Otherwise exit the loop 
+0

所以你想要一個程序,讓用戶回答什麼2363或'a'減去'b'總是13?如果這是錯誤的答案,它會不斷詢問用戶,直到它是正確的。如果它是正確的,它會更新爲「a-13」?那麼'2363 -13 = 2350'然後下一個循環會詢問'2350 -13'是什麼? – MooingRawr

回答

0

你只需要兩個while循環。一個讓主程序永遠持續下去,另一個一旦回答錯誤就打破並重置a的值。

while True: 
    a = 2363 
    not_wrong = True 

    while not_wrong: 
     their_response = int(raw_input("What is the value of {} - 13?".format(a))) 
     if their_response == (a - 13): 
      a = a -13 
     else: 
      not_wrong = False 
0

雖然你應該表現出你在向解決方案和張貼編碼,當你遇到問題的嘗試,你可以這樣做以下:

a = 2363 
b = 13 
while True: 
    try: 
     c = int(input('Subtract {0} from {1}: '.format(b, a)) 
    except ValueError: 
     print('Please enter an integer.') 
     continue 

    if a-b == c: 
     a = a-b 
    else: 
     print('Incorrect. Restarting...') 
     a = 2363 
     # break 

(使用raw_input代替input如果您使用的是Python2)

這會創建一個無限循環,它會嘗試將輸入轉換爲整數(或打印聲明正確輸入類型的語句),然後使用邏輯來檢查a-b == c。如果是這樣,我們將a的值設置爲這個新值a-b。否則,我們重新啓動循環。如果你不想要無限循環,你可以取消註釋break命令。

0

您的邏輯是正確的,可能要查看while loopinput。 while循環一直持續,直到滿足條件:while循環

while (condition): 
    # will keep doing something here until condition is met 

實施例:

x = 10 
while x >= 0: 
    x -= 1 
    print(x) 

這將打印X,直到達到0所以輸出將是9 8 7 6 5 4 3 2在控制檯上的新行中爲1 0。

input允許用戶從控制檯輸入的東西:

x = input("Enter your answer: ") 

這將提示用戶「輸入您的答案:」和存儲什麼都值用戶進入變量x。 (變量含義如容器或箱)

把它放在一起,你會得到這樣的:

a = 2363    #change to what you want to start with 
b = 13    #change to minus from a 

while a-b > 0:  #keeps going until if a-b is a negative number 
    print("%d - %d = ?" %(a, b))      #asks the question 
    user_input = int(input("Enter your answer: ")) #gets a user input and change it from string type to int type so we can compare it 
    if (a-b) == user_input:   #compares the answer to our answer 
     print("Correct answer!") 
     a -= b      #changes a to be new value 
    else: 
     print("Wrong answer") 

print("All done!") 

現在這個節目停在a = 7因爲我不知道,如果你想保持與去負數。如果你只是編輯while循環的條件。我相信你可以管理。