Python Forum
1st Project Guess between 1 and 20
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
1st Project Guess between 1 and 20
#1
Hi, first time on python (only dabbled with VBA previously) and I've done the cliche guessing game (sorry!) Taken me a few days.

I've tried to go further and make it a more robust using functions. I'm finding it really hard to get my head around functions and how to use them with arguments. My code is a little as a result of trial-and-error and I don't quite understand why some of it works. If anyone's willing, could I have some feedback on whether the code is 'neat' or unnecessary or if I've committed any python faux pas? Thank you very much. Shy

# Guessing Game

def string_or_integer(guess):
    while True:
        if guess in ('quit', 'Quit'):
            print('Bye bye!')
            sys.exit()
        elif not guess in ('quit', 'Quit'):
            try:
                return int(guess)
            except ValueError:
                try:
                    float(guess)
                    print("Please use whole numbers")
                    guess = input('>>> ')
                except ValueError:
                    print ("This is not a number. Please enter a number between 1 and 20")
                    guess = input('>>> ')

def game():
    guess = input('>>> ')
    guessInt = string_or_integer(guess)
    if (guessInt == rNum):
        print('Congratulations! You won!')
        sys.exit()
    elif (guessInt > 20):
        print('Way too high! Guess between ONE and TWENTY')
        game()
    elif (guessInt < rNum):
        print('Try a higher number')
        game()
    elif (guessInt > rNum):
        print('Try a lower number')
        game()

import random
import sys
rNum = random.randint(1,20)
print('Welcome to the Guessing Game!\nGuess a number between 1 and 20\nTo give up, type "quit"')
game()
Reply


Messages In This Thread
1st Project Guess between 1 and 20 - by MiNigle - May-31-2020, 09:35 AM
RE: 1st Project Guess between 1 and 20 - by GOTO10 - May-31-2020, 03:05 PM
RE: 1st Project Guess between 1 and 20 - by MiNigle - May-31-2020, 06:44 PM
RE: 1st Project Guess between 1 and 20 - by NectDz - May-31-2020, 04:11 PM
RE: 1st Project Guess between 1 and 20 - by GOTO10 - May-31-2020, 04:24 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020