Python Basics

Chapter 3 31 mins

Learning outcomes:

  1. Printing text using print()
  2. Doing math with numbers
  3. Working with variables
  4. Receiving user input
  5. Working with strings


In the last chapter, we learnt how to set up Python on our computer, and run scripts written in it in given IDEs — IDLE and PyCharm.

In this chapter, we'll explore the general syntax of Python and some of the most used aspects of it such as printing stuff, receiving user input, working with variables and so on. The aim is to get a hands-on experience of Python, and in this way also get experience of working with our respective IDE.

Let's begin the show!

Printing stuff

Almost always, the first thing a learner of a programming language is taught is how to 'print' stuff in the language. That is, how to generate output using the programming language.

Printing in Python is superbly easy as compared to languages like Java that require a big boilerplate to be first set up in order to print the shortest of messages.

In Python, we just call the print() function with whatever we want to output.

Now there might be many questions in your mind right now such as 'why are there () after print', or 'what is a function', or 'what is meant by calling a function'. For now, let's first see a couple of examples of using print() and then move over to explain it thoroughly.

Below we make one of the most conventional programming outputs i.e. 'Hello World!' in Python:

print('Hello World!')
Hello World!

Time to understand a couple of things...

A detailed explanation

print() is a function in Python.

A function in Python is a group of code that can be executed whenever the function is called — or in programming terminology, whenever it's invoked.

'Calling' a function means that we explicitly tell the interpreter to execute its respective code.

To call a function, we use a pair of parentheses (()) after the name of the function. Here the function's name is print, so likewise to call it, we write print().

Functions can be provided with additional data to do their work. This additional data, formally known as arguments, is supplied inside the pair of parentheses.

The print() function is a perfect example.

When called without anything — or better to say, without any argument — inside the parentheses, it outputs a blank line in the shell. However, when we provide it with an argument, it would output that in the shell, instead of a blank line.

In the code shown above, the print() function is called with the argument — 'Hello World!'.

Now what is 'Hello World!'?

In the world of programming, values that represent text are called strings. Usually, strings are represented using a pair of quotes (''). In Python, this convention is followed.

The value 'Hello World!' in the code above is a string in Python. The quotes (') surrounding the text are what make it a string — without these quotes, the text value would be Python code.

Strings are used wherever we need to work with text. In the case of print(), if we want to output a piece of text onto the shell, we'd provide it to the function as an argument, in the form of a string.

This completes the explanation of your first Python code! Did you understand everything?

Frankly speaking, in this beginning stage of learning Python, it's not important for everything to make perfect sense. What's important is that you keep track of all the new concepts learnt, try your level best to understand their outskirts.

If you don't understand any concept fully, don't worry. As you progress through this course, everything would come naturally to you.

Anyways, let's print something else:

print('Hello World!')
print('This is my first Python code!')
print('Python is easy.')
Hello World!
This is my first Python code!
Python is easy.

Here, we call print() three times to output three different lines of text.

By default, print() puts a \n character at its end. This has the consequence of the next print() statement outputting the given text on a new line.

We could change this default behavior whereby a call to print() prints the text on a new line by using the keyword argument end. We'll learn more about keyword arguments in the chapter Python Function Arguments.

Note that the spacing of the print() statements in the code won't affect the spacing in the output.

For example, consider the code below:

print('Hello World!')

print('This is my first Python code!')

print('Python is easy.')
Hello World!
This is my first Python code!
Python is easy.

This time, there is a blank line between the first and second print() statements and two blank lines between the second and third print() statements. Regardless, these don't show up in the final output.


This is because, very obviously, the Python code is not part of the output — it gets parsed and executed; that's it. The print() statement, which is part of the code, is what governs the output. Whatever it provided to it is what's shown in the output. After how many lines does print() come, that doesn't matter!

Moving on, as we've been seeing right now, passing one argument to print() outputs that argument onto the shell. But we can give the function more than one argument.

But how?

The print() function can be passed multiple arguments, separated by commas (,). When multiple argument are given, they are output with a space between them.

Consider the following code:

print('Hello', 'World', '!')
print('Language:', 'Python')
Hello World !
Language: Python

In the first print() statement, we provide three args to the function. All of these get output in the shell with a space between them.

Similarly, in the second print() call, we provide two args to the function and they too get output with a space between them.

As we'll see later on, this can be extremely handy when we want to print stuff other than plain text, such as numbers, Booleans, lists, etc.

Doing math

Let's now do some math. Recall addition, subtraction, multiplication and division from school days? What about basic algebra?

Below we'll perform these simple operations on given numbers using Python.

To represent any number, just type the number as is. For example, to denote the number 10 we would write exactly 10 in the shell.

The + plus symbol is used to add together two numbers. Consider the following shell snippet:

2 + 2
3 + 10
9999 + 1000
The space between the numbers and the symbol is optional. It is given to make the overall expression more readable. You can see this yourself: 2+2 vs 2 + 2, which one looks more calm and readable?

Similarly, the - minus symbol is used to find the difference between two numbers. It subtracts the second number from the first number and returns the result:

2 - 2
3 - 10
9999 - 1000

Numbers with a decimal point, known as floating-point numbers or simply floats, are also available in Python (and almost all other programming languages):

In the snippet below we work with a couple of floats and integers:

2.5 + 2.9
3 - 10.1
0.25 + 0.1
0.1 + 0.2
0.1 + 0.2 should give 0.3, but it doesn't. Rather it gives 0.30000000000000004. This is a consequence of the way floating-point numbers are internally stored in a computer.

Moving on, to multiply two numbers together we use the * asterisk symbol (NOT the x character, which is usually used in mathematics!):

3 * 5
10 * 10
12 * 101

Division is done using the / forward slash symbol:

3 / 5
10 / 10
12 / 3

Akin to most programming languages, Python provides a way to calculate the remainder when a given integer is divided by another integer.

That is using the % percent symbol, also referred to as the modulus operator.

We'll learn more about the modulus operator in the Python Operations unit.
5 % 4
10 % 10
10 % 4

5 % 4 returns 1, because when 5 is divided by 4, the remainder left is 1.

What will the following snippet output?

print(5 + 10)
print(2 * 4 + 2)
print(150 % 2)
print(10 / 2.5)
You might have expected the last output here to be 4 instead of 4.0, since 2.5 divides 10. However, the thing is that 2.5 is a floating-point number with a decimal point in it, and whenever an arithmetic operation in Python involves a floating-point number, the result is always a floating-point number as well.

We'll learn more details to floating-point numbers in detail in Python Numbers Basics.

Recall from mathematics that when we have an expression with multiple operators in it, there is a set of rules as to which do we perform first. Would we perform division first, or addition first?

This set of rules exists in Python as well. We call this operator precedence.

Shown below are the operators we saw above, arranged by their level of precedence, from highest precedence (computed first) to lowest precedence (computed last):

Operator symbolOperator name
*, /, %Multiplication, division, modulus
-, +Subtraction, addition

What this means is that division/multiplication/modulus operations are performed before any subtraction/addition operations.

Consider the following code:

10 * 5 - 5
10 / 5 + 5
2 + 2 * 3 + 2

One way to override this precedence, which is also commonly employed in mathematics, is to use parentheses i.e (), to group expressions that are desired to be computed first.

Below we have the shell script as before, but this time with our choice of order of computation:

10 * (5 - 5)
10 / (5 + 5)
(2 + 2) * (3 + 2)


If you've ever done algebra, you would be familiar with the term variables. They are simply placeholders for given values, and can vary (as the name 'variable' implies).

In programming as well, we have these things to perform exactly the same function — hold values.

A variable is a container for holding data. It can change during the course of a program which is essentially the reason it's called a variable.

In Python, we create a variable simply by typing in its name that we have in our mind followed by an equals = sign followed by the value we wish to put in the variable.

A lot of steps? Let's create one variable...

Suppose we want to create a variable x with the value 30. To do so in Python, we'd do the following:

x = 30

First comes the name x, followed by an equals sign (=), followed by the value 30.

This short script creates a variable named x and assigns to it the value 30. Now like any other value, we can use this variable in expressions, operations and so on.

Consider the code below:

x + 10
3 - x
x + x

A variable can store anything.

Recall the piece of text we sent to print() in the section above. In programming, a piece of text, with quotes surrounding it, is known as a string. Like numbers, a string is a type of data in Python and can therefore also be put inside a variable.

Below we create a variable msg, put the string 'Hello World!' in it and finally print this variable:

msg = 'Hello World!'

Note that print(msg) won't print 'msg' in the shell, but rather the value of the variable msg.

Hello World!

Working with a variable is exactly the same as working with the value itself. It's that simple, but at the same time, a principle idea.

We'll discover a lot on variables in the coming chapters. For now, you shall be comfortable with the idea of variables and how are they created.

Create a variable x with the value 10 and a variable y with the value 30 and represent their sum as follows in the shell:

10 + 30 = 40

You must use the print() function and the variables x and y only to accomplish this task. You must not write the text '10 + 30 = 40' directly.

Pass multiple arguments to print(), so that they are printed on the same line with a space between them.
x = 10
y = 30
print(x, '+', y, '=', x + y)
10 + 30 = 40

Getting input

Getting input is a crucial part of today's modern computing. It's a means of getting data from the user of a machine and then processing that data for a corresponding consequence.

Most programming languages have some sort of method to collect a user's input. Python is no way behind.

To get input from the user, we can use the input() function.

Let's see how to work with it.


As soon as input() is called, focus moves to the shell and a cursor is displayed asking you to type in something. Let's go forward and type the word Hello:


After typing Hello, when we press the Enter key, the input() function completes, and the value input is displayed as an output:


The whole input() expression gets replaced by whatever value is input by the user — in this case 'Hello'.

You can call it with an optional argument, which is output to the user explaining what input is desired.

Below we ask the user for his/her name:

input("What is your name? ")
What is your name? Alex

The moment the input() function is called, execution stops until the user inputs some data and then presses Enter. The execution of the input() function will complete and return with the value input by the user.

When a function returns a value, you can think of its calling expression being replaced by the return value.

For example, as we've stated, input() returns the value input by the user, so if let's say we enter "Ben", then the call to input() would be replaced by the value "Ben"

This means that the function could be called as part of a variable's assignment expression, as follows:

name = input("Enter your name: ")
print('Hello', name)
Enter your name: Alex
Hello Alex

First Python creates a variable name and then executes the input() function. Next 'Alex' is entered in the shell. The whole expression input("Enter your name: ") gets replaced by the string 'Alex' which ultimately gets assigned to name.

Finally, print('Hello', name) is executed, which outputs 'Hello Alex'.

At this stage, even such a simple piece of code would look like some complicated business, but that's perfectly natural.

It takes time to understand things '' as soon as you do understand these basic building blocks of Python, such scripts might end up in your recycle bin since you would consider them too simple to be even a simple piece of code!

Working with strings

In the section above, we've seen strings a couple of times; specifically in the print() function and in the input() function.

Let's learn more about strings...

A string is a sequence of textual characters.

A string is how we represent a literal piece of text in a piece of code.

There are a handful of ways to denote a string in Python. For now, we'll cover the two most simple and most common ways:

  1. Using a pair of single quotes ('')
  2. Using a pair of double quotes ("")
The rest two ways to denote a string — using a pair of triple-single (''' ''') and triple-double (""" """) quotes — will be explored in the Python Strings — Basics chapter.

In the code below, we create two strings using both these notations and save them in the variables a and b, respectively, followed by printing them:

a = 'Hello World!'
b = "This is Python."

Hello World! This is Python.

As can be seen here, the quotes used in either of the strings are just a means of denoting a given piece of text — they themselves aren't included in the string and, hence, not even in the output of the string.


Why we need to use quotes?

You might have one question in your mind right now that why do we need to use a pair of '' or "" to denote a string? Why can't we just right a string as it is?

Well, here's why...

When a language's engine is parsing a given piece of code, it has to be able to distinguish between the actual code and a literal piece of text used in the code i.e. a string.

The pair of quotes is one standard way in which the parser could make this distinction. That is, when it encounters a quote (' or "), it knows that what follows is a string uptil the the next similar quote.

Technically, a language could go with any method for denoting a string as long as the method allows one to clearly distinguish code from a literal string.

For instance, in JavaScript, we could denote a string using a pair of backticks (``) as well in addition to the standard quotes. In PHP, we could denote a string using special identifiers marking the start and end of the string — usually referred to as a heredoc string.

Moving on, one very important thing to keep in mind is that a string denoted using single quotes can NOT have single quotes in itself. The same goes for double quotes.

When a character that's used to denote a string appears, as it is, inside the string, the Python engine misunderstands this character as the end of the string.

Likewise, anything that follows from this point onwards is considered as Python code, NOT as the string's data. Since what follows is usually invalid Python code, this ultimately leads to an error.

This is demonstrated below:

s = 'Let's write some code!'

Here, the string we meant to write was "Let's write some code!", but that is not what the engine sees.

What the engine sees is just the string 'Let'. This is because the string starts at the first ' character and then ends at the next one. The next ' turns out to occur in the string itself, hence it gets terminated before it was meant to.

What follows after this point is Python code (in the case above, it's s write some code!'), and because it's clearly invalid code, an error is thrown:

File <stdin>, line 1 s = 'Let's write some code!' ^ SyntaxError: invalid syntax

If we carefully look at the error message here, it says that the code has an invalid syntax. Most importantly, it even traces the exact point where the syntax is illegal using the ^ character pointing upwards at the illegal code segment.

So to boil it down, using the same character as the one used to denote a string is invalid in Python, and in almost all programming languages.

One simple way to mitigate such a problem is to use the other type of quote to denote the string.

For instance, going with the piece of text "Let's write some code", we could denote a string holding this text as follows:

s = "Let's write some code"
Let's write some code

The text contains a single quote ('), therefore we use a pair of double quotes ("") to denote the string.

If it was the other way round, i.e. the text contained a double quote (") in it, we'd use a pair of single quotes ('') to denote the string, as shown below:

s = 'He said, "I love you!"'
He said, "I love you!"

Simple, isn't this?

From this point onwards, whenever denoting a string, we'll use single quotes ('').

This is because they are more readable than double quotes ("") and a bit easier to type i.e. we don't have to hold on to the Shift key and then enter ' to type a ", but rather just press ' to type '.

Moving on, two strings can be joined together into one single string using the + symbol.

As we saw above, when used on numbers, + adds the numbers together. However, when used on strings, it joins the strings together.

In programming terminology, the joining of two strings is referred to as concatenation.

Concatenation is the process of joining together two strings to obtain a single string.

In the code below, we concatenate the two strings 'Hello' and ' World!' together to obtain the complete string 'Hello World'.

'Hello' + ' World!'
"Hello World!"

Keep in mind that concatenation doesn't introduce spaces on its own between the joined strings — we have to do this ourselves. This can be seen as follows:

'Hello' + 'World!'

We concatenate 'Hello' with 'World!' (without a space at its beginning) and hence get 'HelloWorld' as the resulting string.

To include a space between both the words here, we can put a space at the end of the first string or at the start of the second string, as shown below:

'Hello ' + 'World!'
"Hello World!"
'Hello' + ' World!'
"Hello World!"

Let's apply some of the concepts that we've learnt so far in creating an elementary, yet interesting program.

Write a program that asks the user for his/her name using the prompt message "What's your name?" and then greets the user with 'Hello <name>.', where <name> is the entered name.

Here's an example:

What's your name? Ryan Hello Ryan.
name = input("What's your name?")
print('Hello ' + name + '!')

First, we create a variable name that'll hold the return value of input(), since we need to reuse the name later on. The we call the input() function with the respective prompt message.

The prompt message includes a single quote (') in it, hence we denote it using a pair of double quotes ("").

Finally, we concatenate the strings 'Hello ', name and '!' to form the desired output message and then output it.

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage