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!
Almost always, the first thing a learner of a programming language is taught is how to 'print' stuff in the language. That is, it's taught how to generate output using the programming language.
Printing in Python is superbly easy as compared to languages like Java that require a big bolierplate to be first set up in order to print the shortest of messages. In Python, just call the
print() function with whatever you want to print.
Below we make one of the most conventional programming outputs i.e. 'Hello World!' :
Time to understand a couple of things...
print() is a function amongst many functions in Python.
To call a function, we use a pair of parentheses after the name of the function. Here the function is called
() following the word i.e
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.
print() function is a perfect example. It requires additional data that it would be printing in the shell. In the code shown above, the
print() function is called with a single argument
'Hello World!' that is the value to be output.
Let's print something else:
print('Hello World!') print('This is my first Python code!') print('Python is easy.')
This is my first Python code!
Python is easy.
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.
+ plus symbol is used to add together two numbers. Consider the following shell snippet:
2 + 2, which one looks more calm and readable?
- minus symbol is used to find the difference between two numbers. It subtracts the second number from the first number and returns the result:
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:
0.1 + 0.2should 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!):
Division is done using the
/ forward slash symbol:
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
5 percent symbol, also referred to as the modulus operator.
5 % 4 returns
1, because when
5 is divided by
4, the remainder left is
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.
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.
Suppose we want to create a variable
x with the value
30. To do so in Python, we'd do the following:
x = 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:
We're using our variable in different operations.
A variable can store anything. Recall the string we sent to
print() in the section above. 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!" print(msg)
print(msg) won't print
"msg" in the shell, but rather the value of the variable
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.
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 the input from a user, call the
input() function. You can call it with an optional message argument to be printed, explaining what input is desired.
Consider the code below:
input("What is your name? ")
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
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)
First Python creates a variable
name and then executes the
input function. Suppose that
"Ben" is entered in the shell. The whole
input() expression would be replaced by the string
"Ben" which would ultimately be assigned to
Finally, when we call
print(name) the value of
name is output in the shell which is
At this stage, even such a simple piece of code would look like 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 would 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 have seen strings a couple of times, in the
print() function and in the
Let's do a bit more work with strings.
A string in Python can be denoted in 3 ways:
- Using a pair of
- Using a pair of
- Using a pair of three single quotes -
'''or three double quotes -
The last choice represents a multiline string as we shall see in the Python Strings unit.
The following are all valid Python strings.
s = 'Hello World!' s = "Hello World!" s = '''Hello World!''' s = """Hello World!"""
One very important thing to note is that a string denoted using single quotes can't have single quotes in itself. The same goes for double quotes.
Anything that follows from this point onwards is considered as Python code, NOT as a string. Since what follows is usually invalid Python code, this ultimately throws an error.
Likewise, using a character inside a string that makes up the string is invalid in Python, and in most programming languages.
Two strings can be joined together into one single string using the
+ symbol. When used on numbers,
+ adds the numbers together and when used on strings, it joins the strings together.
In programming terminology, the joining of two strings is referred to as concatenation.
In the code below, we concatenate the two strings
"World!" together to obtain the complete string
"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 message
"What's your name" and then says hello to the user along with printing the provided name like
For example, if the user entered
"Ryan", the program should output
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 message.
Once this statement completes it means that the user has entered his/her name.
Finally, we concatenate the strings
"!" to form the desired message.