Python Forum
codebreaker exercise visualsteps
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
codebreaker exercise visualsteps
#1
HI,

Just starting out with python. Throught my book, a real basic book from visual steps I came to make below code. I think I understand all the working but one thing potentially puzzles me.

I use this: for x in range(0,4): a few times. Now I understand what the loop does and that is is nested further down the code but, how does the interpreter understand that x comes from the number range which was initially put in under the variable "code". Even thinking about the indentation does not explain it to me fully.

Anybody who can explain in baby logic :-) how python interpreter knows that x is processing the numbers given in the variable code (assuming I have that right).

Any help appreciated.

Thanks,
Ivo
import random
import sys
while True:
    # invoer code door de speler
    code = input("geef je code van 4 cijfers op (stop met 9999):") 
    # controleer op cijfers only
    if code.isdigit():
        #stop met het spel
        if int(code) == 9999:
            sys.exit()
        # controleren op 4 cijfers
        if len(code) == 4:
            
            # controleer dat de cijfers < 1 of > 6
            fout=0
            for x in range(0,4):
                if int(code[x]) < 1 or int(code[x]) > 6:
                    fout=1
            if fout == 0:
                
                # controleer of all getallen verschillen zijn
                gelijk=0
                for x in range(0,4):
                    for y in range(0,4):
                        if x != y and code[x] == code[y]:
                            gelijk=1
                if gelijk == 0:
                    
                    break
                else:
                    print ("twee of meer cijfers zijn hetzelfde")
            else:
                print("cijfers mogen niet lager dan 1 of hoger dan 6 zijn")
        else:
            print("er zijn te weinig of te veel cijfers")
    else:
        print("er staan letters in")
print("all is well")
Reply
#2
I have trouble understanding the question. However, I suggest to type into interactive interpreter:

>>> help('for') 
The "for" statement
*******************

The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:

   for_stmt ::= "for" target_list "in" expression_list ":" suite
                ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable
object.  An iterator is created for the result of the
"expression_list".  The suite is then executed once for each item
provided by the iterator, in the order returned by the iterator.  Each
item in turn is assigned to the target list using the standard rules
for assignments (see Assignment statements), and then the suite is
executed.  When the items are exhausted (which is immediately when the
sequence is empty or an iterator raises a "StopIteration" exception),
the suite in the "else" clause, if present, is executed, and the loop
terminates.

A "break" statement executed in the first suite terminates the loop
without executing the "else" clause’s suite.  A "continue" statement
executed in the first suite skips the rest of the suite and continues
with the next item, or with the "else" clause if there is no next
item.

The for-loop makes assignments to the variables(s) in the target list.
This overwrites all previous assignments to those variables including
those made in the suite of the for-loop:

   for i in range(10):
       print(i)
       i = 5             # this will not affect the for-loop
                         # because i will be overwritten with the next
                         # index in the range

Names in the target list are not deleted when the loop is finished,
but if the sequence is empty, they will not have been assigned to at
all by the loop.  Hint: the built-in function "range()" returns an
iterator of integers suitable to emulate the effect of Pascal’s "for i
:= a to b do"; e.g., "list(range(3))" returns the list "[0, 1, 2]".

Note: There is a subtlety when the sequence is being modified by the
  loop (this can only occur for mutable sequences, e.g. lists).  An
  internal counter is used to keep track of which item is used next,
  and this is incremented on each iteration.  When this counter has
  reached the length of the sequence the loop terminates.  This means
  that if the suite deletes the current (or a previous) item from the
  sequence, the next item will be skipped (since it gets the index of
  the current item which has already been treated).  Likewise, if the
  suite inserts an item in the sequence before the current item, the
  current item will be treated again the next time through the loop.
  This can lead to nasty bugs that can be avoided by making a
  temporary copy using a slice of the whole sequence, e.g.,

     for x in a[:]:
         if x < 0: a.remove(x)

Related help topics: break, continue, while
(END)
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
Thanks for the answer. My question is related to e.g. line 16 where x is used after "for". how does x know that it deals with the input given earlier in the "code" variable? (line 16 for your reference: for x in range(0,4):. I just do not understand how from the code line 16 knows this is about the input given in line 5. What if for instance when line 6 had a variable declared called code_2 or something like that.

I miss a fundamental understanding is my feeling, despite the fact I know what it does, I just do not get how it does it.
Reply
#4
In the for-loops x doesn´t know anything :-)
x is used as an index to address single items in the variable code which is a string.
If you enter 4 digits the input() functions returns a string e.g. '1234'.
Each character in the string can be accessed by using brackets e.g. code[0] is '1', code[1] is '2' etc.
range(0,4) is an iterator function that assigns the variable x in the for-loop the values 0, 1, 2, 3
after another. If the start is 0, that value can be omitted, so range(4) does the same.
But!
In Python you can iterate directly over the contents of a string.
for character in code:
    if int(character) < 1 or int(character) > 6:
        fout = 1
is the pythonic way to do that verification.

I refactored your code a little bit to give you some hints how things can be done.

import random

def main():
    while True:
        # invoer code door de speler
        code = input("geef je code van 4 cijfers op (stop met 9999):") 
        if code == '9999':
            break
        # controleer op cijfers only
        if code.isdigit():
            # controleren op 4 cijfers
            if len(code) == 4:
                # controleer dat de cijfers < 1 of > 6
                fout = False
                for cijfer in code:
                    fout = cijfer in '0789' or fout
                if not fout:
                    # controleer of all getallen verschillen zijn
                    gelijk = False
                    for x in range(4):
                        for y in range(x+1, 4):
                            gelijk = code[x] == code[y] or gelijk
                    if not gelijk:
                        print("your code meets all conditions")
                        break
                    else:
                        print("twee of meer cijfers zijn hetzelfde")
                else:
                    print("cijfers mogen niet lager dan 1 of hoger dan 6 zijn")
            else:
                print("er zijn te weinig of te veel cijfers")
        else:
            print("er staan letters in")

    print("all is well")


if __name__ == '__main__':
    main()
Reply
#5
Thanks, I understand. The fact that the loop is indented under de variable code links it to that variable, right?
Thanks very much for taking the time to refactor, although...I will first (have to..)finish my basics and then get to the pythonic way.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  CODEBREAKER game rob101 0 819 Nov-07-2023, 07:08 AM
Last Post: rob101

Forum Jump:

User Panel Messages

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