2016-10-07 12 views
0

プログラミングの新機能。私が乱数を推測していた反復(試行)を数えて印刷する方法は?「3番目の試行から数えたと思います。ループ内の繰り返し回数をカウント

import random 
from time import sleep 
str = ("Guess the number between 1 to 100") 
print(str.center(80)) 
sleep(2) 

number = random.randint(0, 100) 
user_input = [] 

while user_input != number: 
    while True: 
     try: 
      user_input = int(input("\nEnter a number: ")) 
      if user_input > 100: 
       print("You exceeded the input parameter, but anyways,") 
      elif user_input < 0: 
       print("You exceeded the input parameter, but anyways,") 
      break 
     except ValueError: 
      print("Not valid") 
    if number > user_input: 
     print("The number is greater that that you entered ") 
    elif number < user_input: 
     print("The number is smaller than that you entered ") 

else: 
    print("Congratulation. You made it!") 
+0

カウンタを追加するだけです。 while user_input!= number:count + = 1' – AChampion

+0

Thaaaaaaank you !! –

答えて

0

質問が2つあります。まず、反復回数をどのように数えますか?簡単な方法は、whileループが実行されるたびに増分(1ずつ増加)するカウンタ変数を作成することです。次に、その番号をどのように印刷しますか? Pythonには文字列を構築するためのさまざまな方法があります。 1つの簡単な方法は、2つの文字列を単に加算する(すなわちそれらを連結する)ことである。ここで

は例です:

counter = 0 

while your_condition_here: 
    counter += 1 # Same as counter = counter + 1 
    ### Your code here ### 

print('Number of iterations: ' + str(counter)) 

印刷値がwhileループが実行された回数になります。ただし、文字列ではないものは明示的に文字列に変換して連結する必要があります。

書式付き文字列を使用して印刷メッセージを構成することもできます。これにより、明示的に文字列に変換する必要がなくなり、可読性も向上します。

print('The while loop ran {} times'.format(counter)) 

文字列にformat機能を呼び出すと、あなたは引数を指定して文字列内の{}の各インスタンスを置き換えることができます:ここでは一例です。

編集:再割り当てオペレータに変更

関連する問題