Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic logical errors
#1
Hi everybody!

I'm trying to learn python from a book written by Eric Matthes. Right in the introduction he mentions how, as a child, he programmed a number guessing game, which got me thinking - if a kid can do that, surely I can as well!

It turns out that I can, though not without some bumps. The code I've written is as follows:

import random
number = random.randint(0,100);
user = input ("Greetings, new user. To continue, please enter your name: ");
print (f"Hello, {user.title()}. \nI am Guessatron 1.0, Master of Mystery and Enabler of Entertainment.\nI can provide you with endless hours of fun");
play = input ("Would you like to play a game? ");
if play.lower() == "no":
	print (f"Ah, well, that's unfortunate. You probably assume you can find this high quality of entertainment elsewhere. \nYou assume wrong. \nOh well, no second chances. Good bye, {user.title()}!");
	exit();
elif play.lower() == "yes":
	game_on = True
	print ("Excellent choice, let's begin!");		
	guess = input ("I'm thinking of a number between 0 and 100. Try to guess it: ");
	guess = int(guess);
	count = 1;
	win_count = 0;
	if guess == number:
		print ("Wow, nailed it on your first guess, you must be psychic! Congratulations!");
		win_count += 1
		game_on = False
		replay = input ("Would you like to try again? ");
		if replay.lower() == "yes":
			guess = input ("All right, let's go one more time! What's your next guess? ");
			guess = int(guess);
			count +=1;
			game_on = True
		elif replay.lower() == "no":
			print (f"Well, you've already impressed me with your guessing prowess once, {user.title()}! You should always trust your insticts!")
			exit();	
	while game_on == True:			
		while guess > number:
			guess = input ("Not quite, the number I'm thinking is lower. Try again: ");
			guess = int(guess);
			count += 1;
			if guess == number:
				print (f"Congratulations, you got it, {number} is right! It took {count} tries.");
				count = 0;
				win_count += 1;
				game_on = False
				replay = input ("Would you like to try again? ");
				if replay.lower() == "yes":
					number = random.randint(0,100);
					guess = input ("All right, let's go one more time! What's your next guess? ");
					count += 1;
					guess = int(guess);
					game_on = True;
				elif replay.lower() == "no":
					print (f"Well, you've already impressed me with your guessing prowess {win_count} times, {user.title()}! You should always trust your insticts!")
					exit();
		while guess < number:
			guess = input ("No, the number I'm thinking is higher, try again: ");
			guess = int(guess);
			count += 1;
			if guess == number:
				print (f"Congratulations, you got it, {number} is right! It took {count} tries.");
				count = 0;
				win_count +=1;
				game_on = False;
				replay = input ("Would you like to try again? ");
				if replay.lower() == "yes":
					number = random.randint(0,100);
					guess = input ("All right, let's go one more time! What's your next guess? ");
					guess = int(guess);
					game_on = True;
				elif replay.lower() == "no":
					print (f"Well, you've already impressed me with your guessing prowess {count} times, {user.title()}! You should always trust your insticts!")
					exit();
else:
	play = input (f"I don't really understand what you just said, {user.title()}. It was a pretty straightforward question, please provide a straightforward answer: ")					
I have two issues I've been unable to solve:

1. The number of tries the program show is sometimes right and other times wrong. I'm certain it has something to do with where I place the count variable, but having read the code several times, I'm unable to figure out where the problem is.
2. How would I get the program to go back to the start of the main if loop (started on line 6) if the user triggers the else at line 67 by answering anything other than yes or no? I imagine adding a while loop with the play variable being different to yes or no, but I'm not sure exactly how or where I'd go about doing that.
3. Not one of the main two issues, but really, any sort of comment or advice, such as how to make it shorter, neater or more efficient, would be appreciated.

Thanks in advance, and sorry if the questions might have been answered elsewhere not requiring a new thread!

Chris
Reply
#2
you need to separate your code into functions.
Arrange so that sections which are reused are contained in separate functions so that they can be called as required.
Also, add some empyt lines in your code, it helps tremendously in making code readable.
Reply
#3
And, stop putting semicolons at the end of lines. Wrong language - not needed in Python

Logic bug - when it asks if the user wants to play a game you handle the answers yes and no, but nothing else. A lot of people would just want to type the letter Y

Otherwise as Larz60+ says, the code needs to be reorganized. Functions, even if simple, allow you to change things more easily later, maintaining your code.
Reply
#4
You should check into try blocks as well for catching errors.
Here is a basic structure of what you are doing.
It will show a random number. The number the user entered.
Will check that only whole numbers are entered.

It does not ask for name, or keep wins, or do comparisons.
It should give you a start.
I've comments throughout the script what each part is doing.

Hope it will help you get to your goal.

# Do the imports
import random as rnd
import os

# Start a loop
while True:
    # Setup a random number between 1 and 100
    num = rnd.randint(1, 100)
    # Do a try block
    try:
        # Display a message
        print('I am thinking of a number between 1 and 100. What number am I thinking?')
        # Setup our input prompt for whole numbers
        guess = int(input('What number am I thinking?: '))

        # Display random number and our guess
        print(f'Your guess: {guess}')
        print(f'Random Number: {num}')

        # A try block for game continue or not
        try:
            # Print a message
            print('y or yes to play again any other key exits the game')

            #A Ask if the player wants to play again
            ask = input('Would yo like to play again?: ').lower()

            # Check that only text is entered
            if ask.replace('.', '').isdigit():
                print('Please do not enter numbers here')
                continue
            # See if yes or y was entered
            elif ask == 'yes' or ask == 'y':
                continue
            # Else user entered a key other than y or yes exit game
            else:
                print('Thanks for playing!')
                os.sys.exit()
        # Catch any value errors that may have happened
        except ValueError as error:
            print(f'Error! {error}')
    # Display a error if whole numbers are nut entered
    except ValueError as error:
        print(f'Only whole numbers are allowed')
        continue
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with Logical error processing List of strings dmc8300 3 1,084 Nov-27-2022, 04:10 PM
Last Post: Larz60+
  Greedy algorithms on logical problems Opensourcehacker 0 1,538 Nov-22-2020, 05:12 PM
Last Post: Opensourcehacker
  Unable to bit shift and logical OR bytes and ints? MysticLord 7 7,011 Sep-01-2020, 03:31 PM
Last Post: deanhystad
  Python logical operator AND rasec70 4 2,529 May-07-2020, 03:40 PM
Last Post: pyzyx3qwerty
  parsing logical expression with pyparsing palo173 2 5,488 May-13-2019, 09:22 AM
Last Post: palo173

Forum Jump:

User Panel Messages

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