Beginner Tutorial#

Approximate time ~ 2 hours

Table of Contents

Introduction#

This guide was created for complete beginners (i.e. with no programming or computer science experience) and will teach you programming fundamentals in a language called Python. Following a project-driven learning philosophy you will learn as you build your own project. There will be GIFs and screenshots throughout this guide to make everything as clear as possible.

As you complete this guide you’ll be creating a virtual pet we’ll call “PyPet” (a “Python-pet”). Remember tamagochis? (Or if you were born in the 90s then think POKEMON!) With each new Python programming concepts you learn, you will add new features to your “PyPet”.

What is Python?#

Python is a scripting programming language known for both its simplicity and wide breadth of applications. For this reason it is considered one of the best languages for beginners. Used for everything from Web Development to Scientific Computing (and SO much more), Python is referred to as a “general purpose” language by the greater programming community.

Many Python programmers (aka “Pythonistas”) love this language because it maintains a certain philosophy of best practices, described in Tim Peter’s famous “Zen of Python”. There is a large Python community both off and online that is welcoming and supportive of beginners, and you can find a plethora of additional materials in the resources section of this guide.

Part 1: Getting Started#

To get our project off the ground we’re going to get our development environment all set up and write what is essentially a “Hello World!” program – that is, one of the simplest possible programs that simply prints out a message – usually Hello World!.

Part 1.1: Replit#

To get started we’ll need a development environment, aka a place to write and execute code. For this we’ll use Replit, a fast and free way to get you up and running.

Do everything in Part 1 of this Replit Guide to get set up with an account and new project.

Part 1.2: Your first line of code#

Now we’ll write our first line of code and run it.

A. Write code in the editor#

If you haven’t already, add the following line in the editor:

The print() function in Python will print things in the console — it’s very handy for learning Python and debugging your code.

Listing 1 main.py#
1print("Welcome to PyPet!")

B. Run it#

Click the Run button. The console will output:

Welcome to PyPet!

You’ve just written your Python program!

♬♩♪♩ Happy dance! ♬♩♪♩.

Part 2: Creating your PyPet#

Part 2.1: Setting Variables#

Variables are a way of storing information in Python. We’ll use variables to keep track of information about our PyPet such as name, weight, and so on.

A. Add a variable#

Use an equals sign (=) to set a variable to a given value such as name = "Fluffy".

Create a variable called name equal to "Fluffy" (or "Spike" or "Sir   Patrick" or whatever strikes your fancy.).

Listing 2 main.py#
1print("Welcome to PyPet!")
2
3name = "Fluffy"

Variables can store different types of data. In this case, name is something called a string because "Fluffy" has quotation marks around it. (Either single or double quotes will work.)

A string is just a set of characters surrounded by quotations. For example "Bob", 'New York' or "h4ck3r". A string can also include numbers, so long as it’s in between quotes.

B. Types of data#

Let’s look at some additional data types.

Create three more variables to track age, weight and hungry.

Listing 3 main.py#
1print("Welcome to PyPet!")
2
3name = "Fluffy"
4age = 5
5weight = 9.5
6hungry = False
  • The age variable is an integer and therefore must be a whole number.

  • The weight variable is a float. Floats are a numbers that can have values after the decimal point.

  • The hungry variable is a boolean which may be either True or False.

C. Exercise#

Can you add another variable named color and give it a string value like "white"?

See the answer
Listing 4 main.py#
1print("Welcome to PyPet!")
2
3name = "Fluffy"
4age = 5
5weight = 9.5
6hungry = False
7color = "white"

Part 2.2: Special characters#

Since this is a text-based program we’ll have to get creative and use ASCII art to make a picture of your PyPet.

ASCII art is any sort of picture or diagram drawn using basic text symbols. While the simplest example is a smiley face: :-), they can get a lot more sophisticated.

Listing 5 Bessie the cow#
 _________
< oh hai.>
 ---------
       \   ,__,
        \  (oo)____
           (__)    )\
              ||--|| *

For our purposes, we’re going to go for a simple one-line picture like (=^o.o^=)_.

Choose an ASCII art animal

*

Animal

Pic

Alligator

-^^,--,~

Bat

^O^

Bear

⊂( ̄(エ) ̄)⊃

Bird

,(u°)>

B

Bunny

(\\_/)

Cat

(=^o.o^=)__

Cthulhu

^(;,;)^

Fish

< )))) ><

Bat

=^..^=

Koala

@( * O * )@

*

Animal

Pic

D

Monkey

@("_")@

Mouse

<:3 )~~~~

Owl

{O,o}

Pig

^(*(oo)*)^

Robot

d[ o_0 ]b

S

Sheep

<('--')>

B

Snake

_/\\__/\\_/--{ :>~

Squid

くコ:彡

B

Toothless

`/

B

Worm

_/\\__/\\__0>

Or make up one of your own! (^‘0M0’^)

Add another string variable containing a one-line ASCII art pic of your pet.

Listing 6 main.py#
1print("Welcome to PyPet!")
2
3name = "Fluffy"
4age = 5
5weight = 9.5
6hungry = False
7color = "white"
8pic = "(=^o.o^=)__"

Attention

Strings that contain a single quote ('), double quote (") or backslash (\) require special handling.

More info


If a string contains double quotes (") you must enclose it in single quotes to avoid closing the string early.

Listing 7 main.py#
7pic = '@("_")@'

If a string contains single quotes (") you must enclose it in double quotes to avoid closing the string early.

Listing 8 main.py#
7pic = "<('--')>"

If a string contains a backslash (\) you must use two to avoid escaping the next character.

Listing 9 main.py#
7pic = "(\\_/)"

Part 2.3: Using variables#

You can use a variable that you previously created by simply placing the name of the variable where you would otherwise put the literal value.

For example, imagine we wanted to print the name of your PyPet.

We could do it the same way we did on the first line of our program–by putting the literal string "Fluffy" inside the parenthesis of the print() function.

Listing 10 main.py#
 1print("Welcome to PyPet!")
 2
 3name = "Fluffy"
 4age = 5
 5weight = 9.5
 6hungry = False
 7color = "white"
 8pic = "(=^o.o^=)__"
 9
10print("Fluffy")

Instead we will replace the string "Fluffy" with the variable name.

Since the variable name contains the string "Fluffy" it will have the exact same effect.

Listing 11 main.py#
 1print("Welcome to PyPet!")
 2
 3name = "Fluffy"
 4age = 5
 5weight = 9.5
 6hungry = False
 7color = "white"
 8pic = "(=^o.o^=)__"
 9
10print(name)

Can you add a line to print the pic variable?

See the answer
Listing 12 main.py#
 1print("Welcome to PyPet!")
 2
 3name = "Fluffy"
 4age = 5
 5weight = 9.5
 6hungry = False
 7color = "white"
 8pic = "(=^o.o^=)__"
 9
10print(name)
11print(pic)

Part 2.4: Combining strings#

Instead of printing just the PyPet name, we are going to change our program to print the message "Hello from Fluffy".

In order to do that we’ll combine the string "Hello from " with the name variable. This is called concatenation.

To combine the two strings put the + operator between them.

Listing 13 forms the string "Hello from Fluffy"#
"Hello from " + name

Change the line where we previously printed name to add that small piece of code inside the parenthesis in the print function.

Listing 14 main.py#
 1print("Welcome to PyPet!")
 2
 3name = "Fluffy"
 4age = 5
 5weight = 9.5
 6hungry = False
 7color = "white"
 8pic = "(=^o.o^=)__"
 9
10print("Hello from " + name)
11print(pic)

Part 2.5: Documentation#

We’ve taken in a lot of information so far. Now is a good time to think about writing some documentation to make our program easy to understand when we come back to it.

A. Docstrings#

A docstring is a special kind of string that is enclosed by triple double-quotes (""") or triple single-quotes( '''). When used as the very first line in a file it is documentation for that file.

Docstrings have the added benefit of being able to span multiple lines.

Add a docstring to your program that includes a brief description of the file, and any other information you deem relevant. For example, a link to this tutorial.

Listing 15 main.py#
 1"""
 2Pypet Game
 3
 4    From the tutorial found at:
 5
 6    https://alissa-huskey.github.io/python-class/lessons/tutorial.html
 7"""
 8
 9# print to the screen by calling the print() function
10print("Welcome to PyPet!")

B. Comments#

You can leave notes for future reference starting with a #. This tells Python to ignore everything that follows until the end of the line.

Add some comments to your program describing what the code does.

Listing 16 main.py#
 9# print to the screen by calling the print() function
10print("Welcome to PyPet!")
11
12# variables
13name = "Fluffy"
14age = 5
15weight = 9.5
16hungry = False
17color = "white"
18pic = "(=^o.o^=)__"
19
20# use the name variable to form a new message
21# by concatenating two strings, then print it
22print("Hello from " + name)
23
24# print the pic variable
25print(pic)

C. Inline comments#

A comment doesn’t have to be at the beginning of the line as long as it is not inside of quotes.

Listing 17 main.py#
 9# print to the screen by calling the print() function
10print("Welcome to PyPet!")
11
12# creating variables
13name = "Fluffy"       # string: quote enclosed text
14age = 5               # integer: whole numbers
15weight = 9.5          # float: decimal numbers
16hungry = False        # boolean: True or False
17color = "white"       # string
18pic = "(=^o.o^=)__"   # string

Part 3: Getting Organized#

We need a way to tell Python that all of these values represent one pet. One way to do this is to use a Python dictionary.

A dictionary allows you to group a bunch of different values together and assign the group to a single variable. The contents of a dictionary are arranged by key, the unique identifier chosen to look up a particular value.

Part 3.1 Make a cat dictionary#

Create a dictionary called assigned to the variable cat using curly-braces ({ }).

Inside the curly-braces add a list of attributes separated by commas. Attributes have both a key (like "name", "weight", "age") as well as a value (like "Fluffy", True, 9.6), with a colon : between the two.

Listing 18 main.py#
12# variables and types
13name = "Fluffy"       # string: quote enclosed text
14age = 5               # integer: whole numbers
15weight = 9.5          # float: decimal numbers
16hungry = False        # boolean: True or False
17color = "white"       # string
18pic = "(=^o.o^=)__"   # string
19
20# dictionary
21cat = {
22    "name": "Fluffy",
23    "age": 5,
24    "weight": 9.5,
25    "hungry": True,
26    "color": "white",
27    "pic": "(=^o.o^=)__",
28}

Part 3.2: Print the dictionary#

Change the last line so that it prints out the whole cat dictionary instead of the pic.

Listing 19 main.py#
20# dictionary
21cat = {
22    "name": "Fluffy",
23    "age": 5,
24    "weight": 9.5,
25    "hungry": True,
26    "color": "white",
27    "pic": "(=^o.o^=)__",
28}
29
30# use the name variable to form a new message
31# by concatenating two strings, then print it
32print("Hello from " + name)
33
34# print the cat variable
35print(cat)

Part 3.3: Print dictionary values#

Print your PyPet’s name and pic. You can access values in a dictionary the format dictionary["key"] such as cat["name"].

Listing 20 main.py#
20# dictionary
21cat = {
22    "name": "Fluffy",
23    "age": 5,
24    "weight": 9.5,
25    "hungry": True,
26    "color": "white",
27    "pic": "(=^o.o^=)__",
28}
29
30# use the name variable to form a new message
31# by concatenating two strings, then print it
32print("Hello " + cat["name"])
33
34# print the pet picture
35print(cat["pic"])

Part 3.4: Remove old stuff#

Remove the old variables, or you can just comment them out if you would prefer to keep them for reference.

Listing 21 main.py#
 9# print to the screen by calling the print() function
10print("Welcome to PyPet!")
11
12# dictionary
13cat = {
14    "name": "Fluffy",
15    "age": 5,
16    "weight": 9.5,
17    "hungry": True,
18    "color": "white",
19    "pic": "(=^o.o^=)__",
20}
21
22# use the name variable to form a new message
23# by concatenating two strings, then print it
24print("Hello " + cat["name"])
25
26# print the pet picture
27print(cat["pic"])

Part 4: Feeding your PyPet#

Let’s “feed” our pypet using a Python function. A function is a block of organized, reusable code that is used to perform a single action.

Part 4.1: Define feed()#

First, we must define our function — feed — which changes our pypet’s hungry attribute to False to show that it is no longer hungry.

Create this simple function by writing the following above your dictionary.

Listing 22 main.py#
 9# print to the screen by calling the print() function
10print("Welcome to PyPet!")
11
12# function
13def feed(pet):
14    pet["hungry"] = False

There are a couple of things to take note of here. By writing def feed(pet): you defining a function called feed that accepts one variable pet. You”ll also notice we indent the next line pet["hungry"] = False.

NOTE: In python the contents of a function must be indented.

Part 4.2: Call the function#

Add feed(cat) below your function to use the feed function on your PyPet, in this case cat.

Listing 23 main.py#
26# use the name variable to form a new message
27# by concatenating two strings, then print it
28print("Hello " + cat["name"])
29
30# print the pet picture
31print(cat["pic"])
32
33# call the feed function
34feed(cat)

By calling feed(cat) we are passing the variable cat into the function in place of pet. pet acts as a placeholder for whatever variable we decide to pass into the function.

Part 4.3: Increase the pet weight#

We should also increase the PyPet’s weight a bit since it has eaten.

Add cat["weight"] = cat["weight"] + 1 to your feed function.

Listing 24 main.py#
12# function
13def feed(pet):
14    pet["hungry"] = False
15    cat["weight"] = cat["weight"] + 1

Part 4.4: Test it#

We’ll want to make sure it works correctly, so we’ll add some temporary debugging statements so we can see what happens.

Add a line to print the cat dictionary and a message just before and after you call feed().

Listing 25 main.py#
33
34# call the feed function
35print("Before feeding:", cat)
36feed(cat)
37print("After feeding:", cat)
38

Set or change your PyPet’s "hungry" value to True.

Listing 26 main.py#
18cat = {
19    "name": "Fluffy",
20    "age": 5,
21    "weight": 9.5,
22    "hungry": True,
23    "color": "white",
24    "pic": "(=^o.o^=)__",
25}

Look at the output to confirm that the PyPet’s hunky and weight values changed. They should be:

Key

Before

After

"hungry"

True

False

"weight"

9.5

10.5

Part 4.5: Exercises#

A. hello() function#

Exercise 1 (Hello Exercise)

Can you write a function named hello that prints "Hello World!"?

Don’t forget to call it!

B. goodbye() function#

Exercise 2 (Goodbye Exercise)

Write a function named goodbye that takes one argument name and prints Goodbye NAME!

Call it with your name.

What happens when you call it multiple times with different names?

Part 5: Making Choices#

But what if our PyPet is not hungry? We need to take into account whether or not the hungry variable is set to True or False. In order to know whether our PyPet is hungry, we are going to use an if statement.

In Python, if statements check to see whether a specific condition (such as whether or not hungry = True).

If the PyPet is hungry the program will set his hungry variable to False and increase his weight. If the PyPet is not hungry then it will print The PyPet is not hungry! in the console.

Part 5.1: Add if statement#

Add an if statement inside of your function.

Listing 27 main.py#
12# function
13def feed(pet):
14    if pet["hungry"] == True:
15      pet["hungry"] = False
16      pet["weight"] = pet["weight"] + 1
17    else:
18      print("The PyPet is not hungry!")

Notice that we use two equals sign (==) to check a condition (for example pet["hungry"] == True). Only if the condition is not met the code beneath the else: will execute.

Remember, one equal sign is used to assigned a value to a variable (pet["hungry"] = True makes our PyPet hungry), two equal signs are used to check if a condition is true (pet["hungry"] == True checks whether our PyPet is hungry).

Part 5.2: Make sure it works#

Repeat the steps from Part 4 to make sure the function still works.

Then switch to the opposite "hungry" value and check the output to make sure that the before and after values are the same.

Part 6: Making Friends#

In this section we’ll learn how to hold multiple values together in a list.

  1. Let’s create another PyPet using a dictionary. Add (or customize) the code below under your previous PyPet dictionary.

    1mouse = {
    2  "name": "Mouse",
    3  "age": 6,
    4  "weight": 1.5,
    5  "hungry": False,
    6  "pic": "<:3 )~~~~",
    7}
    

    NOTE: Make sure to place this new PyPet above your function (use the GIF as reference if you are confused)

  2. Create a list to hold both of your PyPet using pets = [cat, mouse].

    1pets = [cat, mouse]
    

    Now that we have more than one PyPet we can store them in a Python list. A list is another data type; lists stores variables in order. If Python isn’t the first programming language you are learning, you may have heard of this same concept in other programming languages as an array.

Part 7: Going in Circles#

What if we want to feed all the pets in our list? If we want to run a function on each variable in a list we can use something in Python called a loop. The for loop in Python has the ability to iterate over the items of any sequence, such as a list.

1for pet in pets:
2	feed(pet)
3  	print(pet)

Take a screenshot of your PyPet and tweet them @Thinkful so I can share your creation with the world!

BONUS#

Once you have completed the steps above, you should feel free to add additional features that you design yourself! Here are some ideas to get you started:

  • keep track of a health points variable

  • create a boolean variable for asleep

  • create a play() function

  • create a list of phrases your Python can say at random

  • get input from the user with raw_input()

Conclusion & Resources#

Congrats for reaching the end of this guide! For your convenience we’ve placed a final version of our PyPet on GitHub, if you would like to take a look at the code. If you are stuck tweet @Thinkful and we’d love to help. Feel free to customize any or all of your project and try new things.

This guide is just the beginning of what you can do with Python. If you enjoyed the work you’ve done here, go through any of the additional resources below.

Free Resources:

  • Learn Python Programming – a beginner-friendly step-by-step interactive Python course provided by Programiz.

  • The Official Python Tutorial – this tutorial at Python.org introduces the reader informally to the basic concepts and features of the Python language and system. It is not comprehensive, but rather touches on Python’s most noteworthy features, and will give you a good idea of the language’s flavor and style.

  • Think Python 2e – a book intended as an introduction to Python programming for beginners. It’s available online or as a PDF download for free at Green Tea Press.

  • Interactive Python – a 19 hour online course provided by Coursera for students with little or no computing background.

  • Real Python – a great resource for the budding developer full of articles on every Python-related topic you can imagine and then some.

Credits#

This tutorial can be found at its new home in Python Class:

https://alissa-huskey.github.io/python-class/lessons/tutorial.html

It was adapted from one that was originally available1 on thinkful.com.


1

The URL for the tutorial no longer works, but it was:

https://www.thinkful.com/learn/guide-programming-fundamentals-in-python