Python Forum
total Noob question: Why is the code not executed
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
total Noob question: Why is the code not executed
#1
I am a total noob at learning python (day 6) and i gave myself a homework.

The program is a game where the user has to guess a number between 1-100. The computer then answers back if the secret number is "higher" or "lower" and the the user kepps guessing.

It is running so far, but i really can't wrap my head around why this statements at the end are not executed from that point on:


print(Game())
    z.append(result)
    print(z)....
Program:
z=[]
keepPlay='y'
while keepPlay=='y':
    def Game():
        x=random.randint(1,100)
        y=0
        i=0
        while True:
            print('Please guess the number')
            y=int(input())
            i+=1
            if y>x:
                print('lower - your guess is to high')
            elif y<x:
                print('higher - your guess is to low')
            elif y==x:
                break
        if y==x:
            [b]print('well done you guessed my number in ' + str(i)+' tries[/b]')
        return i[/quote]

    result=Game()
    print(Game())
    z.append(result)
    print(z)

    print('Want to play again y/n ?')
    a=input()
    if a=='y':
        keepPlay='y'
    elif a=='n':
        break
    #else:
    #print()

print('Ok good bye then')
The games runs till you pick the right number but then outputs:
Output:
well done you guessed my number in 5 tries
then it immediatley jumps to
Output:
Please guess the number
but it should have exited the while-loop after the break statement??

2nd question would be: What i wanted to do is to practise to encapsulate the core game into the function and then use the while loop only to execute the function and give back the number of guesses the user needed per round (the z=[]). But i struggled to do this. So if there are any tipps on this would appreciate it...

Thx and have a good one..
Reply
#2
You call your function two times in a row here, once to get the result and once to print the result.
    result=Game()
    print(Game())
If you played the game twice you would see the other prints.

Since you are a noob, you may as well develop good habits from the start. Read PEP8, the document about python coding conventions.
https://peps.python.org/pep-0008/

There is no reason to define a function inside of a loop. Python lets you do it, but nobody does it.

PEP8 says function names should be in snake case. No uppercase letters.

This is how I would write your program.
import random


# Define functions above main body of code.
def number_guessing_game():
    number = random.randint(1, 100)   # Use meaningful variable names, not x
    count = 0
    print('Please guess the number in the range 1 to 100.')
    while True:
        count += 1
        try:
            guess = int(input())
        except ValueError:  # int() can raise a value error.
            print("That is not a number.  Try again.")
            continue
        if guess == number:
            # Use f string formatting instead of concatenation.
            print(f'Well done! You guessed my number in {count} tries')
            return count
        if guess > number:
            print('Your guess is too high. Try again.')
        else:
            print('Your guess is too low.  Try again.')


results = []
while True:
    results.append(number_guessing_game())
    print(results)
    if input('Want to play again y/n?\n') != 'y':
        break
print('Ok good bye then')
MarkMan likes this post
Reply
#3
Thank you deanhystad for this very instructive code and helpful advice.
I now see that i called the function twice and other things.

one questions i would have:
in the code of the function your while loop starts with "while True", but there is no break statement. I have seen this before but i thought than the return statement for the function would have to be the last line in the function definition so that by ending the function the while loop kinda ends to. I don't understand how the execution knows to quit the while loop (and function) since after the return statement there comes more if-statements? Maybe you can shed some light on this?

Thx
Reply
#4
A return statement can be anywhere in a function.

A function can have multiple return statements. This is common coding convention:
def function(arg):
    if arg_is_wrong_type(arg):
        return
    if arg_is_out_of_range(arg):
        return
    do_processing_with_arg(arg)
Executing the return statement ends execution of the function and returns to the calling context.

All return statements return a value. If no value is provided in the return statement, None is returned.
MarkMan likes this post
Reply
#5
Very, very interesting thx for shedding light on this. From reading in a book that after the return statement, all local variables are beeing "Noned", i concluded it should therefore be at the end. But now i understand it is simply a thing of finding the right order.

One more thing i noticed about your original code. You did not use an elif statement but if statements but an else-statement at the end. Is this simply a thing of taste or is there a deeper meaning behind this?
Reply
#6
I used else because I either wanted to print "Your guess is too high" or "Your guess is too low". There are no other outcomes. Using elif indicates there are more than 2 outcomes.

I could also write using if/elif/else like this:
    while True:
        count += 1
        try:
            guess = int(input())
        except ValueError:  # int() can raise a value error.
            print("That is not a number.  Try again.")
            continue
        if guess > number:
            print('Your guess is too high. Try again.')
        elif guess < number:
            print('Your guess is too low.  Try again.')
        else:
            print(f'Well done! You guessed my number in {count} tries')
            return count
Both produce the same result. I like highlighting that that the there are two outcomes from guessing a number. Your guess is correct, and the function prints a message and returns the number of guesses, or the function prints a hint and you continue guessing. It is equally valid to say there are three outcomes when you make a guess.

Quote:after the return statement, all local variables are beeing "Noned"
This has nothing to do with the return statement. This happens when execution exits the function. Execution exits a function when a return statment is executed, but this may also happen when an exception is raised. Execution also exits a function when the end of the function is reached.

Local variables inside a function are not accessible outside the function. When execution returns from a function, the function variables no longer reference anything ("Noned" I guess). This may result in deleting objects referenced by those variables (if they are the sole reference).
MarkMan likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to not open the context menu if a mouse gesture is executed? MicheliBarcello 2 1,497 Aug-22-2023, 02:47 PM
Last Post: deanhystad
  return next item each time a function is executed User3000 19 5,784 Aug-06-2023, 02:29 PM
Last Post: deanhystad
  code not working when executed from flask app ThomasDC 1 3,693 Jul-18-2023, 07:16 AM
Last Post: ThomasDC
  [ESP32 Micropython]Total noob here, I don't understand why this while loop won't run. wh33t 9 3,893 Feb-28-2023, 07:00 PM
Last Post: buran
  Function not scriptable: Noob question kaega2 3 2,213 Aug-21-2022, 04:37 PM
Last Post: kaega2
  Noob question about lists adifrank 4 3,859 Nov-19-2020, 03:26 AM
Last Post: adifrank
  Noob question: why is shapesize() not working for my turtle adifrank 8 9,196 Sep-09-2020, 11:13 PM
Last Post: adifrank
  Noob question adifrank 6 4,030 Aug-18-2020, 11:50 PM
Last Post: adifrank
  I don't get the order of how things are executed with main() pythonrookie 5 3,914 Jul-21-2020, 01:35 PM
Last Post: pythonrookie
  Script works when executed from command prompt but not when executed in SDP Tippex 0 2,747 Apr-07-2020, 04:26 PM
Last Post: Tippex

Forum Jump:

User Panel Messages

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