What is the best way to learn to code?

Okay, so I’ve been tinkering around and I think I’m starting to get to grips with how functions work…maybe. I’ve reworked the code for the Monty Hall problem and now it looks like this:



import random
door = [1,2,3]

def doors():
    """This function picks a door"""
    x = int(input("Select a door (1-3): ").strip())
    door.remove(x)
    y = random.choice(door)
    door.remove(y)
    print("You have selected {}. I open door {}".format(x,y))

def choice():
    """This function gives 2/3 chance of a win if you switch and 

    2/3 chance of a loss if you stick"""
    a = ["Win","Win","Lose"]
    b = ["Lose","Lose","Win"]
    z = input("Will you change doors? y/n: ").strip().lower()
    if z == "y":
        c = random.choice(a)
        d = "YOU WIN!!"
    else:
        c = random.choice(b)
        d = "YOU LOSE :-("
    return d

doors()
print(choice())


I’ve tested it a few times, not exhaustively I admit, but enough times to satisfy myself that it works. What do you think?

It’s a little cleaner but you’re just randomly selecting if someone wins or loses. You want to select a random door as the winner to start, then get the user’s choice of a door. Then you show him one of the other two doors, but it can’t be the one that is the winner. Then ask him if he wants to switch, change his door choice if he does, then see if he’s right. You want to keep track of how many attempts are made, how many times he’s right if he switches, and how many times he’s right if he doesn’t switch, then see how the odds worked out.

So now put it all into a loop, ask if he wants to play again after each iteration, count the iterations, and keep track of the number of wins with and without switching.

You need to select 1 random door out of the 3 at the start of each game which is the winner. You need to select 1 of the 2 other doors after the user’s choice to reveal to the user, but it can’t be the winning door.

You’re getting there.

Don’t bother trying to do that yet. Be happy with the command line until you’ve made a half dozen good command line applications.

You can make them interactive.

I found this (free) online class really helpful for making the leap from writing little self-contained Python scripts to creating an interactive UI. Disclaimer: I did find the dumbed-down, chummy nature of the course really irritating, but I still got a lot out of it: Free Intro to Python Course | Free Courses | Udacity

The end product of the course is an interactive web site that plays the trailers for your favorite movies.

I took the above course after completing another Udacity course – Into to Computer Science. It teaches Python in the context of building a search engine. It’s very rigorous and comprehensive and I highly recommend taking it if you want to learn Python, but I came out with the same issue as the OP: I knew how to write code and make decisions about data structures, etc, but felt that I didn’t actually know how to USE what I had learned in real life.

Another helpful tool for beginners (maybe for everyone) is the Python visualizer here: Python Tutor code visualizer: Visualize code in Python, JavaScript, C, C++, and Java. You paste your code in and then you can click through it step-by-step to see what each line does. It’s fun to see the values of your variables change, and of course it’s very helpful when you’ve written something that doesn’t work the way you expect it to and you can’t figure out why.

This is going to be a radical set of thoughts, but please bear with me.

You might want to consider looking into software and applications that teach coding to children. I am familiar with Scratch and taught it my 12-year-old nephew for about 2 hours; by the end of the weekend, he had built his very own game. Scratch is something you download for your computer; I know it works on Windows. They may support other computers, or, they may have gone with an online model by this time.

The second one, Bitsbox, I have only seen demonstrated (yesterday, in fact), and it seemed really good. My 10-year-old granddaughter wants me to create an account there so she can start doing some coding. I believe it is an online thing, as opposed to a program installed on your computer.

There is nothing wrong with taking a “children’s approach” to programming. You are, effectively, starting out with nothing and hoping to gain some real knowledge. It is certainly an easy/fun way to do that, with lots of examples on their respective sites.

When I started learning the Irish language several years ago, I scoured the internet for resources for children. Yeah, I was over 50, but I was eager to learn colors and numbers, just as if I were 6 years old. After studying for 3 or 4 months, my teacher gave me a book that was aimed at 8-year-olds, and I was thrilled to discover I could read it!

What concerns me most about your original post is that you said you felt like you were blindly copying the teacher’s instructions about setting a variable to X and another to Y and then doing a loop without knowing why you were doing it. If you truly mean that, it indicates that you haven’t grasped some basic, fundamental concepts. I was inclined to give you the benefit of the doubt, but after looking at your Monty Hall problem, I have to agree with TriPolar and others. Some of it may just be rookie mistakes, and we all have to start somewhere.

Both Scratch and Bitsbox will teach you, but they will go about it in different ways. Scratch is a “visual language”, and you drag-n-drop components around like puzzle pieces. It is certainly not a “practical” language, but it will definitely help you see what you are doing, and that may help you figure out some of those basic, fundamental concepts. Bitsbox is more like C/C#/Java/Javascript in that it is a written-out, scripted language. Learning that will help you learn object manipulation in a fun, game-oriented way.

[IMHO]
I don’t want to start a language war here, that is not my intent, and I am sure others will disagree with me. However, I have been a professional software developer since 1983, so please allow me my own bias. I am not sure I would consider python a great language to use as a starting language. I have written several python scripts and modified others without having any training in it. (Again, echoing what has been said before, you can learn a language by reading lots of stuff that other people have written.) I am not a python expert by any means. However, I don’t think it would be my first choice for a language to start learning programming. It feel too “abstract” for me.
[/IMHO]

Good luck, though. There are lots of ways to go about what you are trying to do. There are some good books out there that will help you learn a language. Typically, they start you out on a little program in chapter 1, and then modify it slightly in chapter 2 to add a feature. By the time you get to chapter 20, you have a full-blown application that is fairly useful.

This is pretty much how I teach our Introduction to Programming Class at our community college. The first half of the semester uses Scratch to show graphically how the language parts fit together, and the second half is spent showing pretty much the same concepts in Python. I use the Marji Learn to Program with Scratch because it covers some interesting late-high school or early college type science and math projects. Then I use the Sweigert Automate the Boring Stuff which has some useful projects; I have several non-CS students take the course and this way they get some projects that would be useful to them (such as automating Web scraping or using Microsoft Office).

I think seeing the same “problem” presented in two languages reinforces that there’s nothing magical about which language you use, and though each language has strengths, learning how to think about how to solve problems is the hardest part of learning programming. After you do that, you can learn coding.

Thanks :slight_smile: I took your comments on board and rewrote the program using functions for each stage. The new program [ul]

[li] Selects a winning door at the very start of the program.[/li][li] Then asks the user for a door.[/li][li] Then selects a door to open which is neither the answer (step 1) or the user’s guess (step 2).[/li][li] Then asks the user whether he wants to stick with his original choice or switch.[/li][li] And finally keeps score as you go. [/ul][/li]



import random

win = 0
lose = 0

while 100:

    door = [1,2,3]
    x = 0
    
    def pick_answer():
        answer = random.choice(door)
        return answer
    a = pick_answer()

    def pick_guess():
        guess = int(input("Please choose a door (1-3): ").strip())
        return guess
    b = pick_guess()

    if a == b:
        def montys_door_if_a_is_b():
            global x
            door = [1,2,3]
            door.remove(a)
            x = random.choice(door)
            return x
        c = montys_door_if_a_is_b()
        print("You chose door {}".format(b))
        print("I choose door {}".format(c))

        def montys_final_choice():
            door = [1,2,3]
            door.remove(x)
            door.remove(a)
            y = door[0]
            return y
        d = montys_final_choice()

        print("You're left with doors {} and {}".format(b,d))
        choice = input("Will you SWITCH to door {}? y/n: ".format(d)) 
        
        def switch_or_stick():
            if choice == "y":
                print("Bad luck.  You lost.  You should have stuck as you already had the right answer.")
                global lose
                lose = lose + 1
                print("{} wins and {} losses".format(win,lose))
            else:
                print("Huzzah! You made the right choice by STICKING!")
                global win
                win = win + 1
                print("{} wins and {} losses".format(win,lose))
        switch_or_stick()

        input("
Press Enter to play again")
    
    else:
        def montys_door_if_a_not_b():
            door = [1,2,3]
            door.remove(a)
            door.remove(b)
            md = door[0]
            return md
        e = montys_door_if_a_not_b()
        print("You chose door {}".format(b))
        print("I choose door {}".format(e))

        def montys_final_choice_if_a_not_b():
            door = [1,2,3]
            door.remove(e)
        f = montys_final_choice_if_a_not_b()

        print("You're left with doors {} and {}".format(a,b))
        choice = input("Will you SWITCH to door {}? y/n: ".format(a)) 

        def switch_or_stick_redux():
            if choice == "y":
                print("HUZZAH!  YOU WIN")
                global win
                win = win + 1
                print("{} wins and {} losses".format(win,lose))
            else:
                print("Bad luck.  You should have switched. You chose the wrong door at the start")
                global lose
                lose = lose + 1
                print("{} wins and {} losses".format(win,lose))
        switch_or_stick_redux()

        input("
Press Enter to play again")


If, for example the program chose door 1 and the user also chose door 1, and the user chose not to switch, the output would be:



Please select a door (1-3)
You selected door 1.
I choose door 2
You now have to choose between door 1 and door 3.
Will you switch to door 3? y/n?
Huzzah!  You won.
1 wins and 0 losses


Conversely, if you and the computer chose different answers and you chose to switch, you’d also win. The counter updates from game to game to keep a running tally of your wins and losses.

I ran it a bunch of times and the probabilities definitely work. You have a 1/3 chance of winning if you stick, and a 2/3 change of winning if you switch. I must say, however, that personally I prefer my second attempt because it gives exactly the same results with far fewer lines of code.

That said, I also have to say I found doing it your way (that is, working out every step, creating a function for it systematically and thinking it all through step-by-step) very rewarding. Very frustrating, at times, but very rewarding. It took me literally all day to do this, but I feel I now understand functions much better than I did before. That’s not to say I understand them particularly well, of course, but I think I understand them a lot better. Thanks for your advice. It’s appreciated :slight_smile:

PS - In the above post, ‘while 100’ should be ‘while True’. Don’t know how I missed that. It doesn’t seem to affect the program, though.

Hi, sorry to bump up my own thread, but I was wondering if anyone had any comments on my latest attempt to code the monty hall problem in an interactive game. I’ve found your comments so far really helpful so any feedback you may have on my latest attempt would be massively appreciated. Cheers :slight_smile:

Although you can define your functions right before using them, traditionally, you’d put the definitions at the top, and your main control loop at the bottom.

So not:


while True:
    def foo():
    ...
    foo()
    def bar():
    ...
    bar()


def foo():
    ...

def bar():
    ...

while True:
    foo()
    bar()

For one, that lets you use them outside that loop. For another, it makes the loop easier to read, because you don’t have to read all the sub-parts in sequence.

Next step is: how short can you make this program?

When you sit down to write a program, your first programming language needs to be English*.

You need to be able to tell yourself (or, if necessary, write down) the actual sequence of events – the steps – you want your program to do. Every decision point. Every set of conditions. How to go back and do it again if you’re not done.

Only after you have a good idea of what the program needs to do, in generalized terms, are you ready to implement the program in actual code. Each written step can become a block of code to perform the function of that step.

*Or whatever human language you feel most fluent and expressive in.