Py 101 Course

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 253

Build The Game

In this lesson, you'll build the game that you just played. Don't expect to
understand everything right away. You'll cover it all in detail later on. Get
ready to run your first interactive Python program on your own computer.

Note: Depending on what Operating System you are using, Python might
not be installed yet. You will handle the installation in the upcoming section.
If you don't have Python pre-installed, e.g. on Windows, you can build the
game in an online coding interface, such as repl.it.

Try not to get hung up if something doesn't work yet. The course will guide
you through all the necessary setup steps in just a bit. If something doesn't
work, then just keep reading and move on.

Building The Game

Open up any Text Editor that comes with your operating system. It can be as
simple as TextEdit on macOS, NotePad on Windows, or Text Editor on Linux:
This lesson will show you how to do it on macOS, but the steps will be very
similar on another operating system.

Code is just plain text. So, if you're using TextEdit on macOS, then you can
press Cmd+Shift+t to switch to its plain text mode. This means that you'll
deal with just text, without any formatting, such as bold or italics.

Info: On Microsoft Notepad and the Linux Text Editor you won't have to
worry about that since they open in plain-text mode by default.

After doing this, your window should look a little different and not show any
formatting options at the top:
Now it's time to write some code! Type the following code into your text
editor:

import random

num = random.randint(1, 10)


guess = None

while guess != num:


guess = input("guess a number between 1 and 10: ")
guess = int(guess)
if guess == num:
print("congratulations! you won!")
break
else:
print("nope, sorry. try again!")

Make sure you type it out as-is, including the spaces you see on the left.
Each tab space equals 4 spaces.

Info: If you are using TextEdit and you have trouble with Auto-Correct
capitalizing words, you can turn off auto-correct by unchecking Edit /
Spelling and Grammar / Correct Spelling Automatically.

When you are done, your text should look like the following:
Play The Game
Well done writing that code :) To actually play the game on your computer
you need to run the Python file you just created.

Note: If you built the game using repl.it you only need to press "Run".
Nevertheless, read through this section and come back to give it a try once
you have Python installed on your system.

To run your Python code on macOS, open up your Terminal. Press


Cmd+Space to open up Spotlight, and type Terminal, then press Enter:

This opens up the Terminal program on MacOS, which allows you to run
Python programs.

The process is very similar on Linux, where you can open your Show
Applications menu by pressing the button on the bottom left of your dock,
then type Terminal into the search bar:
This will open up the Terminal program on many Linux distributions. If you're
working on Linux, you're likely already familiar with your terminal.

On Windows, you will need to open up a PowerShell window.

Info: The process on Windows works a little bit differently than on UNIX-
based systems such as Linux and MacOS. Read over the official tutorial for
setup instructions, check your forum, or stick with running the script on
repl.it for now.

Make sure your Terminal program is open. You'll get to know it in more detail
down the road. For now, just type the suggested commands and keep going.
Start by navigating to your Desktop:
cd ~/Desktop

It will look similar to the screenshot below on your computer:

Info: Your terminal surface and colors will probably look different than what
you see here. There are a million different implementations and designs, but
the functionality will be the same. So no worries if it looks different, as long
as it works the same.

Typing this command will teleport you to your Desktop, where you saved the
file guess.py earlier on:
Now it's finally time to play your own guess-the-number game. Since you
wrote it in Python, you need to also start it using the command called
python:
Programming Concepts
There are a lot of different programming concepts that go into creating even
a small program like the game you just wrote. In this lesson, you'll take a look
at what these concepts are.

Fundamental Tools

The fundamental tools you used to write this game can on a high level be
summed up as:

Text Editor
Code
File

You used your text editor to write code that you saved as a file:
Then you were able to run that file using Python, which executed the code
you wrote and made it do its thing.

Programming Concepts

Now take a look at the code itself. Fair warning: What comes next will look
like a lot, because there is a lot going on. A Python script can be broken into
many parts, much like how a paragraph of English can consist of many
different parts:

An introductory sentence
References to outside text
Subjects
Nouns
Verbs
And sometimes new vocabulary

Like with a paragraph in English, if you are able to understand these different
parts, then it's likely that you can write and understand also another, similar
paragraph.

However, if you are just getting started with programming, you need to be
forgiving with yourself. Think of yourself like a newborn who doesn't yet
know how to understand---or form---correct sentences. That's okay! You
learned to understand language, and you can learn to understand code as
well. And it will be much easier than learning your first language :)

With that in mind, scroll down to check out this masterpiece of abstract color
squares:
Those are a lot of colored squares!!!

Don't worry if most of what you can see doesn't make any sense to you yet.
This is what's expected if you're just starting out. You'll look into all of the
concepts recorded in this image and many more during the course, and with
time and practice you will see that you will start understanding more and
more.

What is important to keep in mind for now, is that:

Programming is just writing text


You run Python programs with Python
There's fun stuff you can build :)

Ready to dig deeper? Great, keep up that motivation! But before it's time to
keep coding, you need to make sure that your computer is set up properly.
You'll do that in the upcoming section.

Recap

In this section, you saw how you can build and run an interactive Python
script right on your own computer with tools you already know. You probably
also guessed a number or two :)
Anatomy of an IDE
The Integrated Development Environment (IDE) that you'll use during this
course is called VS Code. It is free and open-source, and a widely loved IDE
among programmers. However, when you first open up VS Code it might
seem a bit intimidating:

Don't be afraid, remain steadfast, and you will get a hang of the basics soon!
Start by thinking about what you can see in this program on a conceptual
level.

There are three things you need to do when you program:

1. Write text
2. Navigate through your file system
3. Execute code files
All of these tasks can be done in just your terminal. The terminal is also
called the CLI, pronounced see-el-ay, which is short for Command Line
Interface. It's a powerful tool, and many programmers tune it specifically to
their wishes and wield it as their primary work tool.

Familiar Programs

However, working on the CLI with just a text-based interface isn't the easiest
way to get started with programming. You'll see that VS Code provides all
the same functionality, but in a visual interface that's more user-friendly to
work with.

Before decrypting your new tool, you'll revisit three programs that you
already know and that you used earlier to write and run your first game:

1. TextEdit, or any other text editing program, which allows you to write
code
2. Finder, or Explorer, which allows you to navigate through your file
system
3. Terminal, or Command Prompt, which allows you to execute your code

As you saw previously, combining the functionality of these three programs


allows you to create and run any code snippet you write. When you open up
all three programs on a computer running macOS, then it'll look similar to
this:
You could do all your software development with these three programs---
but it might get messy. For example, you'd need to keep moving the different
application windows around so that they don't get in each other's way. This
is where using an IDE instead comes into play.

VS Code

VS Code is an IDE, which is short for Integrated Development


Environment. This name attempts to describe exactly what these types of
programs are made for. An IDE integrates all the tools you need for software
development into one tool. Take another look at your open VS Code editor
window:
Compare this image to the image with the three open programs from further
up. Does the VS Code window look a bit more familiar now? You can see that
there are different parts dedicated to each of the actions you need to do
when programming:

1. Write code
2. Navigate through your file system
3. Execute code files

By understanding why you need the different parts of an IDE, and


connecting them to the conceptual understanding of other apps you may
already use, VS Code gets a lot less intimidating! And just like this, you
learned the basics of your VS Code text editor.

Info: You can change the size of each of the different parts of the VS Code
window by pulling them larger or smaller.
The Python Console
In the previous section, you went through the steps to set up your machine,
and before that, you got a quick preview of what it's like to run Python code
in different environments. Now you'll take a deeper look at how to run
Python code on your computer.

You'll use VS Code moving forward, but keep in mind that the integrated
terminal in your IDE is just that, an integrated terminal. This means you could
do any of these tasks also in your native terminal application.

The Python Interpreter

In the section on installing Python, you played around with Python's


interactive mode. This mode is also called the Python Console or Python
Shell. Using the interactive mode, you can execute Python code line by line.

As you can imagine, this approach is slightly limited: once your current
session is terminated, your work is lost forever. Bye-bye code!

On the other hand, the Python Console also has its upsides. If there's
something you don't quite remember how to do in Python, or if you want to
quickly test something before including the code in your program, it is a
great sandbox to experiment.

You can also use it as a calculator if you quickly need to add up some
expenses :)

Starting The Interpreter

You can access your Python interpreter by typing the python3 command in
your VS Code terminal window:
python3

This will launch the Python interpreter and it'll look similar to this:

Your cursor will happily sit next to the three angular braces at the end,
waiting for your input. Now you can enter any Python code you want. You'll
see the output your code produces right after you pressed the Enter key.

Tasks

Explore by playing around with your Python interpreter:

Break It: Type some gibberish and see if you can get the interpreter to
return some error messages to you. Don't worry, you won't break
anything. Which error messages or exceptions can you produce?
Calculate: Try to do some math calculations. How would you expect to
add, subtract, multiply, divide, etc. some numbers? Take a guess and
punch it in. Does it work? Can you find any new error messages?
Explore: What else could you try to do in here? How would you attempt
to print out your name, for example?

Exiting The Interpreter

To get out of this magical universe, you just need to type the super-secret
passphrase exit(), and press Enter:

>>> exit()

The Python snake allows you to leave its grip and you're transported back to
your normal CLI interface. Bye Python!

Remember that all the calculations you made, any variables you declared,
and the beautiful errors you ran into won't be available anymore:

They won't be back to greet you if you open up a new session. This is why
the Python interpreter is not the best tool if you want to write more complex
programs.

Recap

The Python interpreter is also called the Python Console or Python Shell.
It's an interactive Python environment that allows you to write Python code,
get it evaluated, and see the results on a line-per-line basis. The sessions
are not saved, so when you exit you can consider your calculations lost.

The Python interpreter is useful for experimentation and quick testing. For
building more complex programs that you want to keep around you'll instead
write a Python script. You'll learn about how to do that in the next lesson.
Python Scripts
Another way you can run Python code is by executing a script. Python
scripts start execution at the top of the file and proceed line by line until the
end of the file is reached or the program is terminated in another way.

This way of programming is called procedural programming and it's what


you'll do throughout the first module of this Python course. Python is a very
versatile language, and you'll later learn different ways of programming while
sticking with the same language.

Create A Python Script

In order to run a Python script, you need to save your code with a .py file
extension. This tells your computer that the instructions in that file should be
executed with Python. You already saved a file containing Python code with
that file extension when you built the guess-the-number game. Time to give
this process another go, this time using VS Code.

Start by creating a new file by going to File / New File or using your operating
system's keyboard shortcut. Save this new blank file as first_script.py.
You can save the file on your Desktop, or in any other location. Just make
sure you know where it is and how to find it.

Inside this .py file, write some Python code. Keep it short and concise by
printing out some text to the console:

print("hello world")

After you typed this code into your empty file, make sure to save it!

Info: To make your life a little easier, turn on VS Code's auto-save option by
checking File / Auto Save in the VS Code context menu.

Run The Script With A Command

Now switch to the terminal part of your VS Code window. You can run your
new Python script using the python3 command:

python3 first_script.py

The above command will only work if your terminal points to the folder where
you saved the first_script.py file. If you saved it on your Desktop, you can
make sure that your terminal points to your Desktop by typing:

cd ~/Desktop

This command will change the directory to the Desktop of your current user.

Info: The cd command on UNIX systems stands for change directory and
allows you to switch to different locations with your terminal. The tilde
symbol (~) is a shortcut reference for your user's home directory. Therefore,
this command means change directory to the Desktop of my current user.
Check out the Bash Basics course if you want to learn more terminal
commands. The tilde shortcut should also work on Windows PowerShell.
Alternatively, you can navigate to your home directory by using the $HOME
variable.

After you made sure that you are in the directory where you saved the
Python script, you can execute the file with the python3 first_script.py
command mentioned further up.

However, sometimes you won't exactly know where you just saved a file, or it
might get too tiring to type out long paths in your terminal just to run your
script. VS Code has a solution to this!

Run The Script With A Button

VS Code makes running your script even more user-friendly. You won't have
to remember any paths or type commands into your terminal. All you need to
do is press Run:

The green triangle button in the top right of your VS Code window runs the
current file and shows you the output in your terminal. It's really just a
shortcut to doing what you did manually before. When you hover over the
button, you'll see that it's called Run Python File in Terminal, which is exactly
what it does.

It's an extremely common action to run your script while you're in the
process of developing it. You want to know what its current outputs are,
whether it works as expected, and if it doesn't, what might be going on.
Therefore it's very helpful to be able to quickly run your script with just the
click of a button.

Recap

A Python script is Python code saved to a file that has the file extension .py.
Scripts are useful when writing more complex programming logic and when
you also want to keep your code for later use.

Saving your code in a script allows you to run the code multiple times, make
updates, and continue this iteration until you have a functional program.
Most of the code you will write throughout this course will be saved as a
Python script.

As you have seen, there are three steps to running your Python code from a
script:

1. Write your Python code


2. Save it in a file with the .py extension
3. Execute the script using CLI commands on your terminal, or the Run
button in VS Code

In the next lesson, you'll create a new folder for your course documents and
download the exercises that you'll use to train your programming skills
throughout the course.
Create Your Folder Structure
As a software engineer, it is helpful to know where everything is on your
machine. Make it a habit to download and save things into specific
directories. This will reduce the time it takes you to find files and folders
before you can even start to work on your project.

Good organization is one of those little details that show how comfortable
someone is in general with the work they're doing. A seasoned programmer
can open up their CLI and immediately move into the proper directory to
start working on the task at hand.

To start you off on the right foot, you'll set up a workspace that will contain
all your work for this course. That way you will always know where to find
your work.

Go to your personal Documents folder


Create a new directory named codingnomads
Inside the codingnomads directory, create two new directories:
1. resources
2. projects

Place all your coursework in the codingnomads directory, or into one of its
sub-directories. You can create as many new directories as you choose, and
re-order the ones you just created. Just try your best to stay organized
throughout the course. You want to just know where your files are without
having to fumble around and guess every time.

On the next page, you will be prompted to download the programming labs
for this course. You're trying to stay organized, so download the file and
place it in your codingnomads directory.
Get Your Lab Exercises
All ready to get started? Great! Download your coding exercises, also called
labs, and you can start coding!

Info: You can download your Python labs here.

If you haven't done so before, create a new folder in your personal Documents
folder that you call codingnomads. Then, move the downloaded file from your
Downloads folder into your codingnomads folder. Finally, unzip the folder by
double-clicking it.

You should see a new folder that contains all your labs:

You won't need the .zip file anymore, which means that you can delete it.
Now take a look inside your new folder. It contains a bunch of folders relating
to the different course sections. Each of the folders contains Python files
that are your coding exercises for the respective sections.

Recap

The folder you downloaded contains the exercises you'll work on to train the
concepts you'll learn. Completing these labs will practically train your coding
skills throughout the course.

Info: Work hard on completing all the labs. You'll get stuck. You can pause a
hard lab and come back to it later. Take breaks, and keep working through
the course materials. But make sure to give each lab an honest effort.
Training your programming skills through completing exercises and building
projects is one of the best ways to learn!

This completes all necessary setup steps. You're now ready to dive into
learning Python. In the next section, you'll get a quick overview of what
programming even is on a high level, and then you'll start learning about
Python variables, data types, and code logic.
Introduction
You've seen some programming in action, and you might already have a
good idea of what it is and why you'd want to learn how to do it. But before
moving ahead, take a step back and think about this:

What is programming?
Why would you care?

On a high level, programming is writing instructions for your computer.


Computers are amazingly effective at doing some things and surprisingly
ineffective at others. What's exciting about knowing how to instruct your
computer to do things for you, is that:

Computers are precise


Computers are fast
Computers don't mind repetition

All of these are aspects of work where you as a human won't shine like a
bright light in the dark night. Humans are imprecise and slow, and while
some repetition might be nice, we often become even more imprecise when
we have to do the same tasks over and over again.
But as a human, you're great at having ideas and conceptualizing solutions.
And as you can see, your computer is great at executing these tasks. Sounds
like a match made in heaven? Well, the only thing you need for this symbiosis
to work, is a common language. That's where learning a programming
language comes in.

Procedural Programming With Python

In this first module of your Python course, you'll learn the basics of using
such a shared programming language. Python is a great choice for getting
started because it has a relatively intuitive syntax that is similar to the
English language.

While you'll need to slowly ramp up to make your computer do awesome


tasks for you, you'll already build some useful programs in this first module:

You'll build another text-based computer game


You'll build a script that automatically moves files of one type to a new
location

You'll also get to know a big chunk of the fundamental concepts of


programming in general, and the fundamentals of Python in particular.
Among other things, you'll learn about:

Code comments and pseudocode


The print() function
Declaring variables in Python
The int, float, None, str, and bool data types
Working with collections
Operators in Python
Conditional statements
for and while loops
Loop keywords
User input
String formatting
Modules and packages in Python
The pathlib() module

You'll get to know these concepts step-by-step as you need them, and you'll
use them to build creative and useful projects, and automate repetitive tasks.
Scripting for Automation
One area where Python is used a lot is scripting for automation. The
reasons for that are primarily that it's a language that is approachable and
also for people who might not be software developers in their main
profession. Yet, it is very powerful and can help you to automate many
common tasks on your computer.

You might have worked with spreadsheets in one of your jobs.


You might have spend hours organizing and manually renaming your
extensive .mp3 collection.
Or you might even have some programming experience in a different
language, but you need a quick way to build some workflows that
connect multiple APIs and work across different devices.

All such tasks are highly repetitive either in time or in scale. Applying some
level of automation to them will save you a couple of minutes of your
precious time each day.

Python is a great language for writing such automation scripts, and by the
end of this module, you'll have the necessary knowledge to build scripts that
can make your digital life a little more efficient.

Automate Something

Take a moment to think about a repetitive task that you do on your computer.
Get your notebook and write it down. Wouldn't it be great if you could let
your computer take over and handle it for you?

If you already have an idea for a task you'd later like to automate, great!
Otherwise, keep the thought in mind while you work through this course
module. By the end, you might be able to build it out already.
But right now it'll probably feel quite daunting and you won't know where to
start. This is what your course is for, so just keep clicking ahead and you'll
get there eventually, one small step at a time :)
Planning with Pseudocode
It can feel challenging to start off writing a script when you don't know much
about programming yet. Where to start? What to do? And how did this thing
work again...?

Feeling a little lost at the start is completely normal, and there is a trick that
can help you get started easier: use Pseudocode.

Pseudocode

Writing pseudocode is a great way to organize your thoughts and plan out
the functionality of a piece of code that you want to write. Pseudocode is a
step in-between your ideas and functional code. To write it, you open up a
new Python file and start typing out your ideas, each new line prepended
with a hashtag #. This is the normal syntax for a Python code comment, and
you will learn more about them further down.

Before you write some code, try to write some pseudocode. For example, if
you wanted to build a script that greets each of your friends, you could write
pseudocode like so:

# Collect the names of my friends


# Define how to greet them
# Greet each of them with a message on the console

Training to formulate your ideas in pseudocode will help you to break down
ideas into smaller tasks that can be tackled by writing code. Your
pseudocode can help to get you organized and keep you focused on the
task at hand. And breaking down your ideas into smaller steps also makes it
easier to get started at completing each of the necessary tasks.
Info: When you are starting to write a new script, your first step should be to
take notes in pseudocode about what you want the functionality to be, and
what the different tasks are that you can break your idea down to. This
doesn't have to be perfect, and nearly always won't be. That's okay! You're
making the task of writing the code a little bit easier.

In this lesson, you'll go over the process of turning an idea into pseudocode
and finally into functional Python code. In the process, you'll create a script
that greets a list of your friends.

Python And Pseudocode

One aspect that makes Python a great language to get started with
programming, is that it reads similar to everyday English. And once you get
some training with pseudocode, you'll see that Python is even more similar
to English pseudocode.

Look at the example below, and don't worry that you don't know anything
about Python yet. Just read the following text as if it was an English
sentence:

friends = ["Alex",
"Babette"]
greeting = "Hello"

for name in friends:


print(greeting, name)

This valid Python code snippet could be read as:

My friends are Alex and Babette. The word "Hello" is a greeting. For each
name in the list of my friends, print the greeting and their name.

Even if you haven't read the code similarly to the sentence above, you might
see some connections between the two. Python uses a relatively
straightforward syntax that makes coding much easier if you understand
English.

From an Idea to Pseudocode to Python Code

Now bring back the example idea from above and see how you could
develop your script from an idea to an idea that is broken down into steps
that you noted as pseudocode, and finally into the functional Python script.

Start with the idea and write it down in your notebook:

I want to build a script that greets each of my friends

Next, you open up a Python file and break down the steps you can think of
using pseudocode in code comments:

# Collect the names of my friends


# Define how to greet them
# Greet each of them with a message on the console

Then you go ahead and complete each of the small tasks that you gave
yourself. You can do this right under the line of pseudocode that you added
in the previous step:

# Collect the names of my friends


friends = ["Alex", "Babette"]
# Define how to greet them
greeting = "Hello"

# Greet each of them with a message on the console


for name in friends:
print(greeting, name)
Following this process can help you to organize your thoughts, break them
into smaller pieces that you can tackle, and keep you on track while writing
your code. With more experience reading and writing Python code, you
might see that Python itself sometimes reads similarly to pseudocode,
making that final transition much easier than in some other programming
languages. So much so, that there are memes making fun of this transition:

Of course, in reality, it isn't quite as easy as changing a text file containing


pseudocode into a Python .py file to get a functional script. But the meme
expresses the feeling that sometimes Python code can seem so intuitive,
that you might think that it could be possible to just write an English
sentence, and let Python take care of the rest :)

Recap

Breaking down your ideas for a Python script into small steps, and
formulating these steps as pseudocode, makes it easier to get started
writing functional code. You can use code comments to create your
pseudocode right inside the script you are working on, and then tackle each
item step-by-step.

In the next lesson, you will learn a bit more about what code comments are
and why you will want to use them.
Code Comments
In the previous lesson, you learned that writing pseudocode can help you
organize your thoughts and prepare yourself for writing code. You could
write pseudocode anywhere, but you read that it can be helpful to have it
right inside the file where you will write the code.

To make that possible, you have to write them as code comments, with a #
at the beginning of the line. You'll learn more about code comments in
Python in this lesson.

Why Use Code Comments

Code comments are exclusively for humans to read. Python completely


ignores them. If you'd write your code only for a computer to execute, there
would be no use for them at all. However, you nearly always write your code
for humans.

You already learned that keeping track of your tasks with pseudocode can
help while building a script. But there is more! While humans won't be the
ones who execute the instructions, it's humans who do all the rest:

Understand: Humans have to be able to understand what's actually


going on conceptually
Maintain: Humans are the ones who need to maintain functionality over
time and code changes
Improve: Humans will try to improve what's there
Extend: Humans will build on top of your code to create additional
functionality
Debug: Humans are the ones who dig into your codebase to fix bugs
that come up inevitably

Writing descriptive code, as well as code comments where appropriate, is


an important part of programming. You will learn more about what it means
to write descriptive variable names in an upcoming lesson.

How To Write Code Comments

A basic Python code comment begins with a hashtag # and ends with a new
line. This means that anything in a line that comes after a # will be part of a
comment, and therefore be disregarded by Python.

The following example shows a block comment followed by an inline


comment:

# This whole line is a block comment


note = "This part is real code" # And the rest is an inline comment

Generally, it is encouraged to write block comments rather than inline


comments, unless the comment is extremely short. The pseudocode you
wrote in the previous lesson was written as multiple block comments.

Recap

Writing code in a way that is easily readable should be your prime objective
when writing code. Roaming online, you will encounter suggestions to
"optimize" your code by choosing one-letter variables and decreasing the
lines of code used in a script. However, a few milliseconds of a speed
difference when executing your code rarely make a decisive difference.
Instead, what does often make a difference are the hours and hours of
developer time that can be saved if the code is well-written and easy to
understand.

Here are the key takeaways to remember:

Human-Focus: Code comments, as well as code style, are for humans


only. But that doesn't make them less important!
Rationale: Comments Tell You Why code was written in the way it was,
rather than how the code does something or what it does.
Descriptiveness: What the code does, and how it accomplishes it,
should be self-explanatory through well-written code and descriptively
named variables.

Think of your code as an essay and try to make it as pleasant to read as


possible.

Info: You will learn more about variables and descriptive naming in a later
lesson.

It is likely that either you or someone else will read your code later on. They
will need to make sense of it. Keep that in mind while writing your code, and
adopt good habits right from the beginning.

Additional Resources

Zentut: Python Comments


Digital Ocean: How to Write Comments in Python 3
The Pass Keyword
You learned about code comments in the previous lesson. Now you'll learn
about your first Python keyword! Python has a number of keywords that are
part of the language and have special meanings.

You'll start with a fun one, pass, which doesn't do anything. Lazy, right? :)

The pass keyword is generally used as a placeholder while building out your
code functionality. You might see that it sounds a little similar to a code
comment. However, it's actual code that Python executes. It just doesn't do
anything. So why would you need it?

Python doesn't do anything when it encounters the pass keyword, but


execution can continue. Sometimes that means that Python won't throw a
syntax-related error that would come up if you hadn't used pass.
Note: Here comes some more code that won't mean anything to you yet.
Keep your open Zen mindset and let it flow over you in peace and stillness.
Just focus on the concept of the pass keyword, all the rest will come with
time.

For example, if you are planning to build a for loop but don't quite have the
functionality figured out yet. You could use a mix of code and pseudocode
and write something like this:

user_input = input("whisper something: ")

for char in user_input:


# Make each character uppercase
# So that the program SHOUTS back at the user

print("ssssshhhh!")

You might understand the intended functionality of this code snippet, or


maybe not. It doesn't matter for the purpose of thinking about the concept
of the pass keyword.

In any case, this code isn't quite finished yet. There is already some
functionality coded up, while other parts are just described as a code
comment. You might want to test the existing functionality before filling in
the gaps. For example, does the user input work as expected?

However, if you would run this code as-is, you'd get an error:

# OUTPUT
File "your-file-name.py", line 4
print("ssssshhhh!")
^
IndentationError: expected an indented block
You'd receive this error because you did something that goes against a rule
in the Python language. Don't worry, there are no repercussions! No fines, no
jail time, just some feedback from your buddy Python telling you that you did
something that was confusing.

Info: In case you're wondering, the specific reason you're receiving an error
is that you opened up a loop body for a loop, but then you didn't write any
actual code there. Python expects at least some code inside the loop body,
otherwise... why would you make it? Poor Python just doesn't get it...

To avoid confusing your friend Python, you can put the pass keyword into the
body of the loop:

user_input = input("whisper something: ")

for char in user_input:


pass
# Make each character uppercase
# So that the program SHOUTS back at the user

print("ssssshhhh!")

Because pass is actual Python code, and not just a code comment that
Python automatically ignores, this construct sticks to the rules and keeps
Python happy and relaxed.

Python sees the pass keyword and understands that this is a valid for loop
construct. It also understands that it just shouldn't do anything here right
now.

Using pass in this scenario makes it possible for you to double-check the
code you already wrote, then later move on to building out the functionality
that's still missing.

Recap

pass doesn't do anything, but it is code, not just a code comment. This
means that Python reads it and understands that it shouldn't do anything
right there. Because of that, you can use it as a structural placeholder while
planning and building out your code functionality.
The Print Function
Enough with the pseudocode and keywords that are code but actually don't
do anything! After all, you want to learn to program so that your code can do
something.

You've already seen Python in action in previous sections of this course. In


this lesson, you'll revisit one of the Python functions that you'll use very
often: print().

Info: Don't worry about what exactly a function is. It's enough to know that it
makes Python do something.

print() is how you can write anything to your console using Python. You've
seen it before, but because it's such an essential and useful tool, it deserves
to get some more of your attention.

Throughout this course, you'll use print() to:

Display messages to yourself and your users


Show information about your programs
Inspect your code and find possible errors

You can print anything that has a value in Python. You do so by placing the
value you want to see in between the parentheses (()):

print(42)
print("hello world")

The correct way to say this in programming terms is:

I'm passing the value 42 as an argument to the print() function.


You can pass values directly, as you did in the example above, or you can
pass a variable that points to a value. You'll learn all about what variables are
in the next section.

Tasks

Write a script that uses print() to display some messages to your


console.
What happens when you try to print 42 with quotation marks?
What happens when you try to print hello world without the quotation
marks?
Can you perform a calculation inside of print()?
How many different error messages can you manage to get? Are they
helpful?

print() is a versatile function that you'll use often in this course. You'll need
it when you want your scripts to show you some output---which is very
often!

Scripts Vs. Interpreters

You might have noticed that there was no need to use print() to display
your output when using the Python interpreter. This is because it's set up to
execute line-by-line and show each output automatically.

However, when you are building Python scripts, they'll only give output to
the console when you use print().

When you encounter Python code snippets in the course materials moving
forward, they'll sometimes be shown without print(), to make them easier
readable:

5 + 5 # 10
If you are executing your code with a script, you'll need to pass the code to
print() in order to confirm that you get the same output, in this case, 10. If
you see a code snippet like the one above, make sure to run it like below in
your scripts:

print(5 + 5) # 10

If you execute the code in an interpreter, then you won't have to add print()
to see the same output.

Recap

print() is a Python function that you can pass any value to that you want to
display on your console. It's frequently used to communicate information to
users, show the state of your program, and help you as a programmer with
debugging your code.

If you execute code in the Python console, then it displays the output right
away. If you want to display some output from running a Python script, then
you need to use print().
Building Blocks
In the previous lessons, you learned about code comments, the pass
keyword, and about print(). You can think of them as building blocks for
your Python programs. From a zoomed-out perspective, programming is the
practice of assembling different building blocks to form a cohesive structure.

You can build an impressive amount of different structures with just a few
different types of building blocks.
There are a lot of different building blocks, but you can also group them into
a few categories to make them easier to understand. In this course, you will
learn about the different building blocks from a practical perspective.

Why practical first? Think of LEGO sets. Most people would prefer to create
a structure---instead of studying all the different blocks that exist first.

In the same way, this course aims to get you to build stuff from the get-go.
You'll learn about what the blocks are that you're using when you need to
know more about them. This approach to learning is supported by many
influential voices in education as being most effective for most people.

You already followed that process once when you built the guess-the-
number game earlier on. Over the next sections, you'll learn about some of
the background that went into building this game. There will be a bit of
theory, but you'll get to apply it in practice as soon as possible so that you'll
get your computer to do fun and interesting work for you.

Additional Resources

Blog Post about David Perkin's famous book: Making Learning Whole
Essay by Paul Lockhart: A Mathematician's Lament
Python Variables
In this lesson, you'll learn about what a variable is in programming.

Info: To be able to talk about anything precisely, you need to refer to it with a
name. That reference is what a variable is in programming. It is a name for a
value.

Here comes a weird example. Start off by picturing some kind of writing
table:

Next, go ahead and give a name to this table. For example, you could call it
"Grandpa". After your conversation partner understood that Grandpa is your
name for this writing table, you can now go ahead and say:

"Please put the papers over there onto Grandpa."

Or you could say:

"Looks like Grandpa has gotten messy. Can you please clean Grandpa?"

Even if that sounds pretty weird, anyone who is in on the joke would
understand such a request and know how to correctly interpret it. The
situation works out because they know that when you say "Grandpa" you are
referencing the writing table that you showed them before. By showing the
picture and giving it a name, you established a reference:

That process of pointing a name to a value is essentially what variables are in


programming. Threading this weird example back into programming terms,
you could say:

Grandpa is your variable


The table is your value

And looking at it in Python code, establishing the connection between the


two, also called the variable assignment, goes as follows:
grandpa = "table"

Note: This is a bad example of variable naming in programming. In general,


you'll want to be as descriptive as possible to avoid confusion when you
read over your code at a later time. A much better variable name for this
table would therefore be table.

After executing the line of code shown above, you can now reference the
value of your variable throughout your program. Go ahead and recreate the
requests from further up, this time using Python code and a reference to the
table:

print("Please put the papers over there onto " + grandpa)

If you correctly assigned the variable grandpa to the string "table", then
running this line of code will output:

# OUTPUT
Please put the papers over there onto table

Alright, it's not the best English sentence you ever wrote. But you
successfully assigned a value to a variable and referenced that value through
the variable using Python code. Nice work!

Recap

Variables are references that point to values.

Tasks
Using the code playground below, print the following text without ever
writing the word "table":

Yesterday at the dinner table my dad asked me, 'are you even
listening to me?'

Weird way to start a conversation if you ask me.

Congratulations! You just assigned your first value to your first variable. In
your future as a programmer, there are many thousands of variable
assignments to follow.

Remember that naming your variables descriptively is a practice you should


try to get used to right from the beginning. Many programmers keep
struggling with descriptive variable naming throughout their careers. In fact,
it's so common, that there are a bunch of jokes related to variable naming,
for example:

There are only 2 hard problems in computer science: cache invalidation,


naming things, and off-by-1 errors.

So keep in mind to never name your Table object Grandpa, and once that's
anchored in your brain, you can move on to the next lesson where you'll
learn more about how to handle variables in Python.
Variable Assignment
After getting a high-level idea of what a variable is in programming, you'll dig
a little deeper and learn about:

How you can assign variables in Python


How to speak about what you are doing when you do that
What naming rules and conventions to follow

This lesson will cover the most important concepts about Python variables
and variable assignment.

Variables and Variable Assignment

On a more technical level, you can think of variables as reserved memory


locations in your computer that store values. When a variable is assigned to
a value, space in memory gets reserved for that value.

To store a value, you use the assignment operator (=):

number = 5

Using proper programming speech to describe this process, you would say:

I am assigning the value 5 to the variable number

By assigning a value to the variable number, you can later retrieve the value
by using the variable's name, number. Variable names are a combination of
characters---and there is a common naming convention for Python that
you're encouraged to follow!

Variable Naming Rules and Conventions


Some of the naming conventions are really just conventions that are here to
make it easier to communicate your code and read your own and others'
code in the future. There are some rules, however, that are required for your
code to run properly.

Here is a short description of both the rules and conventions for variable
naming:

Rules

Following these rules when naming your variables is necessary to build a


functional Python script:

Start With a Character: Your variable names can include numbers, but
they can't start with a number.
Don't Use Spaces: A variable name can't include any whitespace. It
has to be one consecutive word consisting only of characters, numbers
and underscores.
Avoid Reserved Keywords: There are some words that have a specific
meaning in Python. You therefore can't use them as variable names. You
will learn more about them in an upcoming lesson.

If you break any of these rules, Python will let you know immediately with a
SyntaxError.

Conventions

Following these conventions is best practice and will make your code easier
to read, understand and debug. Breaking these conventions won't break
your code, but you should still try to stick to them as much as possible:

Use Lower-Case: Python variable names should be written in


lowercase. It has a specific meaning if a variable name is not written in
lowercase. Therefore, unless you know exactly why you need to, you
should always use lowercase for your variable names.
Use Snake Case: When you use longer variable names that consist of
multiple words, you should separate the words with underscores (_).
This helps to improve the legibility of your code. A valid snake-case
variable name could look like this: snake_case_variable.
Use Descriptive Names: Always try to name your variables as
descriptively as possible. Your code will be much easier to understand.
Code you find online will often include one-letter variables such as x.
There are some situations where this makes sense, but in general, it
pays off to be detailed and descriptive with your variable names.

Following these guidelines and requirements right from the beginning will
help you to build good habits when writing Python code. This makes reading
and maintaining your scripts so much easier. Your collaborators will like you
more, and also your future self will be thankful if you follow these guidelines.

Info: There's more to proper naming. If you want to dive deeper, check out
Python's PEP-8 naming conventions.

What you have just read about represents the most common way of
assigning values to variables in Python. With this knowledge screwed tightly
into your mind---you're set! There is, however, another way of assigning
values to variables that can sometimes speed up your development a tiny
bit.

Multiple Variable Assignments

Python has a trick that allows you to assign multiple variables in one go. It
works almost the same as the standard variable assignment you used above:

start, end = 0, 100

This line of code assigns the variable 0 to start and the value 100 to end.
While using multiple variable assignments is okay in the example above,
there's a fine line between when it's useful and when it makes your code
harder to read.

Generally, you should only use it for data that is closely related, such as a
start and end value of a progress bar for example.

You should not use multiple assignments if the data you're assigning isn't
closely related, for example:

counter, price = 0, 123.45

In this code snippet, you assigned the value 0 to counter and 123.45 to
price. But it's unclear whether these two variables have anything to do with
each other, they're not inherently related. Also, the values are more
complex than in the previous example.

To keep your code as clear as possible, it's better to use two separate lines
in this situation. Doing so makes your code better readable and easier to
understand:

counter = 0
price = 123.45

Readability is everything when writing code. Always optimize your code for
making it easier to understand, rather than using as few lines or characters
as possible.

Recap

Python has rules and conventions for naming variables. You need to stick to
the rules for your code to work:

Start with a character


Don't use spaces
Avoid reserved keywords

You should also follow the conventions to make your code easier to read.
That means writing lowercase variable names using snake_case and sticking
to descriptive variable names.

Now that you've learned how to assign values to variables, and that you read
about the different rules and conventions to follow, you'll look at the reserved
Python keywords that you can't use as variable names in the next lesson.
Reserved Keywords
Python reserves a set of keywords that you can't use as variables names.
Think of them as the vocabulary of the Python language. You can't assign
your own meaning to these words, because they already have a specific
meaning. If you would go ahead and change their meaning, then you
couldn't effectively talk with your computer anymore. Python reserved these
words to be able to correctly interpret the meaning of your code, which is
why they are called reserved keywords.

Below comes a list of all these keywords as per Python 3.8. You will cover
many of these keywords later on. For now, just skim over them, remember
that they exist and that you can't use them as variable names:

None
False
True
and
as
assert
async
await
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield

Of course, this list is long, and way too long to have fun remembering any of
it when you're just getting started with programming. Luckily, Python is
constantly aware of all these keywords because it needs to be in order to
correctly interpret your code. This means you can always ask Python if you
want to know what the reserved keywords are.

Check For The Keyword List

To bring up a list of all keywords in Python, you can ask Python for help() in
regards to them:

help("keywords")
If you run this command in your Python interpreter, you'll get a full list of all
Python keywords as your output:

Here is a list of the Python keywords. Enter any keyword to get more help.

False class from or


None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not

These are the same keywords as the ones you saw further up. They're
always available at your fingertips with running just a single command.

As you see, there's no need to remember this list. Instead, you can just
remember how to find the list. The concept of externalizing the need to
memorize to computers, and getting better at knowing how to access that
knowledge, is an important pillar of programming today.

Info: In programming it is often more efficient to understand processes


conceptually and look up the details only if necessary

Learn About Individual Keywords

Reading through that whole list to learn about a single word still sounds
rather inefficient. From the helpful message at the top of the output from
running help("keywords"), you see that you can also dive deeper into any of
the individual keywords by passing one of them into help():
help("False")

Running this command with any of the listed keywords will give you a lot of
informative text output that you can read and study:

Help on bool object:

class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of the class bool.
| The class bool is a subclass of the class int, and cannot be subclassed.
...

When you're done reading, you can quit this wordy and informative manual
by pressing the q character on your keyboard.

Over time, some of these keywords will become quite familiar. A few might
stay more obscure. Don't worry about it, and keep in mind that you can
always check back on this list by asking Python for help() with a single line
of code.

Additional Resources

If you want to dive really deep and learn more about Python keywords, read
this excellent article called The 35 Words you need to Python.

Now that you have learned about how to assign values to variables, and
encountered some of the words to avoid when doing so, you'll next look at
how you can update a variable so that it points to a different value.
Variable Updates
The Python programming language is dynamically typed, which means that
you can change the value of a variable after you defined it.

Info: Conversely, in statically typed programming languages you can't


change the value of a variable after assignment. There are advantages and
disadvantages to both designs.

Dynamic typing is also sometimes called duck typing. This term comes from
the phrase "If it walks like a duck and it quacks like a duck then it must be a
duck. Sounds logical---but maybe also slightly out of place in a
programming context? Click the link on the quote above if you want to learn
more.
In a nutshell, dynamic typing means that if you make a variable assignment,
such as number = 2, at the beginning of your code, you can change number
to a different value, e.g. 1889. You can even change it to point to a value of a
different type, such as the string "hei there buddy!".

Info: You will learn more about different data types in Python in an upcoming
lesson.

Updating the value of a variable is done by re-assigning the variable name to


a different value, like so:

duck = 2
print(duck) # 2
duck = 1889
print(duck) # 1889
duck = "hei there buddy!"
print(duck) # "hei there buddy!"

Throughout the lifetime of your short program shown above, the variable
duck pointed to three different values! Note that the print() functions are
just here to check up on the intermediate values of duck.

Recap

Variables in Python are dynamic, which means that you can change what
data they point to after you assigned them.

Dynamic typing presents advantages for writing your code quicker. However,
it also means that you need to take care since you don't want to accidentally
change the value of a variable that you're using in your program. This could
lead to all sorts of strange surprises!

In the next lesson, you'll learn about what these types of data are that
you've read about here and there.
Data Types
In the previous lesson, you saw that you can dynamically change the value of
a variable in Python. 1 can turn into 2, but it can also turn into "Something
Completely Different":

num = 1
num = 2
num = "Something Completely Different"

All of these values are different from each other, but you might agree that 1
and 2 are more similar to each other than "Something Completely
Different". What 1 and 2 have in common, from Python's perspective, is
their type. Both of them are numbers, or more precisely, integers.

Info: Python doesn't think of numbers as "numbers", but instead


distinguishes a few different types of numbers. The most common ones are
integers, such as 1, and floats, which you can think of as decimal numbers,
e.g. 1.23

The text "Something Completely Different", on the other hand, is not a


number. Sequences of characters that make up words and text share a type
that is called string in Python.

Type Checking

While you might correctly guess the type of the example values above, doing
so can be tricky in other situations. For example, what if all you get to see is
the variable name: num?

Just by looking at it, you have no way of correctly inferring what value this
variable holds. Therefore, you also have no way of knowing what type that
value is. Luckily, there is a concise way of asking Python for the type of a
variable:

type(num)

When you execute this in your Python interpreter, it'll show you the Python
type of the value that this variable is pointing to.

Tasks

What type would the variable num hold after you ran the two code snippets
above?

Change the example from the top of the page slightly and experience
Python's type checking in action. Use the type() function like in the first
example to check each variable's type:

num = 1
number = 2
text = "Something Completely Different"
# Use the type() function to check for each variable's type, e.g.:
print(type(num))

As you can see, two of them share the same type, while one has a different
type. Two are more similar to each other than they are to the third one. You
can think of them as being grouped into different types.

Type Operations

There are certain advantages that come with grouping values into types. In a
nutshell, it allows you to perform shared operations on values of the same
type. You will get to know about the different operations that you can
perform on different data types in much more detail. A lot of them might
already make sense to you because you have used them outside of
programming in a similar way.

Tasks

Think about what operations---or use cases---you might expect related to


the following types:

Numbers
Text

Think about them outside in other contexts than programming. Write down
your thoughts in your notebook.

When you think of numbers, you might think that you can, for example, add
them together. Or you could perform other mathematical operations with
them. When you think of text, you might think that you can change the
capitalization, find a word in a text, or use it to display important information.

And indeed, a lot of this functionality translates right into programming, but
there is also more on top of that! And there are other types that don't feel
quite as familiar from experiences in the real world.

Below you can see the names and type representations of some of the most
commonly used data types in Python:

Integers: int
Floats: float
Strings: str
Booleans: bool
Lists: list
Dictionaries: dict

There are even more than that, and later on, you will be able to create your
own types as well. However, with a good handle on the above-mentioned
types, you will be able to fly very high with your Python skills. You will learn
more about all of them---plus some others---throughout this course.

However, before you'll go there, you'll start with a special case. You'll start
with Nothing.

Additional Resources

Official Python documentation on Built-in Types


Nothingness
Sometimes you need to express that there just isn't anything there.
Sometimes you need to be able to say that a variable points to something,
that is just empty:

Python has its own definition of nothingness. It doesn't look like the empty
space above. Instead, it's a special value that is called None:

nothing = None

None is an indicator of the absence of a value. It's a single pit of nothingness


that has its own type, NoneType. There always exists only one such pit of
nothingness in each of your Python scripts. Any time you want to define that
something is empty, you point to that pit of darkness.

You might wonder when you'll want to point a variable to nothing. Why make
it in the first place? You will see that this comes in handy much more often
than you might expect. As an example, think of a situation where you are
processing a collection of values that you collected. For example, you might
have logged the amount of time you spent working out each day of the
week:

day minutes
mon 60
tue 30
wed 0
thu 60
fri 30
sat 30

Well done! You moved nearly every day of the week, except for Wednesday.
It's okay, you were just really tired on Wednesday.

But wait a moment... what happened on Sunday? You remember Wednesday


clearly, you weren't up for your usual workout and skipped it. But what
happened on Sunday? Did you do your workout or did you not?

If these are your records from last week, you'll probably figure out what
happened on Sunday and fill in the missing value. However, what if this data
was collected by someone else? Maybe even years or decades ago? You
could make an assumption that no time was spent working out on Sunday,
and add a row where sun points to 0. But that could be wrong and mess up
your statistics. In reality, you don't know whether there was any time spent
working out on that Sunday, or not.

Info: In this example, you are dealing with missing data. You can record that
the data is missing by pointing it to Python's pit of nothingness, None

By using the None value, you clarify that this data point is missing. It was
never recorded, or maybe it got lost somewhere on the way. All that you
know is that it's not there.

You might see that, in the context of this example, you can't use 0 to note
the absence of a value. 0 is a valid entry in this example, that has the specific
meaning that you didn't spend any time working out.

Recap

Each of your Python scripts contains exactly one pit of nothingness, a value
called None. You can point variables to it if you want them to get dizzy from
looking into the void. Or, even better, if you want to signify the absence of a
value.
Okay, it looks like you've learned about nothing. It's time to build a few more
structures around this black hole so that there is more than nothing to work
with.
Integers And Floats
The numbers that you have encountered in the previous section may have
felt familiar. You might call both 1 and 2.5 numbers---but Python is a little
more specific than that! The two most important kinds of numbers that
Python uses are:

Integers: Whole numbers without a decimal point, such as 1


Floating-Point Numbers: Decimal numbers, such as 1.23

While they are quite similar to each other, they are represented as different
data types in Python. You'll look at each of them in this lesson.

Integers

Integers in Python have the type int. They are whole numbers, which means
they don't have a decimal point. Here are a few integers as an example:

1
2
42
123456789
0

Any of these numbers are of the type int. Go ahead and test their types in
your Python interpreter! You can also practice assigning them to a variable,
then use type() on the variable name instead.

Note: As soon as you use a decimal point, it's not an int anymore. That
holds true even if the only numbers following the decimal point are zeroes,
e.g.: 1.00
Integers are what you might think of as just normal numbers. Another type of
number that you are familiar with from everyday maths is decimal numbers,
which in Python are of a different data type than integers.

Floating-Point Numbers

Floating-point numbers, also often called floats for short, are numbers with
fractions. That means that any number that contains a decimal point is of the
type float in Python, e.g.:

1.0
123.45
9.99
0.5
0.0

In Python, ints and floats behave quite similarly in many ways, even though
they are of different data types. Go ahead and check the types of some
floats in your Python interpreter or the playground below:

You might think that it could be fun to build a calculator using Python! So
that instead of just looking at these numbers and checking their type, you
could do some math with them. Good call and keep up the spirit, but there's
no need to build anything for that. Python already is a calculator. You'll
explore this some more in the upcoming lesson.

Recap

Python distinguishes between different types of numbers. The most


common ones are:

Integers (int): Whole numbers without a decimal point, such as 1


Floating-Point Numbers (float): Decimal numbers, such as 1.23
Python Calculator
A straightforward use of any sort of numbers are calculations. You can take
numbers and combine them using operators. Python comes with all your
favorite math operators already included, so you can use it as a calculator
out of the box.

Info: When you work with your local Python REPL, the result of a calculation
gets displayed right away. If you are using the online coding environment
provided below, you need to wrap your calculations in a function called
print() in order to display the output. You will learn more about functions
and how to use them in a later chapter, for now just remember that you need
to put your calculations inside of the brackets in order to display the output
of your calculation.

Go ahead and dig out some math examples from your school days. Or find
your latest shopping list. Or just make up some numbers! Punch the
numbers into your Python interpreter or the coding playground below to see
how you can use Python as a calculator:

You can use the common math operators such as +, -, *, / like you'd expect
to make calculations with Python. It looks like you just found a possible use
case for Python that can have everyday applications.

Tasks

The next time when you're reaching for your phone or an old-school
calculator to figure out how much you spent on broccoli over the past month,
try to use a Python console instead!

It's important to train by opening up your Python console, typing some code,
and running it. However, drill aside, you probably have a calculator at hand
that is more user-friendly than that.
But copying your calculator app with a less shiny, text-based interface isn't
Python at peak performance. Because with Python, you can do much more
than just add numbers!

Calculating With Variables

Time to combine what you learned about variables with this new idea of
using Python as a calculator. Unlike with a normal calculator interface, you
can give names to your values in Python. Then, you can operate on those
names instead of the bare numbers. Check out the following example that
still uses numbers, but references them via variables:

too = 2
fast = 1
furious = -3

title = too + fast + too + furious


print(title) # 2

Of course, this "calculation" doesn't make much sense in terms of the


variable names you used here. It does output the number of the movie in the
series, however. Coincidence? ¯\_(ツ)_/¯

Info: Note how you're referencing the numbers using variables. Using
variables that hold values is a central concept in programming that you'll
keep drilling.

You may have struggled with mathematics in school because symbols and
numbers seem like unintuitive concepts to wrap your head around. Which
makes it hard to use them as building blocks for calculations!

Programming can help you out. When you write programs, then you can give
your own names to any values that you are working with. This can make
writing calculations similar to writing a short essay.

Tasks

Use your Python REPL or a code playground to write a different "calculation".


Create your own variables and give them descriptive names, then try to set
them in context with the output of the calculation. Go ahead and share your
mini calculation essay on the forum.

Don't be shy and keep in mind that this calculation doesn't have to make any
sense. It's just for fun and to get more familiar with the concept of using
variables for performing calculations in programming.

Some Arithmetic Operators

You may have already played around with a lot of the arithmetic operators
that you remember from your math education. In any case, check out this list
of some of the operators that you can use with Python:
Operator Meaning Example Result
+ Addition 2 + 2 4

- Subtraction 4 - 2 2

* Multiplication 2 * 2 4

/ Division 10 / 5 2.0

** Exponent 3**2 9

Most of these might feel straightforward for you. However, there is one that
you should pay closer attention to. When you look at the example for
division, you can see that the result looks different than the other results.
What is going on here? What type does this result have? Try this out in the
code playground:

As you can see, Python knows that it cannot correctly represent the result of
1 / 2 as an integer data type, so it automatically converts the result of the
calculation into a float.

Info: You can even perform operations on a mix of ints and floats. This is
possible because Python can implicitly convert integers to floating-point
numbers, if necessary. When you perform a calculation that includes both
types, you will always end up with a floating-point number.

As you can see, this means that data types aren't exactly fixed in Python.
You can often convert a value from one data type into another. However,
some aspects of the original value might get lost in this conversion. You'll
look at this in more detail in the upcoming lesson.

Recap

You can do math with Python, and you can use descriptive variable names to
make your calculations better understandable.
Type Conversion
In Python, the data type of a variable can change over its lifetime. You can
often choose to convert the data type of a variable into another data type.
There are two ways that this conversion can happen:

1. Implicit type conversion


2. Explicit type conversion

In the previous lesson, you encountered an example of implicit type


conversion. Wait... What exactly happened there again?

Implicit Type Conversion

When you perform a calculation with two integers, but the result can't be
accurately represented as an integer, then Python automatically changes the
data type of the output to a float:

whole = 1
part_of_whole = whole / 2
print(part_of_whole) # 0.5

This is called implicit type conversion, because you didn't have to tell
Python to change the type. Python did so implicitly.

Implicit type conversion can be very helpful and is generally designed in a


way so that you don’t need to think about it too much. Python applies
probably useful rules and does all the work behind the scenes.

Some common examples of when Python implicitly converts data types are:

Divisions that produce results with a remainder


Calculations that involve an int and a float
Insertions of variables into f-strings

Info: You haven't encountered f-strings yet, but you will learn more about
them in the upcoming section.

When you use f-strings, then Python evaluates expressions and silently
converts everything to the str type. The output is always of type str!
Therefore, anything you dump in there gets implicitly converted to a str.
You'll learn more about f-strings and the str data type soon.

Explicit Type Conversion

In some cases, it's possible to tell Python to convert a value to a different


data type. For example, it's possible to convert text that is a number into an
actual number. This is commonly necessary when you're receiving user
input in a Python script, which always first arrives as text of the data type
str.

Look at the example below. Again, don't worry if you don't exactly
understand what's going on here, and remember to try to read it as English
pseudocode. Then see whether you can somewhat understand what the
code is about:

age = input("Please enter your age: ")

age = int(age) # int stands for 'integer'


print(age, type(age))

The code above explicitly changes the type of the variable age from a str to
an int. Input from a user that is gathered with input() always arrives as a
text value. Therefore, in order to be able to perform a number-based
calculation with it, you'll first need to explicitly convert it to a number. Give it
a go in the playground below:
Collecting user input and then wanting to continue working with it is a
common situation where you may need to apply explicit type conversion in
Python.

Info: If you think back to your guess-the-number game at the beginning of


this course, then you might remember that you also needed to convert the
input provided into a number. Otherwise, Python couldn't compare it to the
randomly generated number that you had to guess.

Can you think of a script you would like to build that collects a number input
from a user and makes a calculation with it? Feel free to use the playground
above to build a draft and share it on the forums.

Recap

You've learned that there are numbers and there is also text, which in Python
is of the string data type str. You've learned that you can convert strings
into numbers, and this conversion also works the other way around.

But strings can do a lot more than just being differently shaped doubles of
numbers. After all, you probably wouldn't want to read a novel if it was
encoded in numbers only! In the next section, you will learn more about
strings in Python, and see how they are a very versatile and common data
structure for programming.

Additional Resources

Implicit and explicit type conversion: Conversion and Casting


Additional Tutorial: Python Data Type Conversion
Strings And Text Data
Working with text is a productive and exciting use of your budding
programming skills. There is an endless and ever-growing amount of text
data out there.

Some examples of text data are your personal emails, all digitized novels that
were ever written, scientific publications, countless tweets, and other social
media data that are produced daily, or also more inconspicuous data, such
as readings from medical devices.
Text is everywhere, and humans use text to communicate all sorts of
information. It's probably the most widely used way of recording information.
Being able to work with text programmatically can therefore be fun,
challenging, and rewarding---all at once! You'll start by defining how Python
knows that something is text.

Text is Wrapped in Quotes

The data type that Python uses to encode text is called string (str).
Everything that is wrapped within single ('') or double quotation marks ("")
is considered a string in Python:

You can choose which types of quotation marks you want to use. Both of
them work fine, as long as you don't mix them together. Go ahead and add
the following code into the playground and watch it respond with an error:

print("help!') # SyntaxError

Now that you know how to define a string in Python, take a moment to
ponder what a string might look like from Python's perspective.

A String is a Sequence of Characters

Python thinks of a string as a sequence of characters. Okay, but what does


that mean? Put yourself into Python's shoes. Well, maybe that's a strange
request, given that snakes aren't really known for their footwear... ¯\_(ツ)_/¯

When Python processes a word, for example "hello", it thinks of it


differently than of a number, such as 200. The number 200 is just that, a
number, a single unit of information. However, "hello" is not a single piece
of information for Python. Instead, it sees it as a sequence of characters:

"h" + "e" + "l" + "l" + "o"


Programs always need to break things into their smallest units, that's just
something they love doing. Computers understand numbers well, but they
don't have a conceptual understanding of words. While for you, as a human,
it is easy to understand that the word "hello" is correct and "hlelo" isn't
quite correct, your computer has no way of knowing any of that.

Info: There's an interesting field of Machine Learning that deals with the
processing of human languages. It's called Natural Language Processing
(NLP) and it has been an active research topic for many decades. More
recently, there have been some big improvements made that can help
computers to correctly interpret, process, and even produce an impressively
large amount of human language.

But keep your phone's speech assistance offline for yet another moment and
skip on that latest ChatGPT conversation. Continue to think about how text
gets processed at the programming level.

As mentioned above, Python doesn't think of text as a unit of words or


sentences, but instead at the lower level of characters. So, if it's a sequence
of characters, that means that Python should know which ones there are,
and how many of them.

Counting Characters

If you're wondering how many characters your string consists of, then you
can use the handy len() function to find out:

name = 'codingnomads'
print(len(name)) # 12

With the len() function, you can find out how many characters make up your
Concatenation
In the previous lesson, you learned that a string in Python is a collection of
characters. As an example of how Python thinks of a word, you saw the word
"hello" stuck together by all the different characters that make it up:

"h" + "e" + "l" + "l" + "o"

While this might look a little unfamiliar, it is actually valid Python code. Head
over to your Python console and type in the exact sequence of characters
and press Enter:

Python takes all the single characters and combines them into one string:
the word "hello". What you did here is called string concatenation. As you
can see, it really is just a fancy word for saying that you are adding
characters together.

Info: You might have noticed that you are using the same plus (+) operator
that you used for adding numbers. Python operators have different effects
on different data types.

This doesn't only work with single characters, but with strings of any length.
You can always use the plus (+) operator to stick them together:

Feel free to experiment with adding other strings together.

Tasks

Create a sentence by concatenating the words "this", "is", and "fun". Try
answering the following questions, and feel free to post your thoughts and
your solution on the forum:

What happens when you put the words together without any further
changes?
What do you need to add in order to create a readable sentence? Why?
Challenge: Can you keep the same words and create a question by
concatenating them differently? Remember to add spaces and
punctuation.

What happens when you use a string that consists of more than one word?
What do you need to do in order to create a sentence with normal spacing
that makes it readable?

Recap

There's more to learn about strings, but before you go there, you'll finish this
lesson with a quick recap:

Collections: Strings are collections of characters.


Concatenation: You can stick strings together to create longer strings.
Operator: When you use the plus operator (+) on strings, Python
performs concatenation.

Over the upcoming lessons, you will keep thinking about what it means that
Python sees strings as collections of characters. When you can stick
characters together, you should also be able to break pieces off. You'll
explore this idea in the next lesson.
Error Friends
PageError: You've encountered a page you didn't expect.

Don't worry, everything is fine. In fact, this page is here to convince you that
error messages are your friends when learning to program :)

Error messages seem intimidating to many people when they are getting
started with programming. You might only have seen error messages when
one of your devices breaks. Or maybe you still remember the blue screen of
death that used to be part of too many computer sessions a couple of years
ago:

In programming, error messages are here to help you out. Python is sending
you a message to tell you that there was a miscommunication and it couldn't
quite understand what you were asking it to do. It gives back all that it knows
and hopes---with all its digital fingers crossed---that the two of you will be
able to figure it out together.

In order for Python to get back on the same page without frustrations, it
helps if you train yourself to read error messages---and feel positive about
encountering them!

Reading Error Messages

Familiarity with reading error messages is one of the most important skills
when working in software development. Training this skill is crucial because
you will encounter error messages all the time. Let me repeat that and put it
here for you as a quote:

You will encounter error messages all. the. time.

To train your error-reading skills, keep exploring when you work on an


exercise, the labs, and the projects in this course. Play around with them,
break the code, and encounter as many error messages as possible. Then
just keep breathing and read over the message that Python sent.

Learning More About Python

Purposefully running into error messages gives you another angle to explore
the inner workings of Python. You can figure out how something works by
first exploring when it doesn't work. Once you see that something doesn't
function as expected, you figure out what needs to be done in order to make
it work.

While working on this course, you'll run into lots and lots of error messages.
Keep in mind that they are just Python's way of chatting with you about a
potential misunderstanding, with the honest-to-good intention of figuring it
out together. Like in any misunderstanding, as long as both parties are
cooperative, this gives you a great opportunity to better understand how the
other party works and thinks.

Anatomy Of An Error Message

At this point, you already did some programming and you had the chance to
encounter some error messages on the way. Now you'll run into some of
them on purpose so you can train your error message reading skills.

Type the following into your Python interpreter:

s = "hello'

If you copied the text exactly as it appears above, you will have managed to
confuse Python. But Python is motivated to figure out what went wrong in
your conversation, and gives you all the info that it has at this point:

>>> s = "hello'
File "<input>", line 1
s = "hello'
^
SyntaxError: EOL while scanning string literal

In this error message, Python tells you the type of error it encountered. In
this case, that's a SyntaxError. This gives you a chance to narrow down
what you should look for in the code you wrote. Looks like there's some
syntactical issue. Great! These errors are often the easiest to spot.

But Python gives you even more information than that. Generally, it's a good
approach to read an error message from the bottom up:

SyntaxError: Something is wrong with the syntax of your code. Your


code doesn't comply with the rules of the Python language.
EOL while scanning string literal: Python expected the statement to
continue, but it was suddenly over.
^: This small arrow points you to the location where Python got lost.
Sometimes this will point exactly to the issue as it does here, but
sometimes you might have to look a little earlier in the code. Python can
only tell you where it got lost, and sometimes the reason why it did
happen a bit before Python noticed.
line 1: Similar to the arrow, this line number tells you where to look for
the error in your code. Python again tells you where it got lost, so the
line number it mentions is a good way to start looking.

In this case, the SyntaxError got caused by mixing two different kinds of
quotation marks when you created the string. That's not a valid syntactical
way of creating a string in Python, which is why Python got confused.

If you're working on Python 3.10 or higher, then you'll see an even more
helpful error message when you mixed two different types of quotes in a
string:

Python 3.11.0 (main, Oct 27 2022, 16:43:43) [Clang 12.0.5 (clang-1205.0.22.9)] on dar
Type "help", "copyright", "credits" or "license" for more information.
>>> "hello'
File "<stdin>", line 1
"hello'
^
SyntaxError: unterminated string literal (detected at line 1)

Python's been working on its communication skills! It's really invested in


making your friendship work out, so there have been some improvements in
error messages that make them a little more clear. If you're curious, you can
read more about these updates in the official "what's new?" pages for
Python 3.10, Python 3.11 and Python 3.12.
Tasks

Purposefully run into some more errors and deconstruct them as shown
above:

Type 3 + "2" into your REPL. What error message do you receive?
Now turn it around and type "2" + 3 into your REPL. What's the
difference in the error message you receive? Can you figure out why?

Carefully read over the error messages that you receive. This gives you a
chance to better understand what might have caused the misunderstanding.
Once you know what went wrong, you're well on your way to fixing it!

Recap

Error messages are your friends. They are here to help you figure out why
Python didn't quite understand what you asked it to do. Use every chance
you get to practice the following skills throughout this course:

Seeing error messages without worrying


Reading error messages and gathering useful tips from them
Resolving error messages, by understanding what they mean and
where to look to fix the underlying issue
Exploring the programming language that you are learning about

Get ready to run into errors frequently! Play around with any code that you
see and find out how you can break it. Try to encounter a lot of error
messages! It'll help you to train a crucial skill every software developer needs
to master, and that'll be useful not even just for Python.
Ready to run into errors? Alright, time for you to get started doing so:

EndOfPageError: End of current page reached. Please click on to the next


page to access more content ;)
Indexing
Welcome back from error-land! In this lesson, you'll keep moving forward
and learn more about working with strings in Python.

You might have found string concatenation to be quite fun, and then it's easy
to go overboard and stick just a little too much text together. Luckily, Python
also gives you the chance to break strings up into pieces. In this lesson,
you'll learn how to pick out single characters from an existing string using
string indexing.

However, before you're ready to start disassembling strings, there's the


concept of European floor numbering that you need to consider:

If you like the look of these houses, but the concept still sounds confusing
and unrelated, read on and it'll tie together quickly with the necessary
prerequisite knowledge for string indexing.

Zero-Based Numbering

In Europe, the stories in houses are numbered starting with the ground floor,
or floor #0. In order to get to level #1, you'll have to climb one set of stairs.

Most programming languages take the same approach when numbering


items in a collection, and so does Python. Since you already know that
strings are collections, it won't be surprising that it applies to strings as well.

Note: A string is a collection of characters where each character has a


defined index position. The first letter has the index 0, the second letter has
the index 1, etc. This is called zero-based numbering in programming.

When you think back to one of the first strings you've encountered in this
section, what would the indices of each of the letters be:

"hello"

Give it a try and practice this type of zero-based numbering also with some
additional strings.

Info: Feel free to get out your notebook and write out some examples
manually. Using pen and paper can be a great companion to better
understand and practice programming concepts.

If you go ahead and break it down, you can look at an indexed string in
Python like in the example below:

0 1 2 3 4
---------
h e l l o
Okay, so indexing starts at 0 in Python. Now, how would you be able to
access one of these characters in order to do something with it?

Accessing Characters Through Indices

Python gives you a handy syntax to pick out only a part of a string, through a
process that is called indexing. Take a look at how it works:

greeting = "hello"
greeting[0] # h
greeting[4] # o

Using the square brackets at the end of a string opens up a window into
that string. You can use the brackets like tweezers to pick out the character
in that string that you are interested in. There's only one piece of information
that you need to provide Python with so that it knows which part of the
string you want. That is the index number of the character that you're
looking for.

These indices translate directly from how you saw them assigned via zero-
based numbering. It means that if you want to pick out the first letter of a
word, you can do this with [0], if you want the second one, you need to type
in [1].

Tasks

Use the playground below to print a new string that impersonates the Santa
Claus impersonator from your local shopping mall by saying "hohoho". You
can only use the provided string! Pick out the relevant characters and
concatenate them in order to print out the new word.

Great job if you got this to work, and ho-ho-ho to you! You might have
struggled with needing to count to the end of your string in order to pick out
the last letter, o. To make locating characters at the end of a word easier,
Python allows you to index also starting from the back.

Accessing Characters Backwards

If you need to pick out the last few characters from a long string, for
example, the file extension from a file name, you might soon want to sigh in
desperation! Do you really need to count all the way to the end every time?!
You don't! Python's got you covered!

Additionally to indexing strings from the beginning, starting with 0, each


string is also indexed from the end, starting with -1:

-5 -4 -3 -2 -1
--------------
h e l l o

The rest of the indexing syntax stays the same, which means that you can
access the "o" in this word also with:

"hello"[-1]

This way of negative indexing makes some string operations much easier.
For example, fire up your Python REPL and fetch just the file extension from
"wow-that-is-such-a-long-filename.txt" using negative indexing.

Recap

String indexing allows you to pick out specific characters from a string.
Here's what you need to remember:
Indices: An index is the location of a character in a string. Each
character has a defined index that is denoted with an integer.
Zero-Based Indexing: Python starts counting at 0. In the same way
that European houses would---if they could count!
Indexing Syntax: At the end of the string, put a pair of square brackets
wrapping the index of the character that you want to access. This gives
you a new string object consisting only of that single character.
Positive And Negative Indexing: You can index from the beginning,
starting at 0, or backward from the end, starting at -1. Effectively, each
character has two valid index numbers: one is a positive integer and the
other one is a negative integer.

Now that you know how to pick out single characters from a string, keep
going and learn how to pick out bigger chunks instead, using string slicing.
Slicing
The syntax you previously used for indexing a string and picking out a
specific character can also be used to pick out whole substrings from a
Python string. Doing so is called string slicing and can get you some
delicious new pieces of your original strings.

String Slicing Syntax

The syntax for picking substrings from an existing string closely resembles
the syntax used for string indexing that you learned about in the previous
lesson. Assume that you're playing a word game and you need to pick out as
many words as possible from a given string. Start off with a feathery word:

s = "plumage"

You might quickly find two words hidden within this word, but how can you
pick them out of there? To extract the word plum from plumage, you'd need
to slice the string like so:

s[0:4] # plum

Time to discuss this syntax within the square brackets in a little more detail:

Start: You pass in the index of the first character that you want to be
part of your resulting word.
Separator: You place a colon (:) as a separator.
End: You add the index of the character one after the last one that you
want to be part of your new string.

While the start and the separator might make intuitive sense, the value for
end might seem a little confusing. If you want, you can note it down to
Python's eccentric way of counting ¯\_(ツ)_/¯ but you can read about why
this is the way it's implemented a bit further down.

Note: When you slice a string in Python, the start character is always
included, and the end character is always excluded.

With this in mind, spin up your text editor or your Python REPL and play
around some more with string slicing.

Tasks

Extract the word "age" from the given word "plumage"


Can you accomplish this task using negative indexing?
Can you find yet another valid English word within the word plumage?

After you have extracted both of the substrings, you can reconsider why
Python doesn't include the end character when slicing. The reason for this
is, that it ensures that with a defined index i (for example that could be 4)
everything up to that index plus everything from that index will always create
the complete string:

s = "plumage"

s[0:4] # plum
s[4:7] # age
s[0:4] + s[4:7] # plumage

As you might see, if both the start and end were inclusive, then this could
lead to unexpected results. (In this case, it would create a purple wizard that
might drown the world in sticky fruit juice...)

However, you may have noticed something else that's strange here. In order
to go all the way to the end of the string, you need to type in an index
number that isn't part of the string anymore.

This makes sense since you want to include the last character, and for that,
you need to give the index of the next character after the last one you want
to include. Still, it seems a little unintuitive, and Python has a better way to
handle this situation.

Syntax Shortcuts

Python provides two convenience shortcuts for string slicing. Namely, you
don't need to specify the start or end index if you want to slice all the way to
the beginning or the end of your string. Instead, you can simply leave out
that number, but still, write the separator colon:

s = "plumage"

s[:4] # plum
s[4:] # age

Omitting any of the start or end indices in your string slice tells Python to go
all the way.

Info: Because of this syntax, you can create an exact copy of a string with
the syntax s[:]. Give it a try!

Similar to using the above-mentioned syntax to copy a string, there is a


shorthand way that you can use to reverse a string in Python. To
successfully achieve this, you need to know one more interesting feature of
Python string slicing.

Specifying Strides

Additionally to defining a window from where to where the substring should


be taken, you can also define a stride. In string slicing, the stride tells Python
the size of steps to take when considering the slice you defined.

The default stride is 1, which means that Python will consider every
character in the substring range. Since that is the default you don't even
need to specify it. Nevertheless, you can still do it:

s = "plumage"
s[0:4:1] # plum

The syntax for specifying the step of your slice is done by adding another
colon (:) followed by another integer. The final integer stands for the size of
the step. Here is what happens when you change the step:

s = "plumage"
s[0:4:2] # pu

Compare the two outputs and think about what has happened here. Spin up
a Python REPL and play around with this syntax and make sure that you
understand how it works. When you think you got a hang of it, get ready for a
challenge:

Tasks

Reverse a string in only one line of code, combining your knowledge of


indexing, slicing, and strides.

When you have found the solution of how to reverse a string in one line of
code, feel free to go ahead and look on the internet how some other
programming languages handle this task. Most of the examples are a lot
more complicated than in Python. This elegance and user-friendliness of
Python's syntax are one of the reasons why it is a great language to pick up.
Recap

In this lesson, you learned how to extract substrings from a Python string
using string slicing.

Syntax: Inside of square brackets, use an inclusive start index position


separated from an exclusive end index position by a colon.
Shortcuts: You can omit the start or the end index, if you want to slice
all the way to the start or end of the string, respectively.
Stride: You can specify the size of steps that Python takes over your
slice with a third number after yet another colon.
Reverse: String slicing, combined with strides, gives you a shorthand
way to reverse a string.

By now you have a good idea of how you can interact with individual
characters of the collection that makes up a string. However, picking out
characters, and even substrings, might not yet be what you want to do with
your text. In the next lesson, you will learn about how you can make
interesting things happen using string methods.

Additional Resources

DigitalOcean Tutorial: How to Index and Slice Strings in Python


String Methods
Now that you know how you can slice and dice your text in Python, take a
closer look at some interesting things you can do with strings. When you
want to do something with one of your values, you usually call a function or a
method on it.

Info: Don't worry about the difference between functions and methods yet.
For now, you can think of them as very similar things that allow you to
perform an action on a value. You will dive more into using and creating
functions and methods later on.

You have already used a few such actions before, for example when calling
print() to display output, or len() to get the number of characters in a
string.

In this lesson, you'll learn more about some actions that are specific to
Python strings, which means that you can only use them on values that have
the str data type. These actions are called string methods.

String Methods

There are a good amount of string methods that you can use to work with
text in Python.

Note: Methods allow to make something happen. You will talk about what
methods are in more detail later on.

You can use these methods to manipulate text. In this lesson, you will write
out an annoying script. You will see why it's annoying in just a bit. Start by
writing out some ideas in pseudocode:

# TODO: Write a prompt that asks users to "type something to win"


# They will only win if they type "something" into the prompt
#
# Collect user input
# Compare to the string "something"
# Print a win or lose message

Feel free to give it a try and write the game by yourself in your text editor.
Remember that getting better in anything is all about practice!

Note: To function properly, the script needs to use comparison logic and
conditional statements that you haven't learned about yet. Both sound
scarier than they are, and you'll get to know them very soon. However,
there's no need to wreck your brain with it just yet, so you can continue
reading for an example solution of the mini-game.

Assume you created this script and shared it with some friends, and they got
quite annoyed, as expected and intended ;P

However, one of them tells you that they typed Something and the script still
told them that they lost. Maybe you've been a little too strict with your input?
Try to soften it up just a tiny bit to make sure you don't lose your friends over
this:

# Collect user input


# NEW --> Convert user input to lowercase
# Compare to the string "something"
# Print a win-or-lose message

Converting their input to lowercase should calm the heated mood, and you
want to allow any type of capitalization of the word "something" to count
towards winning. After all, they got the joke and deserve the winning
message, whether they typed "Something" or "SOMETHING" or "sOmething" or
"something". This is where a string method comes in handy:

While there are a few concepts in this script that might not make entire
sense to you yet, stay focused on the string method for now. You can find it
in line 4 where you are calling word.lower(). The string method's name is
lower() and it is connected to your word through a dot (.).

This is the general way of using a method, and in programming terms you
say:

I am calling a method on an object.

In this case, you are calling the .lower() method on a str object that has the
variable name word and holds as a value whatever the user entered as input.

Now, you heard before that methods and functions always do something. So
what does .lower() do? Take a look into the official Python docs and see
whether you can find out. When you find the entry for str.lower(), it says
the following:

Return a copy of the string with all the cased characters converted to
lowercase.

This description gets right to the point. It explains to you that it makes a copy
of the string which will consist only of lowercase characters. The Python
documentation can sometimes sound a little stiff and difficult to read but aim
to get yourself into the habit of reading it anyway. Feeling comfortable with
reading documentation is an important skill for you to practice as a
developer.

If you scroll around some more in the documentation about Python's String
Methods, you'll see that there are a lot of them. In fact, there are way too
many to learn them all right now, so instead just try a few that seem useful:

Tasks
Find and read the documentation on the following string methods, and try
using them in your code playground:

str.endswith()
str.capitalize()
str.isdigit()

You can think of the str that is mentioned in the documentation as a


placeholder that tells you the data type of the object that you can call the
method on. To use any one of these methods, you'll therefore have to
replace the str part with your string:

"hello".capitalize()

You can also replace the space before the dot (.) with a variable that points
to a string:

name = "codingnomads"
name.capitalize()

Open up your text editor and try using some string methods that you find
interesting. If there is one that you found especially interesting, please share
it on the forum.

In the next lesson, you'll learn why string methods create copies of strings,
as well as some other interesting information about the str data type.

Recap

Now that you have gotten a taste of how you can do things to text in Python
using string methods, you'll finish this lesson with a quick recap:
Methods: Strings have methods associated with them.
Actions: Methods allow you to do something with a string.
Documentation: There are many string methods, and you can look up
what they do in the Python docs on String Methods

Keep in mind that this is just a first taste of methods and you'll learn more
about them in a later part of this course.
Immutability
You might have stumbled across a reoccurring phrase when reading in the
String Methods documentation:

Return a copy [...]

Why do all of the string methods return a copy of the original string, instead
of modifying it? The reason is that it's simply impossible to modify a string in
Python.

Strings Are Immutable

Python strings are immutable, which means that you can't change a string
after you created it.

However, you can always create a new string based on the initial string and
apply certain changes. Since Python allows you to update your variables and
re-assigning different values to them, you can even re-assign the old
variable to the new string. This effectively replaces the way you accessed
the old string value with the new string value:

Using this syntax allows you to continue to work with your original variable
after applying the changes. The variable now points to the new, adapted
string.

Recap

Strings are immutable. You can't change a string, but you can create new
strings and re-assign them to the original variable, effectively replacing the
old string value with the new one.

By now you have learned most of the important things there are to know
about strings in Python. You learned that strings are collections of
characters, saw how you can slice and dice them, learned about some string
methods that exist, and doubled down on the knowledge that strings are
eternal and unchangeable.

For the final lesson in this section, you'll do a little extra and learn about
some fun and useful things that you can do with strings.
Searching And Finding
In this section, you've learned a lot about strings in Python! It's time to take a
break and have some fun. Of course, while also learning something new :) In
this lesson, you will get to know how to find substrings in a string.

Then, you'll then get a chance to apply some of what you've learned in your
Python course labs. The labs are your training exercises to get in the
necessary practice, as well as to challenge you to think through concepts for
yourself, which helps your neurons to fire and build new connections. Time
to get started!

Finding Substrings

Sometimes you'll want to find out whether there's a certain word, or


substring, inside of a given text. Python offers you a couple of ways to do
this. Here, you'll look at string methods that allow you to search in a user-
friendly manner.

Think back to an example where you have a bunch of filenames and you
want to filter out only some of them with just the right file extension. For that,
you can use the str.endswith() method, which you might have already
found in the string method documentation:

"mytext.txt".endswith("txt") # True
"mypage.php".endswith("txt") # False

This string method will check whether the argument you passed to the
method, in this case, that's the string "txt", is indeed how the string you're
calling the method on ends. In the example above, you are calling the
method on both "mytext.txt" and "mypage.html", one of which does end
with "txt", the other one doesn't.
Python returns a truth value as a response to your question. You can think
of what's going on up there like this:

You are asking Python: The string "mytext.txt" ends with the substring
"txt", right? And because it does, Python responds by saying: Yep, that's
True.

Great! Python is a good buddy and responds truthfully. Or is it just trying to


please you? You should check:

So, next you ask Python: The string "mypage.php" ends with the substring
"txt", right? And because it does not, Python keeps it real and responds
with saying: Nope, that's False.

As you can see, str.endswith() is a convenient and user-friendly method


that almost reads like English. And it's by far not the only string method that
allows you to find substrings in text:

Tasks

Check out some other interesting string methods that can help you find
substrings in text in the string method documentation.

Find the method to check whether a string starts with a certain


substring.
Find a method that allows you to determine at what index position a
certain substring exists.

After you finished these tasks, you should know about at least three
methods that allow you to find substrings within the text.

However, sometimes you don't need to know anything about the start or the
end of a string, nor do you care about where a substring exists. Instead, you
just want to know whether a substring is anywhere in a larger text.
There's a user-friendly way to do that, too! You'll learn about how to do that
in the upcoming section that will introduce you to Python's operators.

Additional Resources

The Python Guru: Python Strings


Real Python: Strings and Character Data in Python
Python Operators
You can encounter operators in your daily life. For example, while you might
not explicitly see them, you know they are there when you look at your
receipts after you went grocery shopping.
In this receipt, a computer added a few prices together to come to a final
result. Even though the operator might not be displayed, you know that
there's a symbol that can describe this operation: +.

Even if you might not understand anything about the language that
describes the mystery goods you purchased, you can still understand that
the numbers have been added up.

Python Operators Are Familiar

Python operators largely follow the intuition for mathematical operators that
you might have from school---or from everyday life.

Info: In their essence, operators are symbols with specific meanings that
allow you to bring values in context with each other.

You've heard about values. Now you will learn how you can manipulate
values and compare and contrast them using different Python operators.

In this section you will learn about the following types of operators:

Assignment Operator: Makes a symbol refer to a value


Arithmetic Operators: Do arithmetic calculations
Membership Operator: Checks whether an element is part of a
collection
Relational Operators: Compare two or more values to each other
Logical Operators: Compare values on the basis of logic
Identity Operator: Finds out whether two values point to the same
object in memory

You have already encountered the assignment operator as well as some


others, but you'll explore them in more depth in this section. You'll start by
revisiting the assignment operator in the next lesson.

Additional Resources
Cheatsheet: Python Operators
Assignment Operators
All assignment operators are used to assign values to variables. Wait, there's
more than one assignment operator? Yes---but they're all quite similar to the
ones you've seen before. You've used the most common assignment
operator, and its symbol is a single equals sign (=).

For example, to assign x the value of 10 you type the following:

x = 10

You have used this assignment statement before in order to assign values to
variables. Apart from this very common way of using it, there are a few other
situations that use the same symbol for slightly different assignments.

Chained Assignment

You can assign the same value to multiple variables in one swoop by using
an assignment chain:

x = y = z = 10

This construct assigns the value 10 to x, y, and z. In Python, it isn't very


common to use the chained assignment statement, but in case you see it
around, now you know what that's about.

Shorthand Assignment

Shorthand assignments, on the other hand, are a common occurrence in


Python code. This is where the other assignment operators come into play.
Shorthand assignments make writing code more efficient and can improve
readability---at least once you know about them!

For example, think of a situation where you have a variable x and you want to
add 1 to that variable:

x = 2
x = x + 1
print(x) # 3

This works well and is perfectly fine Python code. However, there is a more
concise way of writing the same code using shorthand assignment:

x = 2
x += 1
print(x) # 3

Check out how the second line in these two code snippets is different. You
don't need to write the name of the variable x a second time if you use the
shorthand operator += like in the example above.

Both code examples shown achieve the exact same result and are
equivalent. The shorthand assignment just allows you to use a little less code
to get the task done.

Shorthand Assignment Operators

Python comes with a couple of shorthand assignment operators. Some of


the most common ones include the following:

Operator Meaning
+= Add the value on the right to the variable on the left
-= Subtract the value on the right from the variable on the left
*= Multiply with the variable on the right, and add to the result on the left
/= Divide by the variable on the right, and add to the result on the left

These operators are combinations of familiar arithmetic operators with the


assignment operator (=). You have already used some of Python's arithmetic
operators, and you'll learn more about them in the upcoming lesson.

Tasks

Play around and try combining different operators you can think of with the
assignment operator in your Python REPL.

Which ones work and do what you expect them to?


Which ones don't?
Arithmetic Operators
You've already used arithmetic operators to perform mathematical
operations in the section about numbers and math. Many common
mathematical operators work the same in Python, which is also why you can
use Python directly as your calculator.

However, there are also a few arithmetic operators that might seem a little
unfamiliar.

The following table summarizes all available arithmetic operators in Python:

Operator Meaning Example Result


+ Addition 2 + 2 4

- Subtraction 4 - 2 2

* Multiplication 2 * 2 4

/ Division 10 / 5 2.0

% Modulo 3 % 2 1

// Floor division 5 // 2 2

** Exponent 3**2 9

While you've already worked with the more familiar ones, there are a few
new ones stuck to the bottom of this table that you'll take a closer look at
now.

Modulo

The modulo operator, also sometimes called modulus, allows you to divide
by a number and get the remainder as your result:

5 / 2 # Normal division OUTPUT: 2.5


5 % 2 # Modulo OUTPUT: 1
In this example, you can see that 5 % 2 will return 1. Using the more familiar
division (/), 5 / 2 will return a float because 5 can't be divided by 2 without
a remainder. Instead of getting a float as a result, the result of using the
modulo operator gives you what remains when you take every possible
number 2 out of 5.

2 fits twice in 5, which comes up to 4. What remains as a difference between


the original number 5 and 4 is called the remainder, which is 1 in this case.
This remainder is what the modulo operator returns.

There is another closely related concept to the modulo, which is called floor
division and handles the other side of this operation.

Floor Division

Floor division performs a division, but instead of creating a float with the
remainder in the fraction, it discards the remainder:

5 // 2 # Floor division OUTPUT: 2

How often the divisor fits into the dividend is the result of your floor division.
2 fits in 5 two times, so the floor division returns 2.

The default behavior of the more familiar division is to implicitly change the
data type of the value to a floating-point number if the division cannot be
done without fractions.

Floor division avoids changing the data type. It performs a division to the last
possible full number and discards the remainder.

Exponent
The third operator you haven't used before is the exponent. You might be
familiar with exponentiation from arithmetics, but you probably haven't seen
it written with the double-star symbol (**).

You use the exponent to set a value to the power of another value, for
example:

2 ** 2 # 4
2 ** 3 # 8

If you write an exponential calculation, like the ones shown above, then make
sure that you keep the two asterisks stuck together. The exponent operator
is a single operator that consists of two asterisks (**). If you accidentally put
a space in between these two symbols, Python will be confused and let you
know by displaying a SyntaxError: invalid syntax.

Tasks

Revisit the section on numbers and math and apply some of the additional
arithmetic operators you learned about in this lesson on integers and floating
point numbers.

Since the arithmetic operators gave you a chance to revisit the int and
float data types, it's only fair to also give the str data type a chance to
make a glorious comeback. In the next lesson, you'll find out how you can
use Python's membership operator to check for substrings in strings.
Membership Operator
In the section about strings and text, you learned how to find substrings in a string
using string methods. This worked well for looking for file extensions, such as .jpg,
with the string method str.endswith(). But what if you just want to know whether a
substring is anywhere inside a text you've been handed?

Python's membership operator in can help with that!

Confirming Substrings
Imagine your favorite Latin teacher proudly presents you with the newest homework
sheet, gently placing it in front of your eyes with the words:

Is the word euismod in this text?


They deliver this sentence with the most charming smile. You lower your gaze to
the worksheet and notice how a cold horror creeps up somewhere in the vicinity of
your spine. What you see is this:

Lorem ipsum dolor sit amet, consectetur adipiscing


elit. Curabitur sem massa, imperdiet quis feugiat nec,
maximus vitae justo. Ut a sem nulla. Ut pulvinar,
libero sollicitudin lacinia faucibus, sapien mauris
viverra nibh, eget blandit leo nibh ut neque.
Pellentesque bibendum est quam, quis dictum eros
placerat
viverra. Nunc ac ultricies lacus. Suspendisse mollis
sed diam feugiat bibendum. Vivamus imperdiet lacus
velit. Class aptent taciti sociosqu ad litora torquent
per conubia nostra, per inceptos himenaeos. Sed
quam augue, volutpat ac nisi at, vestibulum sodales
augue.

Ut varius magna at viverra rutrum. Sed rhoncus


accumsan placerat. Maecenas sed pretium mauris. Sed
tempus
molestie sagittis. Proin bibendum dignissim tortor sed
vestibulum. Etiam dignissim eros sed sem porttitor,
non volutpat dui cursus. Nullam sit amet arcu porta,
aliquet ante eget, venenatis felis. Duis sit amet
aliquet tortor. Ut euismod molestie tellus ac lacinia.
Ut tincidunt, tellus a rutrum semper, ex orci
convallis libero, in accumsan ante lectus nec odio. Ut
cursus fringilla nibh et bibendum.

Vestibulum ipsum velit, porttitor gravida tristique


at, facilisis eu leo. Suspendisse ac nibh eros. Mauris
sem ligula, sagittis eu purus nec, pellentesque
faucibus nisi. Sed pulvinar augue nec mauris dictum,
sit
amet efficitur mi aliquam. Donec eu porttitor risus,
suscipit laoreet erat. Duis purus magna, venenatis a
placerat hendrerit, suscipit sit amet est. Donec
luctus efficitur arcu nec rutrum. Vestibulum suscipit
enim
molestie libero mollis, in egestas est consequat.
Integer urna dui, mollis vitae viverra a, gravida eu
nisi.
Sheesh! Okay, time to start reading some Latin...

Or maybe there's a faster way? Ask Python for help by simply passing the question
along:

text = "Lorem ipsum dolor ---- snip, but you should put it all in
here! ---- a, gravida eu nisi."

"euismod" in text # True


Welp, that was fast! Thanks, Python!

What you used to get this swift answer is called the membership operator in. It
sounds quite intuitive, right? That is because reading Python code is sometimes
nearly like reading English. You've heard that one before, haven't you? :)

The membership operator in allows you to quickly check whether a string contains
a substring at any position. Python doesn't tell you where the substring is---but you
also didn't ask for that.

Info: The membership operator (in) is an intuitive way to check whether an


element is part of a collection.
In this case, you checked whether a substring is part of a longer string. Similarly,
you can use the second membership operator (not in) to check whether an
element is not in a collection:

"euismod" not in text # False


In your REPL session, play around some more with using in and not in and
looking for words in the Latin text:

Tasks
• Is the word pulvinar in the text?
• What about tincidunc?
• What about Proin? Remember that capitalization matters!
• Can you think of a way to generalize the search so that you won't get tripped
up by different capitalization of words?
Once you're fed up asking Python whether words are part of Lorem Ipsum, you
might start to wonder what exactly are those answers that Python keeps giving you
when you ask whether a substring is in a larger string.

Python seems to be quite bi-syllabic about it. It always keeps giving you only one of
two answers:

• True
• False
These values are another Python data type, and they are at the core of how all
computers are built. They are boolean values and you'll learn more about them in
the upcoming lesson.

Recap
The membership operator in allows you to quickly check whether an element is part
of a collection.

You can read a deep dive into the topic of checking for substrings in strings in my
article on how to check if a Python string contains a substring.
Boolean Values
In the previous section, you asked Python whether an element is inside a
collection, and Python diligently answered either with True when it was in
there, or False when it wasn't.

Python is very direct in that sense, and any time that you ask it a well-
formulated question, it will answer with one of these two truth values. They
are also called Boolean values and represent their own data type (bool) in
Python.

Boolean Values

This data type is the fundamental building block of all computer systems.
The type bool stands for Boolean values, which can have one of two
possible states:

1. True
2. False

True and False represent a binary concept. An electronic device is either ON


or OFF. All or nothing. In digital computer terms, you can think of it as 1 or 0:
You've seen that Python likes to respond to you with these truth values. You
can collect Python's answer and assign it to a variable. Think back to the
substring example from your previous lesson. Instead of just letting Python
respond, you'll collect its response and save it to a variable:

text = "Hello Coder!"


contains_hello = "Hello" in text
print(contains_hello) # True

By using the assignment statement, you save Python's response to the


question "Hello" in text in the variable contains_hello. Now you can use
the truth value of this response for other operations.

Boolean values come in handy when working with conditional statements,


which you'll look at a little later in this course.

But you don't need to ask Python a question in order to get access to a
Boolean value. You can also directly assign them to variables just like you
would with any other values:

yes = True
no = False

Assigning a Boolean value to a variable allows you to use its truth value for
further operations. One common example is to specify a flag with a truth
value. Your code can take decisions depending on the truth value of that
flag. Other parts of your code may change the flag when a specific condition
occurs.

Note: Boolean values in Python are capitalized. You will run into an error if
you accidentally write them in lowercase.

Allowing your code to make decisions based on a truth value, whether it


comes as an answer from a question you asked Python, or it's a Boolean
value you defined yourself, is an effective way to build functionality into your
programs.

You will learn more about how to do this in the next section of this course,
where you'll practice working with conditionals and loops.

Recap

Boolean values can be either True or False and represent their own data
type in Python called bool. They are essential building blocks of computer
logic and useful to allow your programs to make decisions.

After taking this detour into a new data type, you'll now get a chance to keep
working with it when learning about Python's relational operators.

Additional Resources
Wikipedia: Boolean Algebra
Wikipedia: Binary Numbers
Relational Operators
Relational operators in Python are also called comparison operators. These
operators allow you to put values in relation to each other and compare
them.

Comparing Numbers

Python has six relational operators to compare number values. The result of
such a comparison evaluates to a boolean value.

Info: Similar to how you were able to use the + operator both for numbers
and strings, other operators can also work with different data types. You'll
learn to use comparison operators with numbers first, but you'll see how to
use them with strings as well.

Python's six relational operators are:

Operator Meaning Example Result


< Less than 1 < 2 True

<= Less than or equal to 1 <= 1 True

> Greater than 2 > 1 True

>= Greater than or equal to 2 >= 2 True

== Equal to 2 == 2 True

!= Not equal to 2 != 1 True

You might already be familiar with some of these operators, while others are
probably new to you. Keep in mind that each of them represents a single
symbol, even if it consists of two characters. This means you always need to
write them without any space in between the characters to keep Python
from complaining.
Comparison operators work on numbers and you can ask Python questions
that it will diligently answer with Boolean values:

1 < 2 # True
1 == 2 # False

However, they also work on other data types that can be compared to each
other, for example, strings.

Info: For an operator to work on a data type, it needs to be implemented for


that data type. Not all operators are implemented for all data types, since not
all operators make sense for all data types. For example, what would be an
exponent of the string "hello"?

Comparison operators, especially == and !=, are commonly used in Python


programs. Your code might want to make decisions based on comparing one
value to another one, also if these values are not numbers.

This is why comparison operators are implemented across the most


common Python data types. You can compare numbers to numbers, and
strings to strings:

# Comparison operators work on numbers


1 < 2 # True
1 == 2 # False

# And on other datatypes


"hello" == "hola" # False

In this example, you're asking Python whether one string is the same as
another one. While a bilingual human might say that "hello" and "hola"
mean the same thing, Python doesn't think about meaning at all.
It just compares whether the first sequence of characters is the same as the
second sequence of characters. Since it isn't, Python answers you with the
Boolean value False.

Tasks

Test all the different operators and make sure you understand what they
do.
Can you compare strings using > and <?

When comparing strings to one another, you can do more than just find out
whether one string is the same as another one.

Comparing Strings

In Python, characters have a specific order---just like numbers do. This


means that you can use the same comparison operators on strings as you
did with numbers. Go ahead and play around with them and see whether you
can figure out the underlying pattern.

Tasks

What is larger: "a" or "i"?


Who is smaller: "Harry" or "Sally"?

Use the code playground below to try using all the different comparison
operators on strings and answer the questions above.

What is the intrinsic order that alphabetic characters have that Python could
use to compare against? Feel free to speculate and share your thoughts, and
read up on those of others, in the forum thread The Order of Strings.

If you find that they have a logical order, then you'll be pleased to hear that
the type of Python operators you'll learn about next will be logical operators.
Logical Operators
Logical operators are also known as conditional operators. They are
implemented following Boolean algebra. If you ask Python a question using a
logical operator, then Python's answer is---again---a Boolean value.

There are only three logical operators, and yet you can build entire
computers with this logic:

Operator Meaning Example Result


True and
and True if both operands are True True
True

True or
or True if either of the operands is True False
True

Trueif the operand is False, False if the


not not False True
operand is True

If you happen to have access to a Minecraft installation, you can use it to


play around and learn about Logic circuits that are built based on Boolean
algebra. You can even build your own computer inside of a computer world
like that!

Practice using logic operators with some examples in the code playground:

You can use the following truth table as a reference until each operator
makes sense. The first two columns show the initial values of the variables p
and q. The other columns display what truth value is the result from applying
the logic operators on these values:

p q p and q p or q not p not q


False False False False True True
True False False True False True
False True False True True False
True True True True False False
Keep coming back to this truth table if you are unsure about how to use one
of the logical operators.

Tasks

Think of a logical comparison that uses at least two different logical


operators and implement it in code.

Keep in mind that you'll usually want to compare the same data types with
each other when using any operators. You can think of it as comparing
apples with apples, and oranges with oranges. That also means that you
might get errors or unexpected results when comparing apples with
oranges.

Info: Feel free to play around and see what happens when you compare
other data types using logical operators. The results may seem confusing!
You can set your doubt aside for now and keep moving forward since you'll
learn more about this later on. If you want to peek ahead, check out What is
truthy and falsy.

By tackling the basic rules of Boolean algebra and its implementation in


Python using logical operators, you've nearly made it to the end of Python's
commonly used operators. In the next lesson, you'll get to know the final
one, called the identity operators.

Recap

Logical operators are used to putting Boolean values in relation to each


other. There are a total of three logical operators, and, or, and not. They all
return Boolean values as well, according to specific rules defined in Boolean
algebra. You can practice using them and check the truth table until they
make sense to you.
Identity Operators
Python offers the operators is and is not to compare the memory location
of two values. These operators are called the identity operators and both
evaluate, yet again, to Boolean values.

Now, what does it mean to compare the memory location of two values? To
better understand this, you'll take a peek below the comfortable cover of
abstraction that Python lays over a computer's internal operations.

You've heard about different data types in Python and you got to know int,
float, str, and bool already. You learned that these are different from each
other, in the sense that you can do different things with and to each of the
data types. However, by the nature of how computers operate on the basis
of 0 and 1, they are all the same at some level deeper down. You just need to
dig deep enough.

Now, Python has another level of abstraction where these data types are
conceptually the same. All of them are objects. You will keep hearing this
sentence over again, and it might take a while until it clicks:

In Python, everything is an object.

That's right, every int is an object, and every str is an object as well. And if
you go one step further, you'll see that every new variable you define, even if
it has the same value as another variable, is a new object.

Such an object is a pretty abstract thing, but for now, you can think of it as
an item in a particular memory location. It is the digital representation of
what takes up some space on your physical computer memory. Pretty cool,
huh?

Different objects can have the same values. You've learned how to compare
two values with each other in the lesson on comparison operators. Here you
can recap and dive deeper:

num_1 = 123456
num_2 = 123456

num_1 == num_2 # True

In this example you see two integers, num_1 and num_2 that both have the
same value 123456. When you use the comparison operator == to compare
their values, Python confirms that these are the same.

The identity operator, on the other hand, doesn't compare the values of two
objects but looks at whether they are both found in the same memory
location. That means you're asking Python whether these two variables are
the exact same object:

num_1 = 123456
num_2 = 123456

num_1 is num_2 # False

Even though num_1 and num_2 are both integers with the exact same values,
they are different objects in memory. This is what you can check with
Python's identity operator.

There are two versions of the identity operator:

is: Returns True if the variables on the left and right side of is point to
the same object
is not: Returns True if the variables on the left and right side of is not
do not point to the same object
There are only these two versions of the identity operator in Python. As you
can see, one of them is a negation of the other one. Two objects either do
point to the exact same memory location, or they don't.

Tasks

Open up your Python REPL and try this out. Use higher numbers and longer
strings for the expected results. Don't use the online playground for this
exercise.

Recap

The comparison operator == checks for the same values, and the identity
operator is checks for whether they are the same object in memory.

Identity Confusion: Python Caches Small Immutable


Objects

However, there's a little catch here that might trip you up when playing
around with this in your Python interpreter. For performance reasons, Python
caches small numbers and strings. This might run you into a head-scratch-
situation if you've never heard about it before:

num_1 = 5
num_2 = 5

num_1 == num_2 # As expected, this returns True


num_1 is num_2 # Surprisingly this is True too!!

You'd expect the second check to evaluate to False as it did when using the
larger numbers in the example further up. However, due to caching, it
doesn't.
In the case of small immutable objects, Python cuts some corners and saves
time by not creating a new object but only referencing one that already
exists. That's unintuitive when you just thought you understood Python's
object identity. But equipped with this little nudge, you'll be fine!

You don't have to dive deeper than this, but if you want to, you can read
more about it in the resources below.

Additional Resources

Journal Dev: Python id()


WS Vincent: Python Integer Caching

This final operator, paired with a surprising behavior of Python, wraps up the
list of Python operators described in this course section.

But there is one more thing to discuss, which is operator precedence, or how
to know what gets evaluated first when you have a lot of them in one line of
Python code.
Operator Precedence
By now you got to know a whole bunch of different operators that you can
use in Python. And even though you learned about them in different lessons,
you can mix and match and use them together in your code.

But once you start using more than one operator in an expression, you'll
have to know which of them gets evaluated first! What is each operator's
precedence? Just like in math, depending on what order the values in an
equation are written, you can get different results.

For example, what would you expect 5 + 5 * 10 to equal? Would it evaluate


to 100 or 55:

5 + 5 * 10

Python follows similar rules as mathematics regarding the order of execution


of different operators. Try it out in the code playground below:

Did you get it right? Generally, the operator precedence in Python works the
same as it does in mathematics. However, since Python includes some
concepts that you might not know from mathematics, it can be helpful to
consult a table.

Operator Precedence Table

Check out the table below describing operator precedence in Python. It is


ordered from highest precedence to lowest:

Operators Description
** Exponentiation
*, /, %, // Multiplication, division, modulo, floor division
+, - Addition and subtraction
<=, <, >, >= Comparison operators
==, != Equality operators
=, %=, /=, //=, -=, +=, *=, **= Assignment operators
is, is not Identity operators
in, not in Membership operators
not, or, and Logical operators

While this is already a long list, it still isn't a complete list of all Python
operators. This course focuses on the most commonly used ones. Feel free
to hop over to your favorite search engine and look for a complete list, if your
mind is ready to soak up some additional, more curious, and lesser-used,
operators. Or you can rest assured that this is all you need to know for now
and keep moving.

Info: There's no need to memorize this table. Just keep it in mind that there
is a rule to operator precedence. Just like for many things in programming,
being aware of a concept is the most important step. You can always come
looking for this information, or find it online when you need it.

Parentheses

If you ever feel unsure about what the operator precedence will be in an
expression, then you can use parentheses to make sure it gets evaluated as
you want it to. Yet another thing that Python shares with mathematics.
Parentheses are helpful because they can make the intended precedence in
an expression clear and easier to understand.

For example, the order of execution can easily be confusing when you think
of a long expression with many different operators:

2 ** 3 + 12 == 20 and "hello" != "hussah!"


What is the result of this expression? Hard to say at a first glance! Python
has no problem evaluating this quickly, but you always want to write your
code so that it's easily readable for a human. Adding parentheses can help:

((2 ** 3 + 12) == 20) and ("hello" != "hussah!")

Both expressions above are exactly the same for your Python interpreter, but
the second one is easier to parse for a human reader.

Info: There is a balance when using parentheses, so no need to go


overboard with them. But when you see some long and complicated
expression that uses a set of different operators, remember that you can use
parentheses to structure and clarify what you want to achieve.

In the example above you didn't change the order of execution and used
parenthesis only for emphasis. However, just like in mathematics, you can
also use them to change the order in which parts of your code should be
executed:

2 ** 3 + 12 == (20 and "hello") != "hussah!"

Using the exact same values you can get a different result just by placing the
parentheses in a different way. This changes the order that the different
parts of this expression get executed and produces a different result.

Tasks

Try using the operators you learned in the code playground above and
see if they evaluate how you expect.
Wrap parts of your code in parentheses and watch how it influences the
order in which operators get executed.
Recap

Python follows a strict order of precedence when evaluating expressions


with more than one operator. Generally, this order follows how it's done in
mathematics. When you're unsure, look it up!

This lesson wraps up the section about operators and Booleans. You learned
about many Python operators and their use cases:

Assignment Operator: Refer a symbol to a value


Arithmetic Operators: Do arithmetic calculations
Membership Operator: Checks whether an element is part of a
collection
Relational Operators: Compare two or more values to each other
Logical Operators: Compare values on the basis of logic
Identity Operator: Finds out whether two values point to the same
object in memory

You also got to know the Boolean values True and False and saw how
Python uses it frequently to respond to questions you ask with many of the
operators you learned.

In the upcoming section, you'll get to use operators and Boolean values to
let your code take decisions in conditional statements, and learn about the
loop construct that allows you to perform an action on each element of a
collection.

If you've been looking for more action when coding, it's about to get exciting
for you! :)
Conditionals Overview
Generally, Python programs execute from top to bottom, from one statement
to the next. But sometimes you don't want that. Programs get way more
interesting once you can change this default order of execution. Control
statements within the code allow you to change the flow of your programs.
In this section, you'll learn all about two ways of changing the control flow:

1. Conditional statements
2. Loops

Get ready to mix it up!

Recap: Boolean Values

You've learned about the Boolean values True and False earlier in this
course. If you need to revisit them, head back to the previous section and
revisit the lessons there. You'll see that these truth values are an important
aspect of allowing Python to make decisions.

Once you're confident that you know True from False, you're ready to write
code that allows your programs to make decisions.
The if Statement
Conditional statements are adaptations to the default control flow. They
allow your program to make decisions. You'll get to know the following
keywords and their usage in this section:

if
else
elif

All three of them are used to make decisions in your program. The most
important one of the three is the if keyword, which is used in the aptly
named if statements. You can use if without the other two keywords, while
you can use those only in combination with an if statement.

The if Statement

The if statement allows your program to make decisions. There's not a lot of
freedom in what these decisions are---you're still miles away from real
Artificial Intelligence. But conditional statements give your programs much
more flexibility.

The idea of an if statement goes as follows:

if something is True, then do what follows in the indented part below.

To clarify this concept, you'll look at a code implementation of a basic if


statement:

if True:
print("yay!")
If the condition following the if keyword evaluates to True, then the indented
code gets executed. Otherwise, Python just skips it.

Info: Indentation has meaning in Python! You need to indent the code after
the conditional statement exactly four spaces.

In the above example, the code will always get executed, because True---
well---it's always True! So in this case your code doesn't have to think much
before knowing what to do. However, your conditional statement that follows
the if keyword can be any code expression that evaluates to a Boolean.

In the previous section, you got to know a lot of Python expressions through
operators that evaluate to either True or False. You can use any of them to
create a more interesting conditional statement. You can use any expression
that Python can ultimately turn into a truth value.

Flags

One common way that decisions are made in your programs is through the
use of flags:

flag = True

if flag == True:
print("yay!")

This code snippet will currently always print yay! because you never change
the value of the flag variable. However, you could make that switcheroo
happen!

Tasks

Add a second conditional statement to the code snippet above that


executes only if the flag variable is False.
Run the code and confirm that the second print() statement doesn't
get executed.
Now add a line to your first conditional statement that changes the
value of flag to False in the indented code block.
Run the code again and confirm that both print() statements now get
executed.

What happened here? You used the changing state of your flag variable to
gently guide your code to do what you wanted it to do.

Info: Keep in mind that flag is just a variable name. You could name this
variable anything you wanted to. The concept of using the state of a Boolean
value to decide what to do in a conditional statement is sometimes called a
flag, which is why you named the variable like that for this general example.

Recap

When using the if statement, you can write code that gets executed only
under certain conditions. You've used a straightforward check for the value
of a Boolean, but you could have used more complex conditions as well.

In the next lesson, you will use more complex conditions, and you will add
the else statement to your control flow.

Additional Resources

Control Flow: The if Statement


The else Keyword
In the previous lesson, you wrote your first conditional statements using the
if keyword. After finishing the task, you ended up with a code snippet
similar to the one below:

flag = True

if flag == True:
print("yay!")
flag = False # Reassign the flag value

if flag == False:
print("yo!") # Now this prints too!

You changed the state of the flag variable to weave your way through the
code and make sure that both print() calls will execute.

Now you only want one of the conditional code blocks to execute. Which
one? That should depend on the state of your flag. In this scenario you can
skip re-assigning its value:

flag = True

if flag == True:
print("yay!")

if flag == False:
print("yo!")

In the example above, the value of your flag variable decides which of the
two print() calls will run. While this works, there's a more elegant and
concise way to do the same.

Using if And else

Because your Boolean flag should only be True or False, you can write a
more concise version of the code by adding the else keyword:

flag = True

if flag == True:
print("yay!")
else:
print("yo!")

If the conditional statement next to the if keyword evaluates to True, then


the first indented code block runs. In this case, the second code block gets
skipped.

If the conditional statement evaluates to False instead, then the first


indented code block gets skipped and the second one gets executed.

Tasks

Write a conditional statement that encodes Hamlet's famous phrase To be,


or not to be into Python code.

As you can see, using the else keyword in your conditional statements can
make your code more concise and user-friendly.

Using More Complex Conditional Statements

Great! You managed to cut down the necessary code and even made it
easier to read. So now it's time to ditch the flag completely and introduce
more complex conditional statements following the if keyword. For example:

if 2 + 2 == 4:
print("Math was right!")
else:
print("Whoa! Quantum Mechanics? 1984? Halpp!!")

In this example, you are using the expression 2 + 2 == 4 following the if


keyword. The expression evaluates either to True or False, in this case, it will
be True.

Info: You can use any Python expression that evaluates to either True or
False as the decision-maker in your conditional statement.

Just like in the example further up in this lesson, if the expression following
the if statement evaluates to True, then the first indented code block runs.

If the expression evaluates to False, then the first indented code block gets
skipped and the second one, following the else keyword, executes.

Tasks

Write three different if-else constructs that each use different


operators to decide which code block should run.
Return to the section about operators and booleans to refresh your
memory.
Can you think of a small game that depends on taking such decisions?
Post your ideas in the forum thread on Conditional Games.

There are a lot of decisions that you need to take on a daily basis, and your
code needs to be able to make decisions as well. Using conditional
statements with if and else gives you a concise way of expressing different
paths your code can take.
Recap

The indented code block following the else keyword gets executed when the
conditional statement following the if keyword evaluates to False.

Sometimes the decisions you need to make aren't as clear-cut as a Boolean


this or that. Python knows the world is more grayscale than that and offers
you a way to choose multiple paths in a conditional statement by adding the
elif keyword to the mix.

Read more about how to use it in the next lesson.


The elif Statement
Some might say that Booleans make your life more simple. With them, it's
either this or that, either True or False.

But you can also make the world more complicated than that. And Python is
happy to help you tackle that decision complexity as well, by using another
keyword for conditional statements called elif, which stands for else if.

The if - elif - else Construct

If you are confronted with a slightly more nuanced decision than Hamlet, you
need more than just two options.

At least the decision you'll need to take is much less impactful than his: After
opening your fridge, you find that you have an apple and a pizza at home.
Now, what should you eat? Time to consult with your inner hunger levels and
run that by your conditional decision-maker:

hunger = "small"

if hunger == "big":
print("Eat the pizza")
elif hunger == "small":
print("Eat the apple")
else:
print("Don't eat anything")

Both expressions following the if and the elif keywords consult the value
of the hunger variable and compare it to a hard-coded string:

if checks whether the value of hunger is equal to "big"


elif checks whether the value of hunger is equal to "small"

Only one of the code blocks associated with these checks will ever execute.
If the hunger variable would point to the string "big", then your code would
print "Eat the pizza". The rest of your conditional construct would get
skipped, meaning that neither the elif nor the else check would ever even
run.

In your case, however, the hunger variable points to the string "small". So
this is what happens here:

The if statement checks whether the hunger variable points to the


string "big"
Since it doesn't, the indented code block under if gets skipped
The elif statement checks whether the hunger variable points to the
string "small"
Since it does, the indented code block under elif gets executed
The string "Eat the apple" gets printed to your console
Since the expression following the elif keyword evaluated to True and
the associated code block ran, Python skips the following two lines
associated with the else keyword

If the hunger variable had pointed to anything else aside from "big" or
"small", then the else keyword would have sprung into action. The indented
code block that follows it would have executed, and your code would have
printed the string "Don't eat anything".

Info: The else keyword is a catch-all. Your hunger variable can have any
other value, even if it is of a different type, such as a number. The else
keyword will execute unless one of the if or elif keywords above has. If you
don't want that, then you don't need to use an else block.

Great! Thanks to your thorough hunger-introspection and your trusted


decision-maker code, you ate just what you wanted to eat. However, what
about if your hunger level would have been... "medium"?

In your case, the code would have told you not to eat anything, but that
wouldn't have satisfied your belly!

Using Multiple elif Statements

Python allows you to chain as many elif keywords into your decision-
making code as you want to. There are no limits to this! You can make your
world of decisions as complicated as you want to.

Tasks

Add another elif statement that covers your cravings when your
hunger level is "medium".
Add a third elif statement that helps you to handle a "giant" craving.

Up to now, you have only compared strings to other strings using the
equality operator (==). As you learned earlier, there are a whole lot of other
Python operators to choose from, when making decisions.

Some of them introduce a little trickery that you need to be aware of when
working with conditional statements, namely that there is a specific order of
execution of these statements which goes from up to down.

Order Of Execution

Conditional statements get executed from top to bottom, line-by-line. If the


first if statement catches, then the other conditionals get skipped
completely. If the next elif statement catches, then the remaining parts of
your conditional statement won't execute. And so it continues.

Info: A line in a conditional statement only gets executed if the line above it
didn't catch.

This is why you need to consider how you structure your checks and where
you place them in the overall conditional block.

Consider the code block below, where you want to find out whether a
number is divisible by two or four. At first glance, the code looks fine:

number = 2

if number % 2 == 0:
print("divisible by two")
elif number % 4 == 0:
print("divisible by four")
else:
print("not divisible by two or four")

Go ahead and run the code. See how it returns the expected solution when
you pass in values such as 2, 5, or 10.

However, there's a problem with this code snippet that relates to the
sequential order of execution of statements in a conditional code block. Can
you spot it? What happens when you enter the value 4 as the number?

As you might have discovered, the first conditional statement if number % 2


== 0 will catch when you run the code using 4 as the value of number. The
reason for this is that 4 is divisible by 2 without a remainder. Therefore, the
first expression following the if keyword returns True, and the rest of your
conditional code block gets skipped.

However, you wanted to print a different message if the number was divisible
by 4! Remembering that the code gets executed line-by-line and that
subsequent lines get skipped if one statement catches, you can refactor the
code to work as expected:

number = 4

if number % 4 == 0:
print("divisible by four")
elif number % 2 == 0:
print("divisible by two")
else:
print("not divisible by two or four")

By changing the order of the checks you apply to your number, you first catch
all the values that are divisible by four. Only values that aren't will be passed
forward to the elif check. Those that are divisible by 2 but not by 4 will
catch here, and the rest gets passed on to your else statement.

Recap

In this lesson, you learned about how to add elif statements to your
conditional code logic to make more specific decisions. Here's what you
should remember:

Required: if statements can exist by themselves, but elif and else


statements require an if statement before them.
Unlimited: You can use as many elif statements as you want to.
Optional: elif and else statements are optional.
Ordered: Conditional statements execute from top to bottom. Order
matters.
Skipped: If one statement catches, then the subsequent ones get
skipped.

If your conditional logic doesn't produce the output you expected, check the
order you wrote your conditional checks in.
After learning about conditional statements, you will get to know another
way you can control the flow of execution in your programs through Python
loops. Read more about them starting in the upcoming lesson.

Additional Resources

Control Flow: The if statement


Loops Overview
Earlier in this section, you learned how to use conditional statements to
influence the flow of execution of your code. With the keywords if, elif,
and else you were able to make only some lines of your code execute, while
others didn't.

There are more possibilities to influence what code gets executed and when.
The second important concept that you'll learn about in this section is called
looping.

Looping allows you to execute lines of code repeatedly.

Could you please repeat that?

Sure thing :)

Looping

Loops in programming allow you to repeat lines of code according to certain


conditions. Similar to how you used expressions to decide which of your
conditional statements should execute, you can use code to decide how
often certain lines of code should run.

Tasks

What's a real-life example of a loop? Post your thoughts in the forum thread
on Real-World Loops.

You use loops when you want to do something more than once in a row.
Time to work through an example to use this concept in practice. Below,
you'll learn how to use a loop to do an action on each character of a string.

Character Collections
Think back to when you learned about strings. When you read over the
documentation for Python's string methods, you may have discovered a
method called .isalpha().

If you haven't, feel free to go and look it up right now. As the documentation
explains, the method does what its name suggests:

Return True if all characters in the string are alphabetic and there is at
least one character, False otherwise.

You know that strings are collections of characters. Now add to that
knowledge that loops are especially useful for collections!

What if you could check out each character of your string separately, call a
string method on it to figure out whether it is an alphabetic character or not,
and then do something with it? Turns out this is possible to do using loops,
so get ready to give it a spin!

Decipher A Cipher Using A Loop

Your friend sent you a secret message and told you that the text is hidden in
between a bunch of random numbers:

secret = "2349H30023388281E3299371l1l3094842O0333322883"

You could just read over the string and figure out where the characters are
hiding. But Python can significantly speed up that process for you! Also, if
you write a script that decodes this message, then you can use it for any
future secret conversations that your friend might send your way.

Note: Don't worry if you don't yet fully understand the code shown below.
You'll learn about the syntax of loops in the upcoming lessons.
Here's a way you can decipher the coded message using Python and a for
loop:

secret = "2349H30023388281E3299371l1l3094842O0333322883"
solution = ""

for char in secret:


if char.isalpha():
solution += char

print(solution)

In this code snippet, you used a conditional statement with .isalpha() on


the secret variable to pick out only the alphabetic characters and assemble
them into a solution message. Finally, you're printing this message to your
console output.

Info: You can see that you're combining a couple of different concepts that
you've learned about in the course up to now. You'll see that adding loops to
your skillset will considerably increase what you can do.

Try to run the code snippet in your text editor and see what the decoded
message outputs.

Tasks

Play around with your script.


Create a new message and see whether your script can handle it as
expected.

As you can see, using a loop to decode this message took a lot less manual
work. Instead of looking at each character yourself, you let Python tackle the
task in no time at all!
In the next lesson, you'll pick apart the syntax for building a for loop and
practice with additional examples.
The for Loop
In the previous lesson, you learned about the concept of looping and
encountered Python's for loop, which allows you to do definite iteration.

Info: The iteration is called definite because the length of your iterable---for
example your string---defines how often the loop will execute.

Now you'll pick apart the syntax of a Python for loop to understand each
part that makes it up.

A for Loop

You'll start by writing out a small for loop that iterates over a string:

for char in "hello":


print(char)

Can you guess what this code outputs?

Info: Thinking about what will be the output of a code snippet before running
it in your interpreter is a great way to train your coding skills. It forces your
brain to process the code and gives you a chance to uncover
misunderstandings if your guess turns out to be wrong.

When you run this code snippet, you'll see that it prints out each character
of "hello" in a new line. This works because strings are collections of single
characters.

Anatomy Of A for Loop

Looking at the example code snippet above, you'll notice that the for loop
consists of a minimum of two lines of code:

1. Opening Statement: for char in "hello":


2. Body: print(char)

The first line makes up the statement that opens up the body of your for
loop. You can deconstruct this line even further into five separate parts:

1. for keyword (for): This is the same in each for loop. It's the signal for
Python that what follows should be interpreted as a for loop.
2. Iterator (char): This is a variable name. You can call it anything, and
you're encouraged to name it descriptively for what you are looping
over. In this case, you named it char, which is short for character. This
describes well what the variable will refer to in the body of your for
loop. In every iteration of the loop the variable char will point to a new
value, which is the current item in your collection. In this case, it'll be
each subsequent character of the word "hello".
3. Membership Operator (in): This is also the same in each for loop.
You've encountered the membership operator before, and here it's used
as a part of the for loop construct to point to every item in a collection.
4. Iterable ("hello"): This is the collection you are iterating over. Any
object that allows you to loop over it is called an iterable. In your case,
this is the string "hello".
5. Colon (:): The colon is Python's indicator that the first line of your for
loop is ending. Which also means it opens up the body of the for loop.

The first line of your for loop always consists of the same elements, even
though the variable name you give to the iterator, as well as the value of the
iterable, will be different.
The second line of code makes up the body of your for loop. Its body can
contain many more lines of code than just one. The code in the body makes
up the code logic that you apply to the elements in your collection, which
means that most of it will be different for each for loop you write.

Still, there are a few important and repeating elements that you can
deconstruct:

1. Indentation (): Each line of code needs to be indented exactly four


spaces. Indentation carries meaning in Python, and in this case, it tells
Python that whatever is indented is part of the for loop's body. If you
forget to indent a line, Python will not consider it part of your for loop.
2. Code Logic (print()): Any code that you want to run once per element
in your collection. In this example, you're just printing the value of the
char variable, but this could be any modification or calculation you want
to write.
3. Iterator Variable (char): Remember the iterator variable you named
char in line one of your for loop? This is where you get to use this
variable. This variable gets overwritten with a new value each time the
for loop loops back to the start. Since it'll run once for each item in your
iterable, your variable char will therefore point to each item in that
iterable one after another.

Within the body of your for loop, you can write code logic that does
something with each element in your collection, because you get access to
each of them one by one.

Tasks

Apply a string method to each of the characters in a string.


Apply alternating string methods to every second character in your
string.
Create a for loop that prints out aLtErNaTiNg CaPs from the word you
iterate over.

Go ahead and practice writing some for loops. Get in some practice and
wrap your head around this concept, it's really powerful and important!
The range Function
Until now, you've only used the for loop to execute an action for each
element in a collection. However, sometimes you might want to run the loop
a certain amount of times. For this, you could use the range() function:

for i in range(5):
print(i)

The code in the body of this for loop will run exactly five times. In the
example above, you're printing the iterator i during each loop. What do you
think that i will be for the different iterations?

Info: Behind the scenes of range(), you're still doing the same thing as
before with strings. You're executing the action for each element in a
collection. range() creates something similar to a collection of numbers,
starting from 0 to the number you pass as an argument to the function minus
one.

Using range() with a for loop allows you to specify the number of times you
want the code in a for loop to run.

A Sequence Of Numbers

The range() function allows you to do more than just iterate a certain
amount of times. As mentioned in the note further up, it creates an
immutable sequence of numbers, which is similar to the immutable
sequence of characters you got to know as strings.

Just like you can work with each individual character while looping over a
string, you can also perform an operation on each number while iterating
over a range:

for n in range(100):
if n % 2 == 0:
print(n)

The code snippet above creates a range of 100 items, from 0 to 99, and
iterates over each of these numbers. Then you added a conditional
statement that checks for each number whether it is divisible by 2 without
leaving any remainder. Finally, it prints those numbers.

This means that the code snippet will print out all even numbers between 0
and 99.

Tasks

Read up on the documentation of range().


How can you include the number 100 into your calculation?
How can you start at a different number than 0?
What can you do with the step argument?
Step through the execution of a for loop on a range using the Python
Visualizer.

You'll frequently see range() used in combination with Python for loops,
because it represents a quick way of creating sequences of numbers as well
as for deciding how often your loop should execute.

Recap

The range() function creates a collection of numbers that you can use to
iterate a certain amount of times, or work with collections of numbers.

In the next lesson, you'll literally go deeper by exploring how you can create
nested for loops.

Additional Resources

Python Documentation: Ranges


Nested for Loops
for loops are useful beyond doing some action to each character in a string,
or number in a range. You'll keep encountering them and you'll learn more
about how they can be effective tools for your automation scripts.

Going Deeper

Sometimes it might not be enough to use a single for loop to do what you
want to do. It's possible to nest loops within each other and create complex
iterations.

Info: Generally you should avoid nesting more than two to maximum of three
loops within each other.

Creating nested loops can get memory intensive when you're working with
large collections, and they can also quickly get difficult to understand. Still,
there are situations where you'll need to use nested loops. Take a look at this
example:

for i in range(5):
for char in "hello":
print(i, char)

This nested for loop prints out each character of the word hello five times.
To make it easier to see what's going on, you're also printing the numerical
iterator i alongside the characters:

0 h
0 e
0 l
0 l
0 o
1 h
1 e
1 l
1 l
1 o
2 h
2 e
2 l
2 l
2 o
3 h
3 e
3 l
3 l
3 o
4 h
4 e
4 l
4 l
4 o

That's a lot of lines, numbers, and characters! The numbers on the left side
show you which iteration of the outer loop you're in, and the changing
characters show you the iterations of the inner for loop. And just like that,
you get rewarded with four times a happy, vertical hello!

One thing to stay alert about when writing nested for loops is that you need
to be consistent with your indentation. Each loop body needs to be
indented four spaces. Since the second loop is in the body of the first loop,
you end up indenting twice, meaning eight spaces, for the body of your
second loop.

Tasks
Pick apart the nested loop as you picked apart the for loop in the
previous lesson.
Write down what each line of code does in your notebook. Make a
sketch of what's happening in the code.

You might not need to use nested for loops in your scripts much. Still, it's
good to be aware that this is possible, and you might run into some useful
applications for it down the road. However, keep in mind that nested loops
can make your code execution significantly slower. When you're working
with large collections, then there are usually better ways to tackle such
challenges.

Recap

You can nest loops within other loops. It can make your code harder to
understand, but it's sometimes the best way to tackle a challenge.

For now, this is enough about for loops and definite iteration in Python. The
language also has a second type of loop, the indefinite iteration, which uses
the while keyword. You'll learn when you would choose a while loop over a
for loop in the next section. In the upcoming section, you'll also collect and
work with user input on the command line.
User Input Collection
Writing programs is much more fun when they're interactive. For example,
it's hard to imagine a computer game that doesn't allow for some kind of
input from the player. After all, playing gets interesting when you can actually
do something.

Python offers a convenient way to collect user input from the command line
with the aptly named input(). Head over to your text editor, create a new file
that you name collect.py, and add the following code:

user_input = input()

print(user_input)

Save the file and execute it through your command line. The program will
start running and then seemingly stop at a blank screen:

It looks like nothing is happening, but that's not true. You asked Python to
open up a prompt for you to type in your input. Python is patiently waiting
for you to do so.

Give it a try. Once you type in any sort of input and press Enter, Python will
print your input back to the command line:

After Python printed your message back to you, you might also notice that
the terminal prompt changed back to normal. This means that your script
has finished execution and Python went on its well-deserved lunchtime
break.

Nothing too world-displacing has happened here, you may think. All that
Python did was copy the sentence that you typed. Not too impressive,
Python. But that's just because printing a copy was the only thing that you
asked Python to do with your input.

Tasks

Change the script to apply a string method to your input. For example,
let Python repeat everything you say in ALL CAPS.
Then, make Python repeat only every second character from your input.
The subtle input() opens up the gates to your Python script---so you can
flood it with your personal input!

But while you, as the programmer, might remember what to type when
Python goes blank and starts waiting for you, anyone else will probably think
that your program died. And even if they trust your skills as a programmer,
they will still not know what they are supposed to type in here! Luckily,
input() takes an argument that can help with that.

The Input Prompt

You can add a string in between the parentheses of input() and Python will
display that message while waiting for your input. Improve your script by
adding an explanatory sentence:

user_input = input("Enter something for Python to echo back: ")

print(user_input)

Save and run your script another time. Now Python will display the input
prompt and make your program more understandable:
Whatever text you add as an argument to input() will be displayed when
you run the program.

Tasks

Add descriptive input prompts to the string-altering programs you wrote


in the previous task.
Create a sarcastic program that asks a user for their honest opinion,
then prints the same sentence back to them in aLtErNaTiNg CaPs.

Next, think back to using Python as your calculator. You could simply type
numbers and operators into your console, and Python evaluated the
calculations for you. What if you wanted to create a calculator that displays
nice input prompts:

number = input("Enter a number you want squared: ")

print(number ** 2)
User Input Conversion
In the previous lesson you saw that when you try to collect a number as
input from your users, Python actually collects the number as a string. You'll
have to explicitly convert the user input to a number:

user_input = input("Enter a number you want squared: ")


number = int(user_input)

print(number ** 2)

In this code snippet, you're calling the int() type conversion on the user
input. As long as your users actually input a number, this code will work as
expected. It will convert the str of a number that comes in via input() into
an int, which Python can then raise to the power of two and print back to
the console:

However, your users need to be nice to your program and actually enter a
number for this calculation to work. Otherwise, Python will decide to quit and
let you know about it by displaying a ValueError.

Info: There are ways to make sure that your program continues also if a user
enters something that can't be converted to an integer. This is called
Exception handling, and you'll learn more about it in a later section of this
course.

For now, you should probably just show your program to your close friends
who are not set on tripping up your code in its early stages :)

Deconstructing Guess-The-Number

With this, you now deconstructed another line in the colorful coding
concepts image, collecting user input:
You can see that the two lines right at the beginning of the while loop look
very similar to what you wrote further up:

guess = input("guess a number between 1 and 10: ")


guess = int(guess)

You could also write this in a more compact way by applying the type
conversion right to the output of input(), instead of first assigning it to a
variable:

guess = int(input("guess a number between 1 and 10: "))

Keep in mind that there's no input validation in this script, so you'd currently
be able to break the guess-the-number game by entering a character
instead of a number.

You'll learn more about how to fix this later on. Now it's time to continue on
the journey to decipher the last remaining parts of this code graphic. Your
next stop is the while loop.

Recap

All user input collected with input() is of the str data type. If you want the
collected data as another data type, then you need to explicitly convert it, for
example by using int().

If the user input can't be converted to the data type you want, then Python
will let you know by stopping the program and displaying a TypeError.
The while Loop
There are two different kinds of loops in Python. You can use them to do
different types of iteration:

1. Definite iteration: for loop


2. Indefinite iteration: while loop

You've already learned about the for loop in the previous section, and now
you'll get to know the while loop.

You can do the same with either of the two types of loops. However, they
have preferred applications. While for loops are much more common in
practice, one good application of while loops is when you are asking for
specific user input.

Python's while loop has a different basic assumption than the for loop. It
doesn't have an automatic stop condition built-in. for loops run only as often
as there are items in your iterable. while loops don't have this limitation.

Infinite Loops

The lack of a built-in exit condition means that you need to take care to avoid
accidentally creating an infinite loop:

while True:
print("loopy, loopy, loopy...")

Don't try this at home, because that's an infinite loop. It's endless. True will
always be True, which means that it just doesn't stop. Just like this
description of infinite loops doesn't seem to stop. Even though you already
understood what an infinite loop is. It just keeps going on. Forever. That's
kind of annoying, right?

Info: If you do want to try running this infinite loop, just go ahead! There's
actually no danger associated with it and you won't break anything. Just be
ready to quit your text editor once it gets stuck.

An infinite loop in programming describes a program that keeps running


without ever being able to stop.

Because indefinite loops, such as the while loop, don't have an exit
condition built-in, you might end up creating infinite loops by accident. When
you're starting out, it's, therefore, easier to begin with using for loops that
end by themselves.

Photo by Joe Ravi - CC BY-SA 3.0

Info: Apple's campus is called the infinite loop. Probably because it's a
circle-shaped building, and very likely also as a joke for the resident
programmers. The campus was definitely not created by accident ;)

However, there are some good reasons for using while loops, such as
collecting user input for a game. Get ready to pick one specimen apart to
make sure that you understand how it works.

Anatomy Of A while Loop

When taking apart a while loop, you might see that it shares more
similarities with a conditional statement than with the for loop. To start
dissecting, you'll first need a while loop to pick apart, so here's a really
annoying one for you to try out:

name = None

while name != "your name":


name = input("Please type your name: ")

print("Finally!")

Can you see what this loop does and where the joke lies? Save it to a file and
give it a go. It's not a great joke, but it'll do for learning about the anatomy of
the while loop :)

The program starts by creating the name variable and setting it to the value
None. This is necessary so that the first iteration of your while loop will be
able to compare its value to "your name". After the first go-around, the name
variable will point to whatever input your user gave this time around.

The first line of the while loop represents the loop statement. You'll pick it
apart just like you did with the for loop. As you might see, it shares
similarities both with a conditional statement as well as with a for loop.
Considering this, you can split it into three distinct parts:

1. while keyword (while): This is the same in each while loop. It's the
signal for Python that what follows should be interpreted as a while
loop.
2. Conditional Statement (name != "your name"): This expression
evaluates either to True or to False. name needs to point to an existing
variable, otherwise Python will get confused. The result of this
expression decides whether the while loop will continue or not.
3. Colon (:): The colon is Python's indicator that the first line of your
while loop is ending. Which also means it opens up the body of the
while loop.

You might notice that this looks similar to an if statement. It might help to
think of a while loop as a repeatedly evaluated if statement, where one of
the values of the condition can change inside the loop body.

As long as the expression keeps evaluating to True, the loop keeps going.
Once it evaluates to False it stops immediately and continues execution
after the body of the while loop.

This brings you to the second line of code in this loop, which represents the
loop's body. It consists only of one line of code, but just like with the for
loop, there could be many more. Anything that is indented four spaces is
considered to be part of the loop body.

The Exit Condition

What makes the while loop interesting, is that it needs to have a possible
exit condition built in. While your loop runs, it needs to be able to change one
of the variables that make up the conditional check in the while loop's
opening statement.
Note: If there is no such possibility, then you're dealing with an infinite loop.

In the case shown above, there is an option for the conditional check to
change its outcome. Every time the user submits an input, the name variable
changes, giving the conditional check name != "your name" a chance to
return False and end the while loop.

The only option for the check to return False, is when the user enters the
exact string "your name". Until they get the joke and do so, the while loop
will just continue to ask the same question.

The Rest Of The Script

The final line of code in this script is a concluding print():

print("Finally!")

You can see that this line is not indented, which means that it isn't part of the
loop body. This line will only execute once the while loop has stopped the
execution, which will only happen when the user inputs the correct string.

As soon as the condition in your while loop has evaluated to False only
once, the loop is left behind and any remaining code in your script that
follows the loop will run.

Tasks

Pick apart the while loop in the guess-the-number game. Make sure
you understand what's going on.
Emulate the functionality of a for loop using a while loop. How can you
create an exit condition that stops the loop after a set amount of times?
Play around with the example code for support.
Looping Keywords
Sometimes you might want to exit your loop early. Doing so could save
execution time. Python offers a few loop keywords that allow you to change
the flow of execution within your loops. When you use the right loop
keywords, you can even escape from an otherwise infinite loop.

Python has two loop keywords that can change the flow of execution in a
loop:

1. break
2. continue

In this lesson, you'll learn what these two keywords mean and when to use
them.

The break Keyword

The break keyword ends the execution of the loop. It skips any code that
comes after it inside the loop body. The execution continues after the loop
body.

Breaking Out Of for Loops

The following example code prints all consonants in a word until it


encounters the first vocal. Then the break keyword kicks in and kicks you out
of the loop. The code continues to run after the loop body, effectively
skipping print(char):

word = "hello"

for char in word:


if char in "aeiou":
break
print(char)

print("done")

Try the code in your text editor. What does it print for the word cradle?

Breaking Out Of while Loops

You can use the break statement to break out of an infinite loop, for example
when you are waiting for a specific input from a user. Using this keyword,
you can write your code in a way that creates an infinite loop that has an exit
condition that leads to a break keyword:

In the example above you are creating an infinite loop with the while True:
opening statement. This will never be False, so the loop would keep going
forever.

However, you also added an exit condition with the break statement:

if prompt == "quit":
break

The while loop incessantly echoes the reverse string of what the user typed
unless they type the word quit. This makes your conditional statement
evaluate to True and the code inside the conditional block executes.

The conditional block consists only of the break statement, which is enough
to kick your program out of the infinite loop.

Tasks

Write the same program without using the break keyword. How do you
need to structure it so it still has an exit condition?
What's a possible advantage of using the while loop with the break
statement over the one without it? You can read and add your thoughts
in the forum thread To break Or Not To break

The break keyword gives you additional possibilities of structuring the flow
of execution in your loops.

The continue Keyword

The continue keyword jumps back to the beginning of the loop. It skips any
code following the keyword in that specific run of the loop. The loop doesn't
quit, however, it just starts again from the top with the next round of
execution:

word = "hello"

for char in word:


if char in "aeiou":
continue
print(char)

print("done")

If you run this code in your IDE, then you'll see that it prints out every
consonant of the word, but skips printing the vocals.

Tasks

Compare this code snippet to the similar one that uses the break
keyword instead. Run them both and investigate their different outputs.

You can also use the continue statement in both the for as well as the while
loop. Each type of loop and each loop keyword dictate a different setup of
your code.

Often, you can achieve the same outcome with a couple of different setups.
You can mix and match different loops and different loop keywords. You can
practice translating between different setups by taking existing loops and re-
writing them using e.g. a while loop with a continue keyword, etc.

Recap

There are two keywords that you can use to alter the flow of execution in
your loops:

1. break quits execution of your loop. Nothing within the loop body that
follows the keyword will be run, and your code continues after the loop.
2. continue skips the rest of the current iteration of your loop. It brings
execution back to the beginning of the loop, and the next iteration
begins.

You can use these keywords to construct your loops in different ways.
Usually, there are many ways of constructing a loop that achieves the
functionality you want.

Info: Getting more familiar with different ways of writing the same
functionality helps you understand that there isn't one "right" way to write
code. Instead, it's a creative process where you can often pick what works
best for you in a specific situation.

In the next lesson, you'll use your newfound knowledge about loops and user
input to build out a command-line game. That's right! Time to build a game!

Additional Resources

A Byte Of Python: The break statement


A Byte Of Python: The continue statement
Project: Command-Line Game
You've already collected a lot of programming knowledge in this course. It's
time to put it to a test and build a command-line game. Ready? Do you have
all your game pieces in place?

For this project, you'll build a text-based command-line game. Your players
will get the chance to make decisions by entering text in their terminals. Your
game will respond with different outcomes, depending on what they chose.

The first version of this game won't be very advanced and probably only fun
to play once or twice. However, you'll have the chance to keep expanding on
it when moving ahead in the course. By the end, you might have a fun and
immersive game in your hands.

Game Mechanics
The game will be a classic text-based Dungeons and Dragons game:

Here are the first tasks that you'll code up in this lesson. You'll read them
String Formatting
If you're handling a lot of string output to communicate information from
your program to users, then concatenating long string messages can quickly
get messy.

Python 3.6 introduced a new version of string formatting called f-strings


that makes this task more enjoyable.

F-Strings

Using f-strings, you can format your strings with a concise and very readable
syntax that embeds any Python expressions right into your string:

name = "Tom"
age = 99

print(f"Hello {name}. Next year you'll be {age + 1}!")

The syntax for f-strings consists of two parts:

1. f: To let Python know that you want a string to be an f-string, you need
to add the letter f, or F, in front of the opening quotes.
2. {}: To inject the value of a variable, or the result of an expression, into
your f-string, you need to wrap the code into curly braces ({}).

As you can see from the example above, this syntax allows you not only to
add variables directly into the string, but you can even do all sorts of
calculations right in between the curly braces.

As long as the code you add in there is an expression, you can make it
directly part of your f-string.
Info: An expression is any combination of programming logic that evaluates
to a result. For example, adding two numbers together is an expression
because it results in the sum of the two numbers.

With the f-string syntax, you can create strings in an intuitive way:

print("Welcome to the unfulfilling market!")


print("Tell us what you want, and we won't have it.")

food = input("What do you want? ")


amount = int(input(f"How much of {food}? "))

print(f"You want {amount} {food}? Sorry, we only have {amount - 1}.")

In this example, the vendor in the unfulfilling market asks the customer what
they want and how much of it. Then they proceed to tell the customer that
they don't have enough of it.

You can see that you're using two f-strings in this example, which makes
writing the communication strings more intuitive for you.

str.format()

If you are working with versions of python that are older than 3.6, you can
use str.format() to format your strings. It provides a similar syntax:

name = "Tom"
age = 99

print(f"Hello {}. Next year you'll be {}!".format(name, age + 1))

The advantage of using f-strings over str.format() is that f-strings are


better readable, especially in long strings that include many variables.

You can also pass an index to the curly braces ({}) in str.format():

print("{0} is not {1}, but it's {0}!".format("Basil", "Sage"))

Using index numbers allows you to reuse arguments in multiple places in


your string. It also makes it possible to mix up the order in which the
arguments get inserted into the string.

Tasks

Flip the above statement about spices only by changing the index
numbers inside the curly braces ({}).
Rewrite the unfulfilling market vendor code snippet using str.format()
instead of f-strings.

Python includes even more different ways to format your strings. However,
unless you have a specific reason for it, you should stick with using f-strings.

Additional Resources

Seasoned & Agile: The new f-strings in Python 3.6


F-string documentation: PEP 498

Recap

F-strings are expressions that are evaluated when your code is run. You can
construct them by pre-pending a string with f or F.

Using f-strings allows you to insert variables and expressions right into your
strings. You just need to enclose your variables with curly braces ({}).

This syntax makes f-strings intuitive to read and very flexible. It also avoids
repetition and keeps the code clean.
String Mini-Language
In this lesson, you'll get to know a few more helpful tricks to work with
strings in Python:

1. String formatting mini-language


2. Character escaping
3. String concatenation using parentheses

These tips will help you work with longer strings effectively and you can
apply what you need when building out your command-line game.

String Formatting Mini-Language

Python strings include their own mini-language that you can use only inside
of the curly braces ({}) of your f-strings as well as in str.format().

Run the code below in your interpreter and play around with it:

message = "you move me!"


print(f"{message:>20}")

If you run this code, then you'll see that Python moves the message in your
string off from the left side of the terminal.

The mini-language inside of the curly braces allows you to format the
injected values.

Tasks

Play around with this example. You can read more about how to use it in
the string mini-language documentation.
Why did Python add exactly the amount of spaces on the left side that it
did?
What happens when you change the number from 20 to another value?
What happens when you use a different operator instead of >? Can you
figure out their meaning?

The string mini-language is quite powerful and gives you a quick way to add
additional formatting to your string values. It works both for f-strings and
strings on which you call the .format() method.

Character Escaping

Sometimes you'll need to include a character with a specific meaning in your


string. The most common situation that you'll encounter is when you want to
have the quote character that you're using to start a string also as a part of
the string:

message = "The door reads "Do Not Enter!"" # SyntaxError

This code will produce a SyntaxError because Python assumes you ended
the string with the second double-quotation mark. As you've already
learned, you can circumvent this problem by using the other type of
quotation marks:

message = "The door reads 'Do Not Enter!'"


message = 'The door reads "Do Not Enter!"'

Either type of quotation marks, single (') or double ("), work, but you can
only use the other type inside your string.

There is an alternative to swapping out the quotes, which is character


escaping:
message = "The door reads \"Do Not Enter!\""

In Python, you can use the backslash character (\) in front of a character
that has a specific functional meaning. This will strip it of its usual
functionality and treat it as a normal character.

One of the characters you can escape that helps you format long strings is
the newline character (\n), which constitutes a line break. This character is
always there as an indicator to start a new line, even though you can't see it
represented in the same way as most other characters:

print("""hi there,
friend""")

Following the comma (,) in the code snippet above, there is a newline
character (\n) that you see not in its character form, but by the fact that the
next word friend appears in a new line.

If you wanted to print the whole message in one line, you'd need to escape
the newline character. You can do this using the backslash character:

print("""hi there,\
friend""")

This might come in handy when you need to write a long message that you
want to appear in one line, but to make the message easier to maintain in
your code, you want to display it over multiple lines:

long_str = "check out this very long string that is full of wisdom \
so you should definitely keep reading all the way to the end!"
print(long_str) # Prints in one line

However, you need to be careful with your formatting if you use this
technique. The backslash character just escapes the newline character,
which means that everything that follows afterward will be considered part
of your string.

If you would format your string like shown in the example below, you
probably wouldn't get the result you were looking for:

long_str = "check out this very long string that is full of wisdom \
so you should definitely keep reading all the way to the end!"

print(long_str)

Because the backslash escapes the newline character and continues the
string, also the indentation you added for the second line will become part of
your string. Is there a way around this? There is!

String Concatenation Using Parentheses

If you wrap multiple strings broken up into multiple lines inside of


parentheses, then you can concatenate them into one long string:

long_str = ("hei there "


"how are you?"
" remember that this ends up as one string!")

print(long_str)
The advantage of using the parentheses instead of escaping the newline
character is that it allows you to indent the code. Python concatenates the
different string pieces to create one string. When escaping the newline
character, as in the example further up, Python continues the string into the
next line.

Using parentheses around multiple pieces of a string in multiple lines works


also with f-strings. Give it a try and run the code in your text editor.

Recap

In this lesson, you learned about some additional helpful tips for formatting
your strings in Python. You learned about:

The string formatting mini-language that you can use when working
with string interpolation through f-strings and str.format()
Character escaping, which you can use to display quotes and skip
newline characters
String concatenation using parentheses

These tricks can help to format your messages both as output to your users,
as well as to keep longer text easier to read within your code. Apply
whichever of these techniques you need when building your command-line
game.
Game Code Recap
If you haven't yet, make sure to build out the command-line game following
the instructions from a few lessons earlier. Make it exciting!

Once you've got a working version done, show it to your friends and family
and let them give it a spin. Feel free to share a link to your game on the
forum in the thread on Command-Line Games.

Recap

In this section on user input and string formatting, you learned more
important programming concepts:

Collecting user input with input()


Looping with while loops
Changing the flow of execution in loops with the loop keywords break
and continue
Formatting your strings
At this point, you've covered all but one concept that you encountered at the
beginning of this course in the guess-the-number game:

The final puzzle piece that is still missing is how to import and use code that
other people wrote. In the guess-the-number game, you used a module from
the built-in standard library called random, which allows you to introduce
some randomness into your code. This can be fun and helpful, especially
when you're working on games.

In the upcoming section, you'll learn how you can access and use code such
as the random module and dramatically increase what you can build with your
code by climbing on the shoulders of giants who came before you and built
code logic that is powerful and user-friendly to work with.

You'll use one of such modules, called pathlib, to automate some tasks
PROJECT: Write An Article
Write a technical article about the CLI game you built and publish it on
dev.to.

Technical writing is a highly relevant skill for:

Learning: Writing pushes you to practice communicating about code,


which helps you to formulate and solve your challenges.
Employment: You start to build your portfolio and prove your interests
and experience as a programmer.

Don't worry if your first 20+ articles will be quite basic and maybe even
boring. That's okay, you're learning how to program and you're learning how
to write about it! Remember that 20 boring articles are better than 0
interesting ones. And keep in mind that you can make them fun and
interesting, if you want to.

But even if they'll be boring. The most important thing is that you start
writing and talking about code. Publishing articles on dev.to is a great way
to get going. You can read more and get some inspiration by reading why all
developers should blog - no excuses!

Tasks

Write a technical article about the CLI game you built and publish it on
dev.to.
Automation
One of the fun reasons to learn about programming is that you can make
your life a little easier as soon as you know a bit about it. Computers are
good at automation, and your lines of code are the instructions that they
need to know what to do.

In this section, you'll learn how you can interact with the file system on your
computer by writing Python code. Your task is to clean up the mess on your
Desktop:

Someone has been taking way too many screenshots on your computer
without ever cleaning them up! You have to weed through these files and
move all the screenshots into a separate folder. Your aim is a clean Desktop:
But you won't do this manually by moving files over into a new folder.
Instead, you'll write a Python script in which you'll use the built-in pathlib
module to:

Find the files


Select only the ones that are screenshots
Create a new folder
Move the screenshots there

As a challenge, you'll even get the chance to rename the files, so you can
give them a more descriptive name than just Screenshot-date.png.

Ready to start using Python for task automation? In the next lesson, you'll
learn about how to import code someone else wrote and use it in your own
script.
Work With File Paths
Python is a great language for writing scripts to automate tiresome and
repetitive processes on your computer. One of the more interesting tasks to
tackle with Python is to make it interact with your local file system.

Remember that messy Desktop?

It's time that you go and clean it up. I'm serious this time---if you don't clean
your Desktop now, then you won't be going out tonight!

Interact With Your File System

Python offers a couple of different ways to interact with your file system.
You'll get to know a module from the standard library called pathlib. You
can peek into its documentation, but you'll learn about the parts you need
right here in the course.
Start by opening up a new Python file in your IDE. Before writing any code,
you'll first take a step back and think of the bigger picture, and note your
tasks in pseudocode:

# Import pathlib
# Find the path to my Desktop
# List all the files on there
# Filter for screenshots only
# Create a new folder
# Move the screenshots in there

With these rough steps in mind, you're ready to get started building out the
core functionality.

Find Your Current Location

The first task you need to tackle is how to find the location of your Desktop
on your computer, and get its absolute path. You might remember that you
can do that with Bash using the pwd command after you navigate there.

Now, how can you do the same thing using Python and pathlib? It might be
a good idea to start out by figuring out where you are in the first place:

import pathlib

pathlib.Path.cwd() # Returns the path of your current working directory

In this code snippet, you start off by importing the pathlib module from the
standard library. Next, you access the Path object through the pathlib
namespace, and call .cwd() on it.

This will return the current working directory of your script, which will be the
folder where you saved your script in.

Info: Because pathlib is an object-oriented module, you're scratching a


couple of semi-new concepts here, namely objects and methods. You'll
learn more about all of this in a later part of the course. For now, just think of
objects as things, and their methods as ways to make these things do
something.

You might notice that .cwd() has a similar name to the corresponding pwd
command that you can use in your terminal. Both of these commands give
you the path of the folder which you are executing the command from.

Convert Your Path

If you run the code you saw above in your Python REPL, then you'll see
something similar to this:

PosixPath('/Users/martin/Documents/codingnomads/python-course') # Or WindowsPath

That looks like a path, but it's also wrapped in parentheses and before the
path, it says PosixPath, or WindowsPath. What's that all about?

Info: If you wrap the second line of code into a call to `print()`, then Python
will show you only the path as an output:

/Users/martin/Documents/codingnomads/python-course

You'll notice that it's the same path but not wrapped inside of PosixPath or
WindowsPath. The reason for this different output is that a Path object is set
up in a way to print only a string representation of the path when you pass it
to print(). On the other hand, if you run pathlib.Path.cwd() in the Python
interpreter, then Python will show you a more complete representation of the
object that the method returns.

This information about objects and different representations of them doesn't


impact what you're working with. It's here for completeness in case you
wondered why you'll see different output whether you print a Path object or
run the code in the Python REPL. If it sounds confusing, then forget about it
and keep moving, things will clear up along the way.

With the output in the REPL, Python is telling you that you're dealing with an
object of the type pathlib.Path---this is not a string! You don't have to
worry too much about what that means, however. Just remember that you're
getting back more than just a string representing the path to your folder.

You can turn this pathlib.Path object into a str object in the same way that
you converted int objects to str objects earlier on:

import pathlib

path = pathlib.Path.cwd()
str(path)

Applying str() on the pathlib.Path object will give you back just the string
that represents the path to your current working directory:

'/Users/martin/Documents/codingnomads/python-course'

You can think of a call to print() doing pretty much what you did here.
That's why printing a Path object gives you back just the path string, without
the object info around it.

If there's a tiny lightbulb turning on somewhere in the back of your head, that
flickers far away and sends you some thoughts such as is everything an
object in Python?, then just keep that little lightbulb flickering there for a
while. You'll learn much more about objects and how it all ties together later
on in this course.

For now, you'll have some fun interacting with your file system!

Recap

In this lesson, you started to work with Python's pathlib module and started
to prepare for your clean-up challenge by:

Writing pseudocode describing the task at hand


Importing pathlib
Finding your current location using Path.cwd()
Converting a pathlib.Path object to a str

You also learned that there's such a thing as objects and methods in
Python, and you might have heard a faint noise whispering to you that
everything is an object in Python, which you tucked away for future
reference.
List Folder Contents
In the previous lesson, you learned how you can get the path of your current
working directory using Python's pathlib module. In this lesson, you'll build
on top of this and use such a path to list what files are inside of this
directory.

List All Files

When you are working with a pathlib.Path object, such as the one you
created in the previous lesson, then you can do a couple of things with it out
of the box.

For example, you can list all the files that are inside that folder using a for
loop:

import pathlib

path = pathlib.Path.cwd()

for filepath in path.iterdir():


print(filepath)

In this code snippet, you are using .iterdir() to create a collection of all the
file paths of the files that are inside of the current working directory. Then
you iterate over each of them and print them out to your console.

Info: You've encountered a collection before when you learned about strings
in Python. There are other data types that are collections in Python, and
you'll get to know more of them as you keep moving along.

The output you receive is quite long! Those are all the absolute paths of all
files inside this directory.

Display Only File Names

You might just be interested in the file names, however, and pathlib.Path
objects have a way to show you just that:

import pathlib

path = pathlib.Path.cwd()

for filepath in path.iterdir():


print(filepath.name)

The only change you applied to this code is that you added .name to the
filepath variable. In fact, you can get the .name attribute of any
pathlib.Path object, whether it's a folder or a file:

import pathlib

pathlib.Path.cwd().name # python-course

In this snippet, you created a pathlib.Path object for your current working
directory, then accessed the .name attribute. This will be the name of the
folder you saved your script in.

Create A Specific Path Object

Now you got the chance to inspect your current working directory, but
unless you saved your Python file right on your Desktop, it won't be where all
the screenshots are. So how can you point Python to another location?
When you have a string that represents a path on your file system, such as
the one you got from running .cwd(), you can pass it to a pathlib.Path
object and start interacting with it.

Info: Python's pathlib handles both UNIX as well as Windows paths, which
is one of the reasons that it's a great choice if you're working with your file
system through Python.

This means that instead of executing .cwd(), you can also pass in a string
that points to a certain location on your computer:

import pathlib

pathlib.Path("/Users/martin/Desktop")

The code snippet above creates an object that points to my Desktop on a


UNIX system. If you passed in the equivalent path for your own Desktop, it'll
point you there instead.

Tasks

Assign the path to your own Desktop to a variable, then play around
with it.
Display only the name of the folder.
List all the files that are currently on your Desktop.
Check out the documentation for .suffix, .is_dir(), .parent, and
.stem. Try them out and investigate what they each do.

You can see that you're already getting closer to cleaning up your Desktop.
You can already see all the mess in there by running your Python script. So
your next step will be to filter out the screenshots and move them to a new
folder.
Recap

In this lesson, you used the pathlib module to:

list all files in a certain location using a for loop and .iterdir()
display only the filenames of files, instead of the whole path, with .name
create a new pathlib.Path object by passing it a specific file path

You can feel how the power of pathlib is unfolding beneath your fingers.
Move The Files
You've found your way to your Desktop and you peeked at all the files on
there. As of now, you're still only dreaming of a clean Desktop.

But you've already tackled a couple of the tasks you noted down in
pseudocode when you began to work on this challenge. Time to take
another look at them:

# Import pathlib
import pathlib

# Find the path to my Desktop


desktop = pathlib.Path('/Users/martin/Desktop')

# List all the files on there


for filepath in desktop.iterdir():
print(filepath.name)

# Filter for screenshots only


# Create a new folder
# Move the screenshots in there

Three tasks are done, and three more to go! Next, you'll filter all the files so
you can pick out only the screenshots. You can do this with another attribute
to a pathlib.Path object called .suffix.

Filter By File Extension

On my system, screenshots have the file extension .png. Python's pathlib


module is aware of the file extensions of the paths it's working with. In the
same way that you were able to get just the .name of a pathlib.Path object,
you can also just get its .suffix instead:
import pathlib

desktop = pathlib.Path('/Users/martin/Desktop')

for filepath in desktop.iterdir():


print(filepath.suffix)

This code prints out all the file extensions instead of the names of the files
on your Desktop. But you want to filter and only do something to the files
with a .png extension. Sounds like a job for a conditional statement:

import pathlib

desktop = pathlib.Path('/Users/martin/Desktop')

for filepath in desktop.iterdir():


if filepath.suffix == '.png': # Filter for screenshots only
print(filepath.name)

By adding the conditional statement, you're telling Python to only address


the files that have .png as their file extension. These are your screenshots.
Now you need a new place where to move them to.

Create A New Folder

The pathlib module comes with many convenient abstractions that make
interacting with your file system easier. Many of the methods resemble
commands you might remember from working with Bash.

For example, if you want to create a new directory in Bash, you use the mkdir
command. You can do the same with Python's pathlib:
import pathlib

new_path = pathlib.Path('/Users/martin/Desktop/screenshots')
new_path.mkdir()

Calling .mkdir() on a pathlib.Path object will try to create a new directory


at the path that it's pointing to. In this case, that's a folder called
screenshots on my Desktop. If the folder already exists, this operation will
fail with an aptly named FileExistsError.

You can circumvent this error by passing an argument called exist_ok with
the value True when calling .mkdir():

import pathlib

new_path = pathlib.Path('/Users/martin/Desktop/screenshots')
new_path.mkdir(exist_ok=True)

If you add exist_ok=True, the directory will get created if it doesn't already
exist. If it exists, then the code will pass and continue. You can add this to
your code:

# Import pathlib
import pathlib

# Find the path to my Desktop


desktop = pathlib.Path('/Users/martin/Desktop')
# Create a new folder
new_path = pathlib.Path('/Users/martin/Desktop/screenshots')
new_path.mkdir(exist_ok=True)

for filepath in desktop.iterdir():


# Filter for screenshots only
if filepath.suffix == '.png':
print(filepath.name)

# Move the screenshots in there

You've updated the order of your pseudocode a bit, by moving the creation
of the new folder above the for loop that iterates over the files on your
Desktop. You also removed the comment about listing all files, because it
wasn't relevant anymore.

Info: Changing and updating your pseudocode, as well as your actual code,
while developing your program is completely normal. You'll never think of
everything you need to do, or in what order, quite correctly. Pseudocode is
there to give you a scaffolding to get started, and you can change and
update it at any time as it best fits.

At this point, there's only one last piece of functionality missing. You need to
actually move the screenshots into the new folder.

Move Files

The final piece of the puzzle is to move the files from the Desktop into the
new screenshots directory. The method to do this is called .replace() and it
works like so:

oldpath.replace(newpath)

For this to work correctly, oldpath needs to point to a pathlib.Path object,


and newpath needs to be a valid path string or another pathlib.Path object.

Note: As the documentation tries to warn you, if the target points to an


existing file or directory, it will be unconditionally replaced. Keep that in mind
to avoid overwriting existing files on your computer!

In your Desktop-cleaning example, you'll want to move all screenshots that


are currently on your Desktop into the new and empty screenshots folder.
This means that you'll want to construct a new file path for each file that
points inside that new folder, and keeps the original filename:

# Import pathlib
import pathlib

# Find the path to my Desktop


desktop = pathlib.Path('/Users/martin/Desktop')
# Create a new folder
new_path = pathlib.Path('/Users/martin/Desktop/screenshots')
new_path.mkdir(exist_ok=True)

for filepath in desktop.iterdir():


# Filter for screenshots only
if filepath.suffix == '.png':
# Create a new path for each file
new_filepath = new_path.joinpath(filepath.name)
# Move the screenshot there
filepath.replace(new_filepath)

There are three things you've introduced in the final two lines of code:

# Create a new path for each file


new_filepath = new_path.joinpath(filepath.name)
# Move the screenshot there
filepath.replace(new_filepath)

Time to pick it apart, beginning with the first new line of code:
new_filepath is the variable name you're assigning the new file path to.
new_path is the path to the new folder called screenshots that you
created on your Desktop.
.joinpath() is a method that allows you to combine the paths of
multiple pathlib.Path objects. In this case, that'll be new_path and what
you'll pass as an argument in between the parentheses.
filepath.name is the filename of each screenshot.

In this line, you're creating a new file path that points to where you want the
screenshot to move. You're constructing it from the path of the new folder
you created and the filename of the existing file.

Info: There's quite a bit going on in just two lines of code. This is the power
of abstraction and why using modules can make building functionality quick,
and not require lots of code. Don't worry if you don't understand a lot of
what's going on behind the scenes, this is also partly what abstraction
means. You'll keep stripping off more and more layers as you progress in this
course.

In the second line of code, you're finally moving the screenshots to their new
location:

filepath is the name for the iterator in your for loop. As you confirmed
in the last lesson, this will be the absolute path of each file with the .png
suffix.
.replace() is the method you are calling on the pathlib.Path object
called filepath. It will replace the old path, filepath, with the new one
that you'll pass as an argument in between the parentheses.
new_filepath is the variable that you created in the previous line of
code. It points to the new path where you want to move the screenshot
to.

Because these operations are inside of your for loop and use the filepath
iterator variable, they'll get applied to each screenshot that is currently on
your Desktop.

After you save and run this script, you're Desktop will be released of its
screenshot burden:

Ah! Fresh air! You've just written a Python script that automated tasks on
your computer's file system. Nice work!

Recap

In this lesson, you used pathlib to:

Filter files for a specific file extension with .suffix


Create a new folder using .mkdir() on a new pathlib.Path object
Move files from one location to another using .replace()

Keep in mind that you might overwrite existing files with .replace() if
you're not careful, so make sure that you wield your new power responsibly.
PROJECT: Complete More
Automation Tasks
You just cleaned your Desktop in a fell swoop and got your first taste of
automating your digital tasks using Python. Well, you might think, it might
have been quicker to just move these screenshots by hand:

Automation by XKCD - https://xkcd.com/1319/

But that's of course not the point here ;)

The advantages of automation come with scale and repetition. Next time you
want to perform the same action, you only need to run your script. You build
the code once, and you can run it many times. Plus, it's fun!

More Automation Challenges

Writing Python scripts to automate some repetitive tasks you perform on


your computer is a great way to keep learning. There is a lot you can
automate with Python, and here you've only just scratched the surface.

Info: Take a moment to write down some ideas of what tasks you might want
to automate. Think about which digital tasks do you perform often, and
which of them do you find annoying. Do a web search on these tasks and
include the keyword Python. You'll likely find a library that would help you to
solve your task.

Once you dive deeper into the language and the many packages that exist
for it, you'll see that there's hardly any end to what you can automate. Of
course, the comic shown above has a point, and there's always a trade-off
between how much time you want to invest in building automation scripts.

For now, you should stay focused on using the pathlib module and keep
practicing with some more automation tasks.

Tasks

Write a script that renames all the files in a folder, giving them a default
name and an incrementing counter.
Write a script that walks through a nested folder structure and prints out
all the Python files that it can find.

Congratulations on making it this far in the course. You've completed the


first level and you graduated to Python novice with enough knowledge to be
dangerous :)

In the next part of the course, you'll dive deeper into the Python language
and learn about more data types, the power of functions, and how to use
your knowledge to interact with information on the Internet.
Introduction To Version Control
In this lesson, you'll learn the basics of version control with Git and GitHub.
But why do you even need version control?

You might remember writing a long heartfelt email or an important job


application, or even just filling out some input fields on a website. Right when
you're happy with how your text was coming along and you were nearly
finished... Suddenly your computer crashes, the internet connection drops,
or you notice that the page has become unresponsive. All your work is gone,
and there's nothing you can do about it anymore :/

You don't want the same thing to happen to the code you wrote. Using
version control can prevent it from happening.

Info: Through using version control you can back up your code and keep it
safe.

But version control does more than just save your code from getting lost.
Using version control gives you the freedom to explore and try out things.
You don't only back up against hardware and software failure, but also
against breaking changes that you, or a collaborator, might add to your code.
Every time you commit your code, your version control system saves a
current snapshot of your project.

Committing your code to version control, therefore, allows you to:

Time-Travel: Go back to earlier versions of your project


Explore: Go wild experimenting, then discard what you tried if it ended
up breaking everything
Read History: Go back in time to understand how a project was built
step-by-step

You could say that version control allows you to keep control of different
versions of a project :)

Using a version control system for code projects is common practice for
software developers. You'll need to be able to work with one if you are
planning to make programming your profession. However, even if you are
only doing this as a hobby, there are lots of advantages of keeping your code
under version control.

Info: Keep in mind that this course wants to introduce you to important
workflows and concepts in software development, not just the Python
programming language. Version control is one of these important topics.

Using version control is not necessary in order to write code, and you've
already written some quite elaborate scripts without putting them under
version control. However, version control is necessary to write code
professionally in order to collaborate productively with other programmers.

In the next lessons, you'll learn how to put your labs under version control
using Git and GitHub. Give it a try, but don't despair if you don't get it to work
right now. You can always skip these pages and come back to them at a later
time.

Additional Resources

CodingNomads: Version Control with Git and GitHub course


Git SCM Book: About Version Control
Wikipedia: Version Control
Commit A File To Version Control
In this lesson, you'll learn how to commit your lab files to version control. The
following information about Git and GitHub is stripped-down to the basics
that you need to get started. If you want to dive deeper into using Git and
GitHub for version control, check out the dedicated course on Version
Control with Git and GitHub.

Installing Git

If Git isn't yet installed on your system, then follow the instructions for your
operating system on the official Git documentation on installing Git.

Git Repositories

Git uses the idea of a repository, which you can think of simply as a top-
level folder. Anything inside a Git repository will be tracked under version
control.

Note: It's important that you only set up Git repositories in directories that
you actually want to track.

A common mistake when first getting started with version control is to


accidentally turn your entire computer into a Git repository. Instead, you only
want to track the directories that contain your coding projects. You'll also
want to have a separate Git repository for each one of your coding projects.

Initializing a New Git Repository

The first thing you'll want to do is to open your terminal. Use it to move into
the directory that contains all your course labs. If you've named the folder
labs and placed it as suggested at the beginning of the course, then you can
go there by typing:
cd ~/Documents/codingnomads/labs

This directory contains folders with your coding exercises, and it's the
project that you want to start tracking with Git as a repository. Once you are
inside of this folder, initialize a new empty Git repository with:

git init

You should see an output message similar to this:

Initialized empty Git repository in /Users/martin/Documents/codingnomads/labs.git

Congratulations! You've just set up a new Git repository. However, you


haven't yet put any of your files under version control.

The next thing you need to do is to add your project files to the Git repository
so that Git knows what to keep track of.

Adding a File To Your Git Repository

To add a file you use the git add <filename> command for each file or
directory that you wish to add. You can also add more than one file at a time.
You'll learn how to do that later. First, you'll learn to add a single file to Git for
tracking. The project folder you downloaded contains a file called README.md.
Add this file to Git by typing:

git add README.md


The README.md file is a file that contains information describing this project.
The process works the same for any other file inside of this folder. Focus on
what happened in Git.

But... how would you know what happened?

Git has a handy way of checking what's currently going on inside of its belly.
You will use this command very often when working with Git. Check the
status of your Git repository by asking Git What's up?:

git status

Git will dutifully reply with a couple of lines of output that will look similar to
this:

On branch master

No commits yet Changes to be committed: (use "git rm --cached <file>..." to unstage)


new file: README.md
...

Note: Your output will be much longer since Git also tells you about all the
files inside of the repository that you haven't yet added. For now, only focus
on the top of this message and ignore the rest. You'll learn more about the
rest shortly

You can see that README.md is highlighted in the color green. This means that
the file has been added to the Git repo, but it has not yet been committed.
Git uses a two-step process when putting your files under version control.
By adding files you decide which ones to bundle up together, and by
committing them you give that bundle a name and register it in Git's version
tracker.
Committing a File To Version Control

By completing the first step with git add you have added README.md to what
is known in Git as the staging area. It means that the file is ready to be
committed to the Git repository, which represents a separate step.

The staging area allows you to add any number of files to be included in a
single commit to the Git repository. Each commit you make to a Git
repository marks a snapshot in the history of your project. It's like writing an
entry to your project's very own history book.

Info: Git also allows you to time travel. You can not only check out any
commit in your project's history, you can also revert back to that point in time
in the history of your project. Pretty neat, huh? You can also see exactly who
committed which code, and what code was committed, and read the label on
each commit, the so-called commit message.

Go ahead and make your first commit. You will start by labeling the file
bundle you created with the required commit message. While this commit
only contains one file, keep in mind that this bundle can consist of multiple
files.

You can add the commit message directly to the git commit command by
adding it wrapped in quotes after the -m option. Your first commit message
will be:

Initial commit: Add CodingNomads online labs

And the full commit command, including the message, will look like below:

git commit -m "Initial commit: Add CodingNomads online labs"

Note: If this is your absolute first time committing to Git, you might be
presented with a question about your identity. To settle Git's concerns once
and for all, you can follow the instruction printed to your console, and fill out
the quick form for your name and email: git config --global user.email
"your@email.com" and git config --global user.name "Your Name"
Remember to use the same email address you used or will use, to sign up for
GitHub.

Your terminal should now present you with text output resembling the one
below:

[master (root-commit) f1ad783] Initial commit: Add CodingNomads online labs 1 file ch

This output tells you that the file has been committed to your local Git
repository. Congratulations, the README.md file is now under version control!

As mentioned, a commit in Git marks a moment in time of your project. Once


it has been recorded, you can always go back to this moment, or any other
commit, should you need to in the future.

Recap

To track your files using version control with Git, you need to:

1. Initialize a new Git folder with git init


2. Add the file to Git's staging area with git add <filename>
3. Commit the content of your staging area to version control with git
commit -m "your commit message"

In the next lesson, you'll learn how to add more than one file so that you can
get your whole lab folder under version control without needing to type out
every single file name.

Additional Resources
CodingNomads: Version Control with Git and GitHub course
Commit Multiple Files
In the previous lesson, you successfully created a new Git repository and
added and tracked a single file under version control. Great job! With
README.md safely under version control, ask Git again what's up:

git status

Oh right! There were all these other mysterious lines describing a lot of other
files. Maybe they even showed up in red:

Untracked files: (use "git add <file>..." to include in what will be committed)

01_python_fundamentals
02_basic_data_types
...

nothing added to commit but untracked files present (use "git add" to track)

Try to figure out what Git is telling you with this message:

Untracked Files: There are files that Git can see inside of this folder,
but they are not currently tracked under version control
01_python_fundamentals (etc.): Next, Git shows you a list of all the
untracked files. I've truncated the output in the example above, yours is
probably much longer
(use "git add" to track): Finally, Git tells you what you need to do in
order to add your untracked files to version control: Use git add <file>

Now that's pretty helpful, thank you Git for the hint!
You have already gone through this exact process with your README.md file.
To gain further practice with the basic Git process, your next task is to add
and commit everything else to version control. The basic Git process always
stays the same and you will use it a lot in your career as a software
developer.

Tasks

Add and commit all contents of this folder under version control.

To make that tedious task a little easier, Git provides you with a shortcut for
adding many files at the same time:

git add .

The . in UNIX systems always stands for "this current directory". Therefore,
as long as you're at the root of your Git repository, you can use this shortcut
to add everything that is inside the current folder to the staging area.

Note: You always want to be aware of what you are adding to a Git commit.
Therefore it is generally better to specifically name each file or folder that
you are adding to a commit. In this case, since you're just setting up the
repository, it is fine to add everything at once

Give it a go and brace yourself for the power of this command! Once you are
done adding the files, remember to:

Check the status


Commit the files with a meaningful commit message
Check the status again

If you get stuck read over this page again, starting from the beginning, and
follow along by adding the additional folders. The process is the same as the
one you went over when adding the README.md file.

Check Your Status

You are done with this exercise once you run git status and see a message
saying that your working tree is clean:

On branch master nothing to commit, working tree clean

This means that every change to the Git repository is safely recorded in its
very own history book.

Info: The output also mentions something that you haven't learned about
yet: On branch master. You can think of branches as a way to make
collaboration between different developers easier, but you don't have to
worry about it at this point.

Recap

In this lesson, you've learned how to add multiple files at once using the git
add . shortcut. You've also trained to use git status often to gather
information about what's the status of the files in your Git repository.

Now you are ready to move on to the next lesson, where you will save the
version history of your repository to GitHub, which makes it possible to
collaborate with other people on your code projects.

Additional Resources

CodingNomads: Version Control with Git and GitHub course


Introduction To GitHub
In this lesson, you'll learn how to connect your local Git folder to GitHub.

Info: The information about Git and GitHub is stripped-down to the basics
you need to get started. If you want to dive deeper into using Git and GitHub
for version control, check out the dedicated Version Control with Git and
GitHub course.

You just learned about Git, but what's the deal with GitHub? You can think of
GitHub as a cloud storage for your Git repositories. It allows you to keep
your code and its history safe from deletion should your computer fail, as
well as allows you to access it from any machine.

Most of all, however, GitHub allows software developers to remotely


collaborate on complex coding projects and give feedback to each other.

Getting started with GitHub

If you have not already created an account on GitHub, please create a free
GitHub account now.

Once you're logged into GitHub, click on the + icon in the top right corner of
the screen and select New Repository.

You will see a screen where you need to adapt a few settings. Look at these
settings one by one:

Name: Give the new repository a name. Call this project python-labs.
Description: You can leave the description blank for now.
Repository Type: Leave the repository type set to the default public.
Initialize...: Lastly, you can leave Initialize this repository with a
README unchecked.
Click on Create Repository. You will see a page that looks similar to the one
shown below:

This means that you successfully created a GitHub repository and are ready
to connect it with your local Git repository.

Connecting Your Local Git Repo to a GitHub Remote Repo

Next, you need to connect your local Git repo to your new GitHub repository.
Connecting your local repository to a remote repository is called "adding a
remote repository" to your local Git repository. Doing this allows you to push
your code to an online repository where you can share your work and
collaborate with others.

You'll need to take the following steps:


Orient yourself
Monitor remotes
Add your remote
Monitor remotes again

Follow the step-by-step instructions below to go over this whole process.

Orient Yourself: Make sure you're in the right directory. The right directory
is the one that contains the README.md file and all the individual labs folders.
If you followed along in the previous sections this will be the
~/Documents/codingnomads/labs directory. If you are not there yet, use your
terminal to move there:

cd ~/Documents/codingnomads/labs

Monitor Remotes: Check to see what remotes are already connected to


your local repo:

git remote -v

If you have downloaded the labs folder as previously described, there


shouldn't be any remotes showing up.

Info: If you have cloned the repository instead of downloading the ZIP file,
then the original CodingNomads GitHub repository will show up as a remote.
This is no problem. You can choose to keep the connection and add a
second remote pointing to your own GitHub, or replace the CodingNomads'
one with yours. Check out the Intro to Git & GitHub course if you need help.

Add Your Remote: Now it's time to add your new GitHub repo as a remote
to your local Git repository. The default name for Git remotes is origin. Add
your GitHub remote under that name:

git remote add origin https://github.com/<YOUR GITHUB USERNAME>/python-labs.git

Be sure to replace <YOUR GITHUB USERNAME> with your GitHub username as


shown in the image below under the section labeled, "...or push an existing
repository from the command line":

Monitor Remotes: Check a second time to see what remotes you have
connected to your local repo now:

git remote -v

At this point, you should see that you have one remote repository called
origin that points to your GitHub repository titled python-labs.

Note: The -v option stands for "verbose". Adding -v to the command will
print out the URL that the remote is connected to. Without the -v it will only
Pushing To GitHub
Now that you have connected a remote to your local Git repo, you're ready to
push your code to GitHub:

git push -u origin master

Note: Depending on your setup, this command may prompt you for your
GitHub username and password first. If you need help getting set up with
Git, consult the Version Control with Git and GitHub course.

Info: The -u option is an argument to the push command that sets the
remote you specify, in this case origin, and a branch, in this case master, as
the default upstream remote and branch. If you use the -u option, you won't
have to specify the remote and the branch anymore for subsequent pushes.
Following this setup, you will only need to run git push to send your updated
code to your GitHub remote.

If all went well you should see feedback from Git in your CLI that reads
similar to the output below:

Enumerating objects: 122, done.


Counting objects: 100% (122/122), done.
Delta compression using up to 4 threads
Compressing objects: 100% (119/119), done.
Writing objects: 100% (122/122), 2.11 MiB | 1.50 MiB/s, done.
Total 122 (delta 0), reused 0 (delta 0)
To https://github.com/martin-martin/python-labs.git
* [new branch] master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.

Congratulations, you have successfully pushed your local version-controlled


code to a remote GitHub repository. Double-check whether it worked as
expected by returning to the new repo you created in GitHub using your web
browser and refreshing the page. You should see the labs project folders and
the README.md file show up:

If you see your GitHub repository has filled up with the same files and folders
you committed earlier to your local Git repository, then your setup is
complete.

From now on, every time you make a commit to your local Git repo, you
should also push your code to GitHub using git push. Every time you push
code to GitHub, the site awards you with a green dot on your profile's
Contributions heatmap:
For some employers, GitHub is considered as an alternate portfolio, and the
contributions heatmap can be a way to show that you code on a regular
basis.

Tasks

Aim to have a green dot just about every day of every week moving forward
in order to train your skills and build on your GitHub portfolio

Use the code you push to your GitHub repo to share code examples or ask
and answer questions on the forum.

Recap

After you've connected a remote GitHub repo with your local Git repo using
git remote add origin <your_github_repo_url>, you can push the files
you put under local version control to GitHub with git push -u origin
master.

Your files and their version history are now online visible and you can
collaborate with others on your code projects.

If you want to dive deeper into using Git and GitHub for version control,
check out the additional course on Version Control with Git and GitHub that
goes into much more detail.
Project Documentation
You can think of a README file as a manual for your project. READMEs are
text files containing an introduction, summary, and all necessary pieces of
information anyone needs to know about the project, such as what the
project is all about or what steps a user needs to take to run it.

READMEs can be written in any text file format, and the all-caps naming is
also just a convention that isn't absolute. You may encounter README files
looking like this readme.txt, like so Readme.md, or even just README without
any file extension. The most common format on GitHub projects is to use a
Markdown file named README.md. The Markdown format allows you to add
simple formattings, such as headings, bolding, emphasis, lists, and links.

Why Have a Good README?

So you've built a great project and put it on GitHub. Since you wrote it, you
know exactly what the project is all about and what it contains. Your friend
wants to contribute to your project, but they live far away in a different
timezone than you. To avoid going back and forth to explain every bit of the
project, it would be great to have a file that contains a summary of the
project, as well as instructions on how to start working on the project. Such a
file would help your friend to get started.

Info: After reading your README.md file, a newcomer should have a good idea
on how to use your project

In short, having a good README.md makes your project more approachable for
other people, and is overall a great advertisement for you and your project. It
is a rich manual that makes your project stand out in the eyes of other
people. If your project has a quality README.md, it'll help others to understand
the fundamentals and the functionality of our project quicker and make them
aware of features that they might have otherwise failed to notice.
How to Write a Good README

A good README.md file describes all the necessary aspects of a project, such
as its version, which technologies are used, how to run it, what is the
purpose of the project, what future updates are planned, etc.

To accomplish this, your README.md file should always include at least the
following elements:

Introduction
Summary of the project,
What the project is all about
Technologies
Which technology and versions are used
Project setup
Hardware requirements
Software requirements
The minimum requirements to run the project
How to start the project on your own machine

To make your README.md file even better, consider also using additional
elements, such as:

Table of contents: A TOC gives a quick overview of the project's README.md


file using links to the headings. A TOC will look something like below. It
usually allows readers to click on the headings and be taken to the
corresponding content.

## Table of contents:

- Introduction
- Technologies
- Project setup
- Illustrations
In order to create functioning hyperlinks inside of your Markdown document,
you need to use a bit of HTML code and add an id element to the headings
you want to link to, for example:

## Table of contents:

- [Introduction](#intro)

<h3 id="intro">Introduction</h3>

While a clickable table of contents is preferred, also just adding one for
overview at the top of your README.md file is already very helpful.

Visual Aids: Adding some screenshots of your project in action, or even


GIFs that show the functionality, goes a long way. Depending on the project
type, illustrations or graphics related to the project could be more
appropriate. In general, adding visual aids will make your project's README.md
file more accessible and easier to read for most viewers.

Project Information: It can be helpful to list features, TODOs, etc., which


can also help to get a quick high-level overview of the current state of the
project.

Project Status: Clarifying the status of the project can be helpful, especially
if the project is still in development. Also, if there's a chance that a new
feature might be added soon, it's a good thing to have that information
noted in your README.md file.

Sources/Inspiration/References: What inspired you to do the project,


which other sites and projects helped you build it? Was there any tutorial you
watched, or blog post you read that helped you build the project's
functionality? Adding your resources to your README.md file is important.
Share the love!

Contribution Instructions: Do you want other people to contribute to your


project? It's important to clarify whether or not you want that, and maybe
make it easier for newcomers to see where they could start out. Often,
especially in larger projects, this information is separated into its own file,
aptly named CONTRIBUTING.md, and should contain detailed instructions on
how to get started contributing. It is extremely helpful both for yourself as
well as for others when you clarify what contributions you welcome, and how
they should be presented to you.

Other Information: There might be some specific information that is


relevant just for your project and your individual information. Feel free to add
whatever you think is informative and relevant.

There are multiple great resources on the web that you can use to improve
your skills in writing README.md files. For example, check out the Make a
Readme site to learn more about how, when, and where to use a README.md
file, as well as more detailed guidelines on how to author quality project
documentation.
Push Your Game Code To Version
Control
Nice work! You went over a short introduction to Git and GitHub and learned
about writing documentation for your projects. You also pushed your labs to
a remote repository on your own GitHub account! Now it's time to create
another empty repository on GitHub.

Push the code for your CLI role-playing game to that repository. You'll
continue working on this game as you progress through the following course
modules. With a dedicated GitHub repository, you'll be able to keep
improving and updating your game code, as well as sharing it with the world.

Add a README.md to your project folder and use it to create a description of


your game project. GitHub will render the Markdown on their web interface.
This means that you can write a good-looking description of your project in
Markdown, and you can use your GitHub repo as a portfolio page:
When you're done, share your GitHub repo with your CLI game code on the
forum thread on Command-line Games.

You might also like