Variable not being updated after while loop iterations

Viewed 46

This program is supposed to compare the user's input to the randomly created integer stored in the 'n' variable. Also, once achieved, it should return the number of attempts taken by the user. For some reason, the 'attempts' variable is not being increased after each iteration. I suppose this problem is related to the position of my while loop.

import random
import time
import sys

def number_guess():
  n = random.randint(1,75)
  attempts = 0

  print(n)
  guess = int(input('Enter an integer from 1 to 75: '))
  
  if guess == n:
    print ('You Guessed It!')
    print ('You guessed the correct number in %s attempts!!!' % (attempts)) #This line always shows '0 attempts'
    time.sleep(5)
    sys.exit()
  else:
    while guess != n:
      if guess < 1 or guess > 75:
        print ('Remember, the integer should be from 1 to 75')
        attempts += 1
        number_guess()
      else:
        print ('You Missed It')
        attempts += 1
        number_guess()

number_guess()

As you can see, I'm quite new to programming. Any corrections will be greatly appreciated. Thanks!

2 Answers

What the issue is every time you guessed it wrong you were re-calling number_guess which in turn reset attempts. So what you do to get around that is when you call it again is you send it the attempt number your on. And if you do not put in a number it will default to 0.

import random
import time
import sys

def number_guess(attempts=0):
  n = random.randint(1,75)

  print(n)
  guess = int(input('Enter an integer from 1 to 75: '))
  
  if guess == n:
    print ('You Guessed It!')
    print ('You guessed the correct number in %s attempts!!!' % (attempts)) #This line always shows '0 attempts'
    time.sleep(5)
    sys.exit()
  else:
    while guess != n:
      if guess < 1 or guess > 75:
        print ('Remember, the integer should be from 1 to 75')
        attempts += 1
        number_guess(attempts)
      else:
        print ('You Missed It')
        attempts += 1
        number_guess(attempts)

number_guess()

You don't need to keep calling number_guess() inside of itself (recursion). I moved your while loop to avoid this. Here's a better approach:

import random
import time
import sys

def number_guess():
  n = random.randint(1,75)
  attempts = 0
  guess = 0 # can be any number other than a valid guess number

  print(n)

  while guess != n:
    guess = int(input('Enter an integer from 1 to 75: '))
    
    if guess == n:
      attempts += 1 # added this to add an attempt for correct answers too
      print ('You Guessed It!')
      print ('You guessed the correct number in %s attempts!!!' % (attempts)) #This line always shows '0 attempts'
      time.sleep(5)
      sys.exit()
    else:
      if guess < 1 or guess > 75:
        print ('Remember, the integer should be from 1 to 75')
        attempts += 1
      else:
        print ('You Missed It')
        attempts += 1

number_guess()
Related