Python Forum
codebreaker exercise visualsteps
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
codebreaker exercise visualsteps
#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


Messages In This Thread
codebreaker exercise visualsteps - by ivobrugman - Aug-10-2019, 08:12 PM
RE: codebreaker exercise visualsteps - by perfringo - Aug-11-2019, 08:35 AM
RE: codebreaker exercise visualsteps - by ThomasL - Aug-11-2019, 09:44 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  CODEBREAKER game rob101 0 895 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