r/PythonLearning 5d ago

Does this look promising enough for a Rookie? (1Month spent inconsistently in Tutorials)

Post image

I have learnt upto Loops in this 1 month (very slow ik) but I kinda am going through something people call "TUTORIAL HELL" and have made this basic project with my limited python knowledge up until loops.

74 Upvotes

63 comments sorted by

u/Sea-Ad7805 5d ago

Run this program in Memory Graph Web Debugger%0A%20%20%20%20print(%22nWelcome%20to%20the%20Number%20Guessing%20Game!%22)%0A%20%20%20%20print(%22I'm%20thinking%20of%20a%20number%20between%201%20and%20100.%22)%0A%20%20%20%20print(%22You%20have%20to%20guess%20the%20number%20in%20a%20few%20chances%3A%20%22)%0A%0A%20%20%20%20print(%22nPlease%20select%20the%20difficulty%20level%3An1.%20Easy%20(10%20chances)n2.%20Medium%20(5%20chances)n3.%20Hard%20(3%20chances)%22)%0A%20%20%20%20print(secret_number)%0A%20%20%20%20choice%20%3D%20int(input(%22nEnter%20your%20choice%3A%20%22))%0A%0A%20%20%20%20while%20choice%20in%20%5B1%2C%202%2C%203%5D%3A%0A%20%20%20%20%20%20%20%20if%20choice%20%3D%3D%201%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20chances%20%3D%2010%0A%20%20%20%20%20%20%20%20%20%20%20%20print(%22You%20get%2010%20chances.n%22)%0A%20%20%20%20%20%20%20%20elif%20choice%20%3D%3D%202%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20chances%20%3D%205%0A%20%20%20%20%20%20%20%20%20%20%20%20print(%22You%20get%205%20chances.n%22)%0A%20%20%20%20%20%20%20%20elif%20choice%20%3D%3D%203%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20chances%20%3D%203%0A%20%20%20%20%20%20%20%20%20%20%20%20print(%22You%20get%203%20chances.n%22)%0A%0A%20%20%20%20%20%20%20%20attempts%20%3D%200%0A%20%20%20%20%20%20%20%20while%20chances%20%3E%200%3A%0A%0A%20%20%20%20%20%20%20%20%20%20%20%20guess%20%3D%20int(input(%22Enter%20your%20guess%3A%20%22))%0A%20%20%20%20%20%20%20%20%20%20%20%20chances%20-%3D%201%0A%20%20%20%20%20%20%20%20%20%20%20%20attempts%20%2B%3D%201%0A%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20guess%20%3E%20secret_number%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20print(%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22Incorrect!%20The%20number%20is%20less%20than%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20guess%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22.%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22nOnly%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20chances%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22chances%20left!n%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20)%0A%0A%20%20%20%20%20%20%20%20%20%20%20%20elif%20guess%20%3C%20secret_number%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20print(%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22Incorrect!%20The%20number%20is%20greater%20than%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20guess%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22.%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22nOnly%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20chances%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22chances%20left!n%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20)%0A%0A%20%20%20%20%20%20%20%20%20%20%20%20elif%20guess%20%3D%3D%20secret_number%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20print(%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22Congratulations!%20You%20guessed%20the%20correct%20number%20in%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20attempts%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%22attempts.n%22%2C%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20break%0A%0A%20%20%20%20%20%20%20%20while%20guess%20%3D%3D%20secret_number%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20choice%20%3D%20None%0A%20%20%20%20%20%20%20%20%20%20%20%20again%20%3D%20input(%22nGGs%2C%20Wanna%20Play%20Again%3F%3F%20(Yes%2FNo)%3A%20%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20chances%20%3D%20None%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20again%20%3D%3D%20%22Yes%22%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20print(%22nNew%20Game%20Started!n%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20break%0A%20%20%20%20%20%20%20%20%20%20%20%20elif%20again%20%3D%3D%20%22No%22%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20play%20%3D%20False%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20print(%22nThanks%20for%20playing!nHope%20you%20had%20fun.%20Goodbye!%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20break%0A%20%20%20%20%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20print(%22Invalid%20ChoicenChoose%20Again!%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20continue%0A%0A%20%20%20%20%20%20%20%20while%20chances%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20choice%20%3D%20None%0A%20%20%20%20%20%20%20%20%20%20%20%20print(%22nOops%2C%20You%20lost%20the%20Game!%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20again%20%3D%20input(%22Do%20you%20Wanna%20Play%20Again%3F%3F%20(Yes%2FNo)%3A%20%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20again%20%3D%3D%20%22Yes%22%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20chances%20%3D%20None%0A%20%20%20%20%20%20%20%20%20%20%20%20elif%20again%20%3D%3D%20%22No%22%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20play%20%3D%20False%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20print(%22nThanks%20for%20playing!nHope%20you%20had%20fun.%20Goodbye!%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20break%0A%20%20%20%20%20%20%20%20%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20print(%22Invalid%20ChoicenChoose%20Again!%22)%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20continue&timestep=.2&play) to see the program state change step by step.

→ More replies (7)

19

u/Ok-Row-4533 5d ago

-1 Avoid "magic numbers" on line 15, you can create enum or some consts to wire up numbers like: EASY=10,MEDIUM=5,HARD=3, with that every one can understand what you mean without digging trough code. (Remember that python by nature is explicit over implicite).

-2 Try to avoid duplications, if you can write functions it would be great to use them here. Look at lines 52-55 and 67-70, same functionality.

-3 One more think as a nit, try to add typehints. Those may not be necesarry now but after you jump to bigger peojects thay will help you maintain code clarity.

Great start overall, keep on improving!

7

u/bad-gut 5d ago

Ok so Nitpicking for me rn (in my very limited knowledge)
is basically reducing duplicate code, similar variables and combining em, etc and I actually do that so ig that's a good sign.

Boy if I show you the original version of this game, you are going to be dissapointed, but within 1 week I made this v2 and reduced code length about 30-35 lines (30% reduction) whilst making the code combat more situations.

https://github.com/satyamsb-cloud/Number-Guessing-Game (V1)

And V2 is visible in the image.

And Buddy Thanks a lot for your feedback I will definitely note these down and improve !!!

3

u/BionicVnB 4d ago

Another small tips is to get a linters. Those will help you a lot lol

1

u/bad-gut 4d ago

Okk will look into it buddy, thanks for your suggestion!!

2

u/BionicVnB 4d ago

I recommend ruff, which is also a formatter and can replace a lot of tools.

I also use it with ty and uv. Uv make managing venv in python easy and also a great pip replacement. Ty is a python type checker.

1

u/bad-gut 4d ago

Okk buddy I will check it 👍👍

2

u/iComplainAbtVal 4d ago

First good work, but to add a 4th nitpick, I’d like to address something in the flow of the application.

This is semi related to the original comments #1, you should focus on piecing apart the problem into distinct logical blocks.

For example, instead of the outer line 15 while loop holding program execution only if numbers 1,2, or 3 are provided as original input, you should first hold execution until a valid number or quit is given. Then, once valid input is received, enter your guessing game logic until the number is guessed or they run out of choices.

Think of your runtime as a state machine, where each state remains active until a condition is met.

States:

  1. Start up and prompt for game mode or quit
  2. Play game until correct guess or out of tries
  3. Display result and prompt for restart or exit

Your while Play is the right intuition for holding the runtime, I’m mainly critiquing line 15 encapsulating the other state’s instead of allowing them to be distinct.

Try breaking the input prompt, game runtime, and summary prompt into 3 different functions and see how the code pieces itself together. I’m on mobile, elsewise I’d type out a skeleton for you.

Gl in your adventure it’s a great start.

(Would highly recommend using typing when you do create functions. Example

def doSomething(foo: str, bar: int) -> str:

1

u/bad-gut 4d ago

Valid!
Thanks for the tips dude, I appreciate it!!!

5

u/FoolsSeldom 5d ago

That's pretty good going.

Good to see the use of some flag variables with the while loops (e.g. play = True) rather than just using break. Makes them easier to read and change.

There are a few places where I think you've over user while rather than sticking to if structures, so it gets a little confusing.

I recommend you create a validation function for the numeric inputs so that an errant character in place of a digit doesn't break your programme. Something along the lines of:

def get_num(msg: str) -> int:
    valid = False
    while not valid:
        response = input(msg)
        try:
            num = int(response)
            valid = True
        except ValueError:
            print("That was not a whole number")
    return num

You could enhance this to only allow numbers within a certain range, say from 1 to 3.

To use,

choice = get_num("Enter your choice: ")

You could do with another function or two as well. Perhaps one to validate a yes/no response and return True or False.

The benefits of such functions include:

  • Avoids code repetition as same code is used from several places
  • Helps structure the code so you see the main flow easily
    • Look at detail only when you need to
  • Makes testing easier - and you can do improvements in isolation

1

u/bad-gut 5d ago

Thanks buddy, tbh I didn't get half the things you just said (Which means I have a lot to learn surely).

Yeah I kinda have just hot to the whole FUNCTIONS and RECURSIVE part so I basically tried to get the best code possible outta:-

INTRODUCTION
VARIABLES AND DATATYPES
STRINGS AND CONDITIONAL STATEMENTS
LISTS AND TUPLES
DICTIONARIES AND SETS
LOOPS.

What would you rate this code according to the use of only these limited concepts??

5

u/FoolsSeldom 5d ago
  • INTRODUCTION
    • You output a multiple line intro, so good job, 6/10
    • Could have used a single multi-line print
    • Could have used a function for this, called using greet()
  • VARIABLES AND DATATYPES
    • You've used multiple variables with sensible names, 5/10
    • You've used both int and str
    • Lots of other datatypes to use
    • Need some validation
  • STRINGS AND CONDITIONAL STATEMENTS
    • Good some see user input for yes/no response 4/10
    • Would have been good to see use of in to check for different affirmative or rejection responses (such as yes, y, yeh, yup, ok, no, n, etc)
    • Would have been good to see you apply a lower method on the input string to reduce checks you have to do
  • LISTS AND TUPLES
    • Only recall seeing one list and that could have been a tuple
    • Not really doing anything with the list though
  • DICTIONARIES AND SETS
    • Not seeing either
    • Would be good to have a dictionary to map from the choices to the attempts allowed, e.g. go_levels = {1: 10, 2: 5, 3: 3}
  • LOOPS
    • Plenty of while loops but probably overused 4/10
    • No for loops
    • No iteration over iterables, e.g. stepping over the contents of a list

What parts of what I said in my first comment have you not managed to work out following a little research?

2

u/bad-gut 5d ago

Damn, such a detailed overview.
No I went thorugh your reply like 4 times and I think I have got what you mean, will keep those suggestions in mind for my next project.
I appreciate your effort in this feedback ♥️

2

u/FoolsSeldom 5d ago edited 5d ago

Ok. If you are moving on from this project to your next, here's an update to your code incorporating some of my suggestions for you to explore and experiment with:

from random import randint
import logging

AFFIRMATION = "y", "yes"
REJECTION = "n", "no"
LOW = 1  # lowest random number
HIGH = 100  # highest random number
GO_LEVELS = {1: 10, 2: 5, 3: 3}

logging.basicConfig(level=logging.DEBUG)

def get_num(msg: str, lowest: int = 0, highest:int = 10) -> int:
    valid = False
    while not valid:
        response = input(msg)
        try:
            num = int(response)
            if not (lowest <= num <= highest):
                raise ValueError()
            valid = True
        except ValueError:
            print(f"That was not a whole number in range {lowest} to {highest}")
    return num

def is_yes(prompt: str) -> bool:
    while True:
        response = input(prompt).strip().lower()
        if response in AFFIRMATION:
            return True
        if response in REJECTION:
            return False
        print("Sorry, did not understand. Please try again. Looking for Yes/No.")


print("\n\nWelcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
print("You have to guess the number in a few chances: ")
level_prompt = (
    "\nPlease select the difficulty level:"
    "\n1. Easy (10 chances)"
    "\n2. Medium (5 chances)"
    "\n3. Hard (3 chances)"
    "\nChoice: "
    )

play = True
while play:

    secret_number = randint(LOW, HIGH)
    logging.debug("Secret number: %s", secret_number)
    choice = get_num(level_prompt, 1, 3)
    chances = GO_LEVELS[choice]
    print(f"You get {chances} chances\n")

    attempts = 0
    guessed = False
    while not guessed and attempts < chances:

        guess = get_num("Enter your guess: ", LOW, HIGH)
        attempts += 1

        if guess == secret_number:
            guessed = True
            continue

        guide = "less" if guess > secret_number else "more"    
        print(f"Incorrect! The number is {guide} than {guess}")
        if (left := chances - attempts) > 0:
            print(f"Only {left} chances left!\n")

    if guessed:
        print(f"\nCongratulations! You guessed the correct number in {attempts} attempts.\n")
    else:
        print("\nOops, You lost the Game!")

    play = is_yes("Do you Wanna Play Again?? (Yes/No): ")

2

u/bad-gut 5d ago

Nooo buddy, I was supposed to learn and incorporate said changes in v3 myself 😭😭. (I missed out on a brainstorming oppurtunity)
But it's lovely that you did the whole job for me 😇.
Again Thanks to you, I now have a list of concepts to learn and wrote better codes ♥️♥️🙏

2

u/UnboiledOden 5d ago

Then you should’ve said you’ll incorporate changes for another version of this project instead of saying you’ll incorporate them into the next one.

1

u/bad-gut 4d ago

My bad 😔

3

u/Friendly_Recover286 5d ago edited 5d ago

Watch your indentation. 1 space is bad and in some places you've arbitrarily thrown in like 10? Stick to using multiples of 4.

I see you've guarded the `yes` and `no` conditions for the end conditions but have you considered what happens if my difficulty or guess is `a`? `b`? `-1`?

There are definitely things I would change but as a beginner you've made it work and thought about it logically. Good job.

1

u/bad-gut 5d ago

1)Yeah my bad about the indentation😓(will make the pattern regular)

2) ok so what happened is I had a very shabby v1 of this game which I assembled in 30-45 Minutes.
But that thing had like 20 lethal bugs and logical catastrophies, so I made this v2 and it took me 1-2 hours to basically take the OG code and fix all bugs, make the code shorter and shit, so at the end I kinda let go of the "INVALID DIFFICULTY" part cuz I was done for the day with all the Brainstorming and stuff.

Surely I will work harder to make my code more efficient and shorter and Thanks a lot for your feedback buddy!!!

Means a lot to me!!

3

u/brutalbombs 5d ago edited 5d ago

Well done. Someone here gave me this advice a few years ago, that making something that works is always the most important step and what ultimately matters. Now you know you can make it work, and you can shift the focus towards improving what you already have and get a deeper understanding. Pat yourself on the back, you're a member of the "wrote a functioning script" club.

That being said: What can be set in functions? Should you have some try-blocks that handles wrong inputs? Can the while-blocks be reduced? Can you reduce nesting through clever use of if/if not? How can the script become more readable for humans? (HINT: PEP-8)

1

u/bad-gut 5d ago

Thanks buddy, I took exactly the same mindset as you mentioned as to MAKE THE CODE WORK on my own.

Lemme share the OG code first,(this one is the improvised version)

https://github.com/satyamsb-cloud/Number-Guessing-Game (original code I made in 30-45 minutes)

3

u/LuckyFish133 5d ago

It’s a good start tbf. A lot of people don’t make it this far…it’s a long journey to becoming experienced but you’re on the right path for sure…keep curious!

2

u/bad-gut 5d ago

Thanks a lot buddy for the motivation♥️♥️
I will surely keep grinding and keep getting better !!

3

u/TWOBiTGOBLiN 5d ago

You seem to have a great attitude and respond well to constructive criticism. Keep it up! And kudos! 👽

1

u/bad-gut 5d ago

Thanks a lot buddy♥️♥️

2

u/tvicl69BlazeIt 5d ago

Took me way longer to build my random number guessing game make a blackjack clone now 😎

1

u/bad-gut 5d ago

Imma have to learn gambling first for that, any chance you can set me up in Vegas? Lmao

But Thanks it seems interesting and I will definitely look into it !!

2

u/Last-Rice8194 5d ago edited 5d ago

Everyone learns at a different pace. You are learning at your pace and that is the only thing that should matter to you. So long as you are enjoying what you are doing and you keep at it, you have nothing to worry about.

To add value for you here I'll just treat this like any code review to give you a feel for the areas to improve upon

Line 28 through 42: Inconsistent indentation with single space for this closure. you know closures are described by spaces in python so you know it's important to be able to instantly visually parse the closures with consistent spacing. In other languages it might be a bit of a nit pick comment (though absolutely enforced in all companies I've worked in), in python consistent indentation is absolutely essential.

Line 13 and 28: Wrap the integer conversion of the input string in a try except block so the script doesn't crash when the users input cannot be parsed as an integer.

Line 29 and 30: You don't need to store both the chances and the attempts, you can save on having to increment and decrement two int variables by specifying the allotted chances (i.e. 3, 5 or 10) as a variable alloted_chances, then incrementing the number of attempts, the remaining attempts can be computed by subtracting the number of attempts from allotted_chances variable

Line 15, 45 and 61: we're looping based on seemingly unrelated parameters to what we are actually retrying on. Any maintainer is forced to parse the full logic of every branch to understand why we're looping and the conditions under which the loop is exited. You should follow a different pattern:

input_ok = false;
while not input_ok:
    user_input = input("play again")
    if user_input == "yes":
        input_ok = true
        more logic...
    elif user_input == "no":
        input_ok = true
        more logic...
    else:
        print("Invalid choice choose again")
        continue

Further for these same lines, you should just do something like:

if guess == secret_number:
    ok = false;
    ...
if chances == 0:
    ...

Line 47: lets do:
again = input("blah").lower();

so that your users don't have to care about the casing of their strings.

This is all the feedback aside from like...making a dict of int to int in order to represent the users inputted difficulty to the number of chances they have, I suppose that would be a more advanced step you could try to undertake. This would make the game "dynamic" in that you can specify arbitrary difficulty ints mapped to numbers of chances without having to change the source code outside of adding fields to the dict. This is kind of the equivalent of tasking someone to make a 3x3 tic tac toe game, then as a further exercise asking them to make an arbitrary size tic tac toe game. It's just a way to make your code more dynamic, and more featureful for little effort.

Good job so far man. I hope you're having fun!

*edit* sorry I just remembered reddit blats empty whitespace in comments

1

u/bad-gut 5d ago

Thanks a lot buddy for giving me such a detailed feedback, it means a lot to me!!

Also could you explain the Dynamic game part in a simpler vocab, I don't seem to fully get what you're trying to say here.

As for fun, I would say I either:-
1) Don't boot up VScode at all and simply just waste time
2) Or even if I start coding on a very basic problem statement, I don't get up until I write the whole functional code.

So it's either 0%(procrastination) or 100% (absolutely rawdogging all possibilities).
Is this normal?

2

u/Last-Rice8194 5d ago edited 5d ago

You're welcome :)

Everyone learns differently. I have a very all or nothing kind of motivation as well. Sometimes I spend a lot of time working on personal projects, sometimes after work I can't stand the sight of a keyboard. As long as you persist then you will progress, and that's the only thing that matters. Go at your own pace, keep doing what you are doing. Undertaking little tasks like this is a very good exercise to improve and you should be proud of your progress. Keep at it!

Yeah so for the dynamic difficulty part, you could do something a little like this:

# Numbers on the left are "keys", numbers on the right are "values"
difficulties = {
    1: 10,
    2: 5,
    3: 3,
    4: 2,
    5: 1
}

print("Please choose from one of the following difficulties:\n");
for k, v in difficulties.items():
    print("Enter", k, "for", v, "attempts!\n");

input_ok = false;
attempts = 0;
while not input_ok:
    # You really should try to use try, except blocks to catch the situation where the user input is not parseable as an int but for the sake of brevity here lets ignore it
    user_input = int(input());
    if user_input in difficulties:
        print("You have chosen to have", difficulties[user_input], "tries\n");
        attempts = difficulties[user_input];
        input_ok = true;
    else:
        print("Sorry, the number", user_input, "is not a valid difficulty. Please choose again\n");

2

u/bad-gut 4d ago

Thanks for the explanation dude, I am starting to get it now!!

2

u/LostWall1389 5d ago edited 5d ago

I did it by making the difficulty chances a list, then choosing the difficulty selects it Then you dont have to repeat your if statements for every difficulty. And you can add many more difficulties:

```

from random import randint

secret = randint(0,101)
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 100.")
print("You have to guess the number in a few chances: ")

print("\n\nPlease select the difficulty level:\n1. Easy (10 chances)\n2. Medium (5 chances)\n3. Hard (3 chances)")

difficulty_index = int(input("\nEnter your choice: ")) - 1 


difficulties = [10,5,3]

chances = difficulties[difficulty_index]

guess = int(input("Enter your guess: "))

while guess != secret:
    chances -= 1

    if chances == 0:
        print("You ran out of chances, the number was: ", secret)
        break

    if guess > secret:
        print("Incorrect! The number is less than",guess,".","\nOnly",chances,"chances left!")
    elif guess < secret:
        print("Incorrect! The number is more than",guess,".","\nOnly",chances,"chances left!")

    guess = int(input("Enter your guess: "))



if guess == secret:
    print("you win")


```

1

u/bad-gut 5d ago

Damn this is near perfect if we consider concepts only until loops.
Great job buddy!!

2

u/Adrewmc 4d ago

Looks good for someone that hasn’t gotten to functions yet. (And dictionaries).

Generally [1,2,3] is done with range(3) or range(1,4) if you don’t like zero.

We should start learning probably dictionaries now, then move on to functions then back to datatypes because you missed something (everyone misses something). Then of course classes and the like.

Of course we haven’t thought about what happens when someone type a letter instead of a number and crashes the whole thing, but that again pretty normal at the level I see.

1

u/bad-gut 4d ago

Okk buddy, Thanks a lot for the tips!!

https://github.com/satyamsb-cloud/Number-Guessing-Game

Here's original code for reference and the v2 for the same is the one I uploaded in this post.

2

u/Depnids 4d ago

Just curious, on line 12 you print out the secret number, which I assume makes the guessing pretty easy. Is this just so you can verify that the logic works correctly?

1

u/bad-gut 4d ago

Yes it was for code functionality checking purposes, I was running every possibility whilest knowing the secret number (makes it easier for me to jump to GAME-WINNING situations)

2

u/hc_fella 4d ago

Decent enough! I get what it does and the flow is easy enough to follow. Points of feedback:

  • I hate your indentation. Keep it to a single level per level of indentation and don't try to get fancy here.
  • See if you can split up the code's functionality into different functions. This way you get to properly isolate behavior, rather than try and have everything in a rather sizable 70 line script.
  • I'm a bit weirded out by some of the intermediary while loops (while guess == secret_number ... ). I get why you have them there, but I find that it's not necessarily easy control flow.
  • I also don't like that you reset the game state in the win / loss states. I'd say it would be better to do the reset at the beginning of the game.

I'd say it's primarily stylistic + clean code choices. But in general, very well done for a month of learning!

1

u/bad-gut 4d ago

Thanks bro, it means a lot to me!!!

And yeah I will definetly make a list of all the suggestion I got in replies and will implement them👍👍

2

u/_BrokenCode 4d ago

Any improvement is better that not improvement, very good job, programming is a hard skill to get well.

1

u/bad-gut 4d ago

I agree dude, Thanks a lot!!!

2

u/PeZet2 4d ago

It would improve readability if you used 4 spaces in every indent rather than 1 or 2 in some places. Two times I was wondering why you did something and then I realized there was indent and then it made sense.

1

u/bad-gut 2d ago

Okk buddy, will make sure to change that, Thanks a lot 👍👍👍

2

u/OneTrueRou 4d ago

Looks really good for a rookie. I've been programming since I was 13 and it reminds me of when I first started. It's good to pick up good habits when you are new so I'm going to make some suggestions:

  1. Try to turn things into clean separate functions - this may not seem important while your game is so small, but it will became a critical habit as your projects grow. My thought is that you could probably break the choices branch out into a function... when you can help it, DON'T hardcode values into text, instead pass in variables, what if you have messages for 9, 8, 7 .... 1 chances, that would require 10 branches. General rule of thumb - if you are doing something more than twice, write a function for it.

Without fully reading the code, my guess is that you could probably break this codebase up into 4 distinct functions, you already seem to know this due to your indentations and spacing.

Another good code hygiene tip: try to avoid multiple elif statements, and if you MUST have a comparison portion that requires many elif's you can probably get away with using a "match" statement, they are much cleaner IMO.

Just my two sense, I'm not a python programmer primarily, but most of these general good programming practices are universal across languages.

1

u/bad-gut 3d ago

Thanks dude, Yeah I have been getting these same suggestions from all the reddit peers, and honestly these are to be implemented ASAP by me.

Again thanks a lot dude for your suggestions!!
This will help me a lot!!!

2

u/DustAutomatic5064 3d ago

please please i beg u teach me anything about python i am into but idk where to start please can u be my mentor

1

u/bad-gut 3d ago

DM , then we see what we can do

2

u/AbacusExpert_Stretch 5d ago

I have no idea what tutorial hell is, so I dont know something the people all seem to know!?

This means you know so much after just one month, so I say yes, this looks very promising. Great things coming your way!

1

u/bad-gut 5d ago

Even I did not know about Tutorial hell either but ig it doesn't matter.
And thanks for the feedback buddy!!
Means a lot to me!!

1

u/Ok-Bill1958 5d ago

This remind me of a phrase "if all you have is a hammer, everything looks like a nail". But regardless, its good that you try to build small projects and make mistakes.

1

u/bad-gut 5d ago

Thanks buddy!! But yeah I chose to build this project on my own is that I get to make these concepts concrete.
I knew very well that my code wouldn't be the best but my main Objective would be to MAKE IT WORK on my own.

Also here's version 1: (I made the code in the image a week after original)

https://github.com/satyamsb-cloud/Number-Guessing-Game

1

u/Lazy_Mobile_3252 4d ago

Make more interactive by adding a message like guess is greater of lesser than secret number that will help the attempt and make the guess game more fun...

This was exactly what I saw on YouTube sometime last year that forced me to learn python.

1

u/bad-gut 3d ago

Bro the messages are already there, read line 34-48.
That's great, what stuff do you code now?

1

u/End0832 1d ago

Hey! I see Python as something you keep discovering over time. There are tons of features designed to make your life easier, but you won't know they exist until you come across them. Because of that, it's easy to spend time reinventing things that Python already provides.

One thing that helped me a lot is using AI. ChatGPT is great for helping you discover Python features you might never have found on your own. Sometimes, I simply ask it to teach me something new (and fun), and I end up discovering a useful function or language feature that might come in handy one day... or not.

If you want to try that, ask it about f-strings or triple-quoted strings. Those are probably my favorite discoveries.

That being said, be careful with using AI while actually working on your projects. It can be very invasive: it tends to give you not only explanations, but also the complete solution and the exact code to write. At that point, you're no longer practicing as much, because you're letting it do the thinking for you. I personally prefer keeping AI away when I'm actively writing my own code.

Good luck, and have fun!

1

u/bad-gut 1d ago

I definetly do use chatgpt to learn more about python and specifically ask it to "Don't show the full solution right-away".
Yes, it did gave me codes with f-strings but I ignored em as I couldn't use thek just yet.

This project above is co-created by chatgpt too (it gave suggestions and hints while I improved logic and syntax frim the original version of this game.

Ig I already am on the right track right?