2016-10-07 2 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

'카운터 = 0; while user_input! = number : count + = 1' – AChampion

+0

당신은 Thaaaaaaaank you !! –

답변

0

질문하는 두 가지 질문이 있습니다. 먼저, 반복 횟수를 어떻게 계산합니까? 이를 수행하는 간단한 방법은 while 루프가 실행될 때마다 증가 (1 씩 증가)하는 카운터 변수를 작성하는 것입니다. 둘째, 그 번호를 어떻게 인쇄합니까? 파이썬에는 문자열을 구성하는 여러 가지 방법이 있습니다. 하나의 쉬운 방법은 단순히 두 개의 문자열을 함께 추가하는 것입니다 (예 : 연결).

여기서 예이다 :

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 함수를 호출하는 것은 당신이 인수를 사용하여 문자열 내에서 {}의 각 인스턴스를 대체 할 수 있습니다 예를 들면 다음과 같습니다.

편집 : 재 할당 연산자로 변경