Python Forum
Can someone help me please understand this code?
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can someone help me please understand this code?
#1
I believe i have highlighted the sections i'm referring to below.


So i just want to understand the parts i'm going to ask about, because i got confused and don't want to move onto the next section until i understand them.

line 18 - 22,

i understand that name and system, the net is for windows and clr is to clear the screen and the else is there in case it is mac or something else, so either way it clears the screen, so is that the main reason for this function, that is clears my screen after typing information and then whatever need to be retained stays on the appropriate section of the screen?


line 45,
the function there that has (good, bad) for arguments, what does good and bad do, i'm confused with how arguments work honestly. So here couldn't that part of code have been written without them or did it need them to write the code?

then line 58,
what does return guess do ? Couldn't we have done print guess? I'm still trying to understand how return works as well.

then line 71,

what in the world is found = True for? I'm very confused here, as well as line 74 where found is now false? Then line 75 where, if found: what does this mean? that whole part of code from line 71 to 75 has me lost.

then line 83
where done = true and that is the argument to the play function? What does that do? then line 89 where return makes done = false? Return runs the play function and makes the argument false??? how did we run the function through return that also confuses me?

then line 99
what does return true do there? Why is it there?

then lastly what does 103
done = False do, how did done go from true to false and what did it do each time?

I really appreciate any help here, I understand most the code but i feel this will really help me get clarity.

THANK YOU ALL FOR THE HELP SO MUCH THANK YOU!!!

import random
import os
import sys

words = [
    'apple',
    'banana',
    'orange',
    'coconut',
    'strawberry',
    'lime',
    'lemon',
    'blueberry',
    'melon',
]

def clear():
    if os.name == 'net':
        os.system('cls')
    else:
        os.system('clear')[ / color]

def draw(bad, good, secret_word):
    clear()
    print('strikes: {}/7'.format(len(bad)))
    print('')
    for letter in bad:
        print(letter, end=' ')
    print('\n\n')
    for letter in secret_word:
        if letter in good:
            print(letter, end='')
        else:
            print('_', end='')
    print('')

def get_guess(bad, good):
    while True:
        guess = input("guess a letter: ").lower()
        if len(guess) != 1:
            print("you can only guess a single letter")
            continue
        elif guess in bad or guess in good:
            print("you've already guessed that letter")
            continue
        elif not guess.isalpha():
            print('you can only guess letters')
            continue
        else:
           return guess

def play(done):
    clear()
    secret_word = random.choice(words)
    bad = []
    good = []
    while True:
        draw(bad, good, secret_word)
        guess = get_guess(bad, good)
        if guess in secret_word:
            good.append(guess)
            found = True
            for letter in secret_word:
                if letter not in good:
                    found = False
            if found:
                print('win')
                print("word was {} ".format(secret_word))
        else:
            bad.append(guess)
            if len(bad) == 7:
                draw(bad, good, secret_word)
                print('you lost secret word was{} '.format(secret_word))
                done = True[ / color]
        if done:
            play_again = input('play again y/n')
            if play_again != 'n':
            else:
                sys.exit()

def welcome():
    start = input("press enter to start or q to quit ")
    if start == 'q':
        print('bye')
        sys.exit()
    else:
        return True[ / u][/color]

print('welcome to letter guess')

while True:
    clear()
    welcome()
    play(done)
Reply
#2
Your original code did not compile due to 'color added' and due to some bad code. I corrected both. The program also did not run correctly due to some logic errors. All the changes I made are annotated in the code at the bottom of the post. I changed as little as possible to make the program still functional. The code should now run.

NOTE: Line numbers are your original line numbers (which were often incorrect), and do not reflect changes to the code.

------------------
Quote:line 18 - 22
Function clear() clears the screen. 'net' is incorrect and should be 'nt' which stands for Windows NT (which is the underlying code for versions of Windows since 1993). The other branch is for other operating systems.

------------------
Quote:line 45
'bad' is a list containing each of the 'bad guesses' and 'good' is a list containing each of the 'good guesses' . For more information about lists see https://www.tutorialspoint.com/python/python_lists.htm
Functions draw() and get_guess() need access to both 'bad' and 'good'.

For a basic function tutorial see https://python-forum.io/Thread-Basic-Fun...+reference courtesy of metulburr.

There are a few basic concepts you need to know about functions. See the function in the following simple Python Program.
def weighted_add(a, b):
    sum = a + a + b
    return sum
 
x = 3
y = 4
z = weighted_add(x, y)
print(z)
print(weighted_add(x, y))
print(weighted_add(3,4)) 
print(weighted_add(a = 3,b = 4)) 
print(weighted_add(b = 3,a = 4)) 
a and b in the function definition are called Arguments.
When you call a function (e.g. 'weighted_add(3,4))', 3 and 4 are called Parameters.
Some people (including me) incorrectly use the two terms interchangeably.

In general (there are exceptions):
a. Variables defined inside a function (e.g. sum) are local to the function and can not be seen outside the function.
b. Variables defined outside a function (e.g. x, y, z) can not be seen inside the function.
c. For a function to see an outside item, the item is passed to the function as a parameter.
d. The return statement is the last statement executed in the function. It does not have to physically be the last statement in the function.
d. A function can send zero or more values back to the outside world. This is done with a return statement.
e. 'return sum' sends sum to the calling routine.
f. A function with 'No return statement' returns the special value 'None' which is a special object type called 'NoneType'.

Some of the above concepts should be saved for the future

------------------
Quote:line 58 .... what does return guess do ? Couldn't we have done print guess?

'return guess' sends the value of guess back to the outside world.
print(guess) prints the value (useful in debugging). It performs no other useful purpose.

------------------
Quote:then line 71, what in the world is found = True for? I'm very confused here, as well as line 74 where found is now false? Then line 75 where, if found: what does this mean? that whole part of code from line 71 to 75 has me lost.

In the following code excerpt from the working program, 'found' is initialized to 'True' (meaning the guess was found in the 'secret word'. The 'for loop' examines each letter in the 'secret word' until either the letter is not in the list of 'good guesses' (i.e. meaning the entire 'secret word' is not yet 'found' and 'found' is set to False) or until all the letters were examined and all the letters were in the 'secret word; meaning the correct 'secret word' was found. If found' (is true), then set the 'done' flag is set to True and tell the world we won.

if guess in secret_word:
            good.append(guess)
            found = True
            for letter in secret_word:
                if letter not in good:
                    found = False
                    break                 #added this line to exit the loop when a letter is NOT in the SECRET WORD
            if found:
                done = True               #added this line - otherwise game restarts automatically on a win
                print('win')
                print("word was {} ".format(secret_word))
--------------------------
Quote:line 83 - where done = true and that is the argument to the play function? What does that do?

Good question. That is a programming error. That 'done' should not be there. 'done' should be initialized inside the play() function.

--------------------------
Quote:then line 89 where return makes done = false? Return runs the play function and makes the argument false??? how did we run the function through return that also confuses me?
line 99 - what does return true do there? Why is it there?

Another programming error. play() runs forever until the user does not want to play another game.
Line 99 is another programming error that should not be there.

--------------------------
Quote:what does 103 - done = False do, how did done go from true to false and what did it do each time?

Another programming error. 'done' indicates that a single game is completed. It is initialized to 'False' (new code) and set to 'True' when a single game is over. If the user wants to play another game it is initialized to 'False' at the top of function play(). The new variable 'iguesscount' is initialized to 0 before each game, causing important items to be reinitialized.

Complete code:
import random
import os
import sys
 
words = [
    'apple',
    'banana',
    'orange',
    'coconut',
    'strawberry',
    'lime',
    'lemon',
    'blueberry',
    'melon',
]
 
def clear():
    if os.name == 'nt':       #was '.net' changed to '.nt'
        os.system('cls')      #on windows
    else:
        os.system('clear')    #Removed color extraneous text  # on linux / os x
 
def draw(bad, good, secret_word):
    clear()
    print('strikes: {}/7'.format(len(bad)))
    print('')
    for letter in bad:
        print(letter, end=' ')
    print('\n\n')
    for letter in secret_word:
        if letter in good:
            print(letter, end='')
        else:
            print('_', end='')
    print('')
 
def get_guess(bad, good):
    while True:
        guess = input("guess a letter: ").lower()
        if len(guess) != 1:
            print("you can only guess a single letter")
            continue
        elif guess in bad or guess in good:
            print("you've already guessed that letter")
            continue
        elif not guess.isalpha():
            print('you can only guess letters')
            continue
        else:
           return guess
 
def play():                           #'def play(done):' changed to 'def play():'
    iguesscount = 0        #initialize the 'Guess Count' - when 0, then initialize all variables
    while True:
        #
        #Moved initialization here - required for multiple plays
        if iguesscount == 0:
            done = False                      #Added this line to initialize 'done' 
            clear()
            secret_word = random.choice(words)
            bad = []
            good = []
        #
        draw(bad, good, secret_word)
        guess = get_guess(bad, good)
        iguesscount += 1                  #increment the guess counter - just need non-zero value so initialization does not occur during game
        if guess in secret_word:
            good.append(guess)
            found = True
            for letter in secret_word:
                if letter not in good:
                    found = False
                    break                 #added this line to exit the loop when a letter is NOT in the SECRET WORD
            if found:
                done = True               #added this line - otherwise game restarts automatically on a win
                print('win')
                print("word was {} ".format(secret_word))
        else:
            bad.append(guess)
            if len(bad) == 7:
                draw(bad, good, secret_word)
                print('you lost secret word was{} '.format(secret_word))
                done = True  # removed [ / color] extraneous text  - invalid syntax string
        if done:
            play_again = input('play again y/n')
            if play_again != 'n':
                iguesscount = 0   #initialize the 'Guess Count' - to enable replay
                #pass             #was indentation error - previously added this line to remove compile error - 'pass' is a place holder that does nothing
            else:
                sys.exit()
 
def welcome():
    start = input("press enter to start or q to quit ")
    if start == 'q':
        print('bye')
        sys.exit()
    else:
        return True  # removed [ / color] extraneous text  - invalid syntax string
 
print('welcome to letter guess')
 
while True:
    clear()
    welcome()
    play()        #compile error - done is NOT DEFINED  'play(done)' changed to 'play()'
Lewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
Reply
#3
Working with lists in python is a bit tricky at the beginning.
This resource is helpful for playing with lists.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unable to understand the meaning of the line of code. jahuja73 0 272 Jan-23-2024, 05:09 AM
Last Post: jahuja73
  Unable to understand how given code takes a fixed input value, without inputting. jahuja73 4 2,646 Jan-28-2021, 05:22 PM
Last Post: snippsat
  Don't understand example code from a textbook lil_fentanyl 1 1,798 Jan-25-2021, 07:02 PM
Last Post: nilamo
  Unable to understand a statement in an existing code ateestructural 1 2,191 Aug-01-2020, 09:38 PM
Last Post: deanhystad
  Trying to understand the python code spalisetty 2 1,836 Mar-16-2020, 08:11 AM
Last Post: javiertzr01
  I couldn't understand the output of the below code ravich129 1 1,893 Dec-12-2019, 06:24 AM
Last Post: sandeep_ganga
  can you understand why this code prints None? arcbal 2 2,700 Mar-13-2019, 02:57 AM
Last Post: arcbal
  Don't understand why this quicksort code works lupoalberto 6 3,913 Mar-27-2018, 10:01 AM
Last Post: lupoalberto
  Can't understand the code SelectiveDuplicate 2 2,875 Mar-23-2018, 07:57 AM
Last Post: SelectiveDuplicate
  code to understand the script execution Skaperen 2 3,298 Jan-06-2018, 05:25 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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