12
\$\begingroup\$

The required output is stated just before the main() function. Is there a better way to achieve it? I feel like I am repeating code unnecessarily but am unable to find a better way to get the result. Not squeezing the code too much, like one liners, but reasonably using better logic.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#Time to play a guessing game.

#Enter a number between 1 and 100: 62
#Too high. Try again: 32
#Too low. Try again: 51
#Too low. Try again: 56

#Congratulations! You got it in 4 guesses.

import random

def main():

    return 0

if __name__ == '__main__':
    main()

print("Time to play a guessing game.")

val = random.randint(1, 100)
guess = 0
count = 1

guess = input("\n\t\tEnter a number between 1 and 100: ")
guess = int(guess)

print("")
print("randint is", val)
print("")

if (guess == val):
    print("\nCongratulations! You got it in", count, "guesses.")

while(guess != val):

    if guess > val:
        print("Too high. Try again:", guess)
        guess = input("\n\t\tEnter a number between 1 and 100: ")
        guess = int(guess)
        count = count + 1
        if guess == val:
            print("\nCongratulations! You got it in", count, "guesses.")
            break

    elif guess < val:
        print("Too low. Try again:", guess)
        guess = input("\n\t\tEnter a number between 1 and 100: ")
        guess = int(guess)
        count = count + 1
        if guess == val:
            print("\nCongratulations! You got it in", count, "guesses.")
            break
    else:
        pass

print("")
\$\endgroup\$
10
\$\begingroup\$
  1. The pythonic way to do count = count + 1 is count += 1
  2. You don't need to repeat the 'guess again' part of the game twice:

    if guess > val:
        print("Too high. Try again:", guess)  
    elif guess < val:
        print("Too low. Try again:", guess)
    guess = int(input("\n\t\tEnter a number between 1 and 100: "))
    count += 1
    if guess == val:
        print("\nCongratulations! You got it in", count, "guesses.")
        break
    
  3. You don't need to add the extra if statement because if guess != val, then the loop with break anyway:

    while guess != val:
        if guess > val:
            print("Too high. Try again:", guess)  
        elif guess < val:
            print("Too low. Try again:", guess)
        guess = int(input("\n\t\tEnter a number between 1 and 100: "))
        count += 1
    print("Congratulations! You got it in", count, "guesses.")
    
  4. I think print("randint is", val) was probably for testing purposes, but it's still in your code!

  5. If you execute your program outside the command module (I'm not quite sure what it's called), the program will close immediately after it's finished; it's always best to give the user the choice of when to quit, so insert this at the end of your code:

    input("Press enter to quit")
    
  6. The first section is unneeded:

    def main():`, `if __name__ == "__main__":
    
  7. The first if statement is also unneeded:

    if guess == val:
    
  8. You don't need to define guess = 0 the first time.

So, all in all, my improvement of your code is:

import random
print("Time to play a guessing game.")
val = random.randint(1, 100)
count = 1    
guess = int(input("\n\t\tEnter a number between 1 and 100: "))
while(guess != val):    
    if guess > val:
        print("Too high. Try again:", guess)    
    elif guess < val:
        print("Too low. Try again:", guess)
    guess = int(input("\n\t\tEnter a number between 1 and 100: "))
    count += 1
print("\nCongratulations! You got it in ", count, " guesses.")
input("Press enter to quit.")
\$\endgroup\$
2
  • \$\begingroup\$ I'd use instead of while guess != val: is elif guess == val then break \$\endgroup\$ – alexyorke Mar 11 '13 at 1:01
  • \$\begingroup\$ One minor thing: while(guess != val): can be changed to while guess != val: \$\endgroup\$ – Elias Zamaria Aug 27 '16 at 6:14
3
\$\begingroup\$

How about this:

import random

def main():
  print('Time to play a guessing game.')

  val = random.randint(1, 100)
  count = 0

  guess = int(input('\n\tEnter a number between 1 and 100: '))
  while True:
    count += 1
    if guess == val:
      print('\nCongratulations! You got it in ', count, 'guesses.')
      break
    elif guess > val:
      msg = 'Too high.'
    else:
      msg = 'Too low.'
    guess = int(input('{}\tTry again: '.format(msg)))
  return 0

main()

Maybe you can draw a flow chart, which can help you get clearer control flow to avoid unnecessary repeating.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.