2017-12-12 5 views
0

ランダムに数値を選択するプログラムを作成しようとしていますが、その数値が正しい値になるまで推測する必要があります。これまでのところ、私は1つの時間を推測できるように動作し、その後プログラムは終了します。正しい数字が推測されるまで入力を繰り返す必要があります。正しいランダム値が選択されるまでループを繰り返す

import random 
a = random.randint(1,20) 
print("My number is somewhere between one and twenty") 
b = int(input("What is your guess?: ")) 
if b == a: 
    print("You guessed my number!") 
elif b > a: 
    print("You're number is too large") 
elif b < a: 
    print("You're number is too small")  

input("\n\nPress the enter key to exit") 
+1

を働いています。 [here](https://wiki.python.org/moin/WhileLoop)を参照してください。 –

+0

チュートリアルはあなたの友人です:https://www.tutorialspoint.com/python3/python_loops.htm – MrT

答えて

1

特定の条件が満たされるまで実行されるwhileループがありません。あなたのケースでは、コードは次のようになります:

import random 
a = random.randint(1,20) 
print("My number is somewhere between one and twenty") 
b = 0 # We create the variable b 
while b != a: # This executes while b is not a 
    b = int(input("What is your guess?: ")) 
    if b > a: 
     print("Your number is too large") 
    elif b < a: 
     print("Your number is too small")  
print("You guessed my number!") # At this point, we know b is equal to a 

input("\n\nPress the enter key to exit") 
0

それは `while`ループを使用し

import random 
a = random.randint(1,20) 
print("My number is somewhere between one and twenty") 
while True: #missing the while loop 
    b = int(input("What is your guess?: ")) 
    if b == a: 
     print("You guessed my number!") 
     exit() 
    elif b > a: 
     print("You're number is too large") 
    elif b < a: 
     print("You're number is too small") 
+0

'exit()'はループを壊すだけでなく、プログラムを停止させることに注意してください。また、ドキュメントによれば、それは "インタラクティブなインタープリタシェルにとって有益であり、プログラムで使われるべきではありません"。 https://docs.python.org/3/library/constants.html#exitから –

関連する問題