Your First Python Program

If you followed the Python tutorial from the start, you’ve learned a lot by now. We’ve covered key topics, like booleans and conditional programming, strings, and functions. What we haven’t done yet, is create an actual program. So let’s wrap this up by combining what we learned into a nice little program. We will create your first Python program together.

Entering the code in the REPL

Let me share the program first. Please analyze it thoroughly before you continue reading. There’s one function you don’t know yet (input), but that I’ll explain shortly:

def say_hi(name):
    if name == '':
        print("You didn't enter your name!")
    else:
        print("Hi there...")
        for letter in name:
            print(letter)

name = input("Your name: ")
say_hi(name)

Now it’s time to try this program yourself. If you simply copy and paste the above code into the REPL, you’ll notice that it won’t work. What does work is:

  1. First copy the function say_hi(name) and hit enter. Now the REPL knows this function.
  2. After that, copy and paste the name = input("Your name: ") and hit enter again. It will ask for your name, so enter it.
  3. Finally, you can copy and paste the say_hi(name) line and see what happens!

In the REPL, it should end up looking like the following:

>>> def say_hi(name):
...     if name == '':
...         print("You didn't enter your name!")
...     else:
...         print("Hi there...")
...         for letter in name:
...             print(letter)
... 
>>> name = input("Your name: ")
 < enter your name at this point >
>>> say_hi(name)

If you still have problems, here’s a version in my online Python interpreter, that you can run right from this page. Note that input() doesn’t work in this system, so we just call say_hi() with a predefined string instead:

Your first Python program

Analyzing your first Python program

Let’s go over the code step by step.

Asking for input with Python

I managed to cram in one more new thing, the built-in function input(). It does exactly what you expect it to do: ask for input and assign that input to a variable. If you give input a string as an argument, it will print it as a prefix. In this case, it will print ‘Your name: ‘ and wait for you to enter your name.

The say_hi function with one argument

The say_hi(name) Python function that we defined, takes one argument, the name, and prints the name to the screen. The function does not return anything. It doesn’t need to, since it does all the printing work itself.

An if .. else block

Our function only greets us if the name is not an empty string. Why’s that?

When someone just hits enter when asked for input, the input() function returns an empty string. You can check for yourself in the REPL:

>>> input()
''

Just hit enter when asked for input, and you’ll see that the call to input() results in an empty string. So to not make a fool of ourselves, we won’t greet someone showing such rude behavior. We do this by checking if the input is equal to an empty string using an if-else block.

A for loop

Finally, with Python’s for loop, we print each letter of the entered name on a new line, just because we can.

Assignment: adapt your first Python program

Since we defined a function, say_hi(name), we can reuse this function. You can repeatedly ask for a name and repeatedly call say_hi. Here’s a little assignment:

Create an infinite loop that keeps asking for names,
and that keeps greeting us using the entered name.

Hint 1: use the say_hi function from above.
Hint 2: revisit the section about loops if you need to.
def say_hi(name):
    if name == '':
        print("You didn't enter your name!")
    else:
        print('Hi there...')
    
    for letter in name:
        print(letter)

# This is an infinite loop
while True:
    # Ask for the name first using input()
    name = input('Your name: ')
    # And then call say_hi with that name
    say_hi(name)

And now what?

At this point, using the interactive Python shell starts to work against us. Chances are you’ve been fiddling a lot to get this first Python program working, mainly because of indentation issues. Luckily, we can also store our Python programs in files, as you’ll learn in the next section: creating Python programs. But before we do so, we’ll first dive into Python comments.

For now: congratulations. If you followed along, you should have a basic understanding of programming with Python. You created your first Python program! I recommend you to keep experimenting inside the REPL. You may need to re-read some or all of the sections. That’s OK and perfectly normal.

The most important piece of advice I’d like to give at this point is that you don’t learn programming by reading alone, just like you don’t become a doctor just by reading. You’ll have to get your hands dirty and practice.

If you feel ready, continue with the next chapter!

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

Related articles

18 thoughts on “Your First Python Program”

  1. Hi Eric,
    I loved your tutorial until this last topic!
    I suggest to change the name of this topic to “Your First Python Program which will not work”.
    “And now what?” – as the name of final part of this topic fits perfectly into such experience! But I’d suggest to add explanations that debugging is just part of the game and it’s normal that it could make you crazy. You have to love/hate/respect that if you wish to think like computer scientist😜😁

    Back to my case, after having the assignment done in couple of minutes I spent several hours trying to understand what’s wrong with my code – why is it not working. Anyway, it’s good to re-read the needed topics again and spend some time trying to correct the mistakes myself. But obviously, after couple of hours I gave up and opened the solution tab of that assignment. Imagine how surprised I was to find out that solution code appears to me nearly identical to my… Ok, but what exactly is wrong with my version?? Let me try to correct my version to get it working… the colour of some words doesn’t match in solution and my code – may be I couldn’t define or call the function properly? May be I forgot some special symbols, or used some small letters instead of capital, or used letters from different alphabet / keyboard layout witch only look similar?? I haven’t managed to find any of that or anything else.
    Ok, time to give up again, luckily we have it in tutorial form with the solution available – let me copy/paste the solution. And you guessed it correct – the solution itself doesn’t work too!!! Such challenges make me only more interested to figure out what’s wrong, and what exactly I do not understand (if I’m ready to spend time for that). Nevertheless, I could imagine that normal people could only lose their interest at such point, would prefer not to continue, or to make own conclusion that Python or programming itself is not for them.

    Of course, finally I found that in one of the first topics it was clearly stated that online interpreter has certain limitations and one of them is “It’s not a REPL; it’s not interactive. You can’t use input()”.
    The difference between the systems should’ve been clear already and that such assignment just couldn’t be tested online without having Python with REPL properly installed.

    Nicely hidden milestone challenge to filer-out those who are not committed enough to continue 😜🤣

    • Ahh that sounds frustrating. It is stated in a few places that input() does indeed not work inside the crumbs. I’m working on an improved version where input does work!

  2. Hi Eric!
    I used a while loop to so it can run indefinitely as long as they input a name. Thanks for these tutorials!!

    
    def inf_greeting(name):
        while name != '':
            name=input('Your name is:')
            print('Hi',name)
    
    inf_greeting(name)
    Code language: Python (python)
  3. Hello,

    I think I did not understand the assignment correctly, but this was still fun to work out:

    >>> def say_hi(name):
    ...     while name == '':
    ...             print("You didn't enter your name!")
    ...     while name == name:
    ...             print('Hi there...')
    ...             for letter in name:
    ...                     print(letter)
    ...
    >>> name = input('Please enter your name: ')
    Code language: Python (python)

    Please enter your name:
    >>> say_hi(name)
    You didn’t enter your name!
    You didn’t enter your name!
    You didn’t enter your name!

    and the other option:

    >>> name = input(‘Please enter your name: ‘)
    Please enter your name: Sergiu
    >>> say_hi(name)
    Hi there…
    S
    e
    r
    g
    i
    u
    Hi there…
    S
    e
    r
    g
    i
    u
    Hi there…
    S
    e
    r
    g
    i
    u

    and so on and so forth…

    Many thanks!

    Sergiu

  4. Hello, So I hope you don’t hate me, but I changed your assignment.
    I am day 1 on coding. like only done this for THIS tutorial.
    But I was thinking of the practicality of asking and greeting your name over and over. I did something else. I only asked if you didn’t give your name.

    def say_hi(name):
        if name == '':
            print("You didn't enter your name!")
        else:
            print("Hi there " + name)
    
    name = input("Your name: ")
    say_hi(name)
    
    while name == '':
        name = input("Your name: ")
        say_hi(name)
    Code language: Python (python)
  5. Hey Erik,

    Loving the tutorial so far! Thanks so much. 🙂
    How’s this?

    def say_hi(name):
    ...     if len(name)<=1:
    ...             print("Please enter your name.")
    ...     else:
    ...             print("Hi", name)
    ...     while True:
    ...             name=input("Your name:")
    ...             say_hi(name)
    Code language: Python (python)
      • I think I fixed it.

        def say_hi(name):
            if name == '':
                print("Enter your name!")
            else:
                print("Hi", name)
        
        name = input("Your name:")
        
        while True:
            name = input("Your name:")
            say_hi(name)
        Code language: Python (python)
  6. Hi Erik,
    Ty for this amazing tutorial!

    
    def loop_say_hi():
    ...     counter = 1
    ...     while (counter > 0):
    ...             ask = input('Please enter your name:  ')
    ...             if (ask == ''):
    ...                     print('Please enter proper name\n')
    ...             elif(ask == 'stop'):
    ...                     counter = 0
    ...                     print('Stop collecting names!\n')
    ...             else:
    ...                     print('Hi... ', ask)
    ... 
    >>>
    >>> loop_say_hi()
    Code language: Python (python)
    • Nice one Patrick. Instead of using a counter and a number, you might want to look into using a boolean. E.g. a variable called ‘continue’ that is set to True or False.

  7. I just looped the entire thing

    
    while True:
        def say_hi(name):
            if name == '':
                print("You didn't enter your name!")
            else:
                print("Hi there...")
                for letter in name:
                    print(letter)
        name = input("Your name: ")
        say_hi(name)
    Code language: Python (python)
    • Although it works, I would not recommend it. The function is defined over and over again. Also, it will only be available inside the loop. If you would want to call it outside the loop, you won’t be able to!

  8. Hi Erik,

    It is very handy and helpful learning Python using your tutorials. Kudos for you!!
    Regarding the assignment about creating a function that ask for infinite loops of names, I have written slightly modified version of the program based on your answer which uses the function back inside its own.

    Could you please comment on the program that I have written below?
    Also, I was wondering whether calling a function inside its own is efficient in this particular case?

    def say_hi(name):
    if len(name)!=0:
    print(“Hi there,”,name)
    NAME=input(“Enter your name: “)
    say_hi(NAME)
    else:
    print(“You didnot enter your name!”)
    NAME=input(“Enter your name: “)
    say_hi(NAME)

    Thanks!

Leave a Comment