Hello everyone, in this article, we will really begin programming. But, if you have really no knowledge about basic programming concepts like algorithms, variables or functions, or if you have not Python installed, you can check my last article Python Basics 1/7 — Introduction where I explain everythin you need to know before getting started. So now, we can focus on Python.
First, you must know the notion of indentation. In Python, blocks of code do not have statements or symbols that explicitly define the beginning or end of a block. Instead, indentation is used. This consists in using spaces to separate blocks of instructions. For example:
Here is a if instruction that we will see in detail later. Notice that at the end of this if statement, we put :, we return to the line and we use a tab (character replacing several spaces). This is the classic syntax of a code block in Python. If you do otherwise, your program will not work.
if is_red: # Will not work, missing indentation
Also, if tabs are used unnecessarily, for example when there are no code blocks to separate, this will not work either.
print("Hello Word !")
print("Goodbye !") # Will not work, wrong indentation
These are pieces of code that are ignored by the computer, that are not executed.
But what is the use of writing code that the computer ignores?
In fact, comments allow you to explain your code, or to add remarks or information that anyone reading your code can see and use, including you. For example, if you have made a complicated function, it can be useful to comment out that function to explain how it works, so that when you come back to see your code, you don’t waste time trying to figure out what you had written.
Here is how to write a comment in Python :
# This is a one-line comment"""
This is a comment too,
but on several lines
You can also use apostrophes,
and not quotation marks
Here are two ways to write a comment, the first one allows you to write a comment on one line, for that you just have to start the line with a hash (#).
And the second one allows you to write a comment on several lines, for that you start the comment with three quotation marks (“””) or three apostrophes (‘’’), and you end with three quotation marks if you started with quotation marks, or three apostrophes if you started with apostrophes.
Note that comments can be inserted anywhere in your code, even at the end of a line or in a block of instructions.
In Python, the initialization of a variable and its declaration are done at the same time. Moreover, you don’t need to specify the type of a variable when declaring it because Python is a dynamically typed language, and detects the type itself.
x = 10 # Assigns the value 10 to x
x = 15 + 8 # Assigns the value 23 to x
x = None # Assigns no value to x
As you can see, we can perform operations during the initialization. We can also declare a variable without assigning a value to it, for this we use the keyword None during initialization.
But why not assign a value to a variable?
Maybe you need this variable to exist right away, but you don’t have a value to assign to it. So instead of assigning it a random value, which wouldn’t really make sense, you just initialize a variable without giving it a value.
Types of variables
The type of a variable is in fact its “nature”, what it represents. For example, a variable can be an integer, a decimal number, a complex, a character string, a boolean… To know the type of a variable, we use the type statement. For example:
x = 3 # An integer
y = 6.94 # A decimal number
name = “John” # A string of characters
is_red = True # A boolean
a = None # “Nothingtype(x) # <class ‘int’>
type(y) # <class ‘float’>
type(name) # <class ‘str’>
type(is_red) # <class ‘bool’>
type(a) # <class ‘NoneType’>
What?! Even “a” which has no value has a type ?
Indeed. By the way, it’s imprecise and incorrect to talk about type, whether it’s for an int, a float, a str, etc… We talk about classes. In fact, in Python, everything that exists is a class, or an instance (an instance is an occurrence of a class). Here, a is an instance of the class NoneType, used for variables without values, just as x is an instance of the class int, used for integers.
Note also the syntax for each base type. Thus, a string starts and ends with quotes (or apostrophes, as you wish), a boolean is initialized with `True` or `False`, etc…
But what is a boolean?
A boolean is a variable that stores a state, either “true” or “false” (in this case True or False). It is used for logical conditions, more on that later.
In Python, a variable name can be composed of lowercase letters, uppercase letters, numbers, or the underscore character (_). You can’t use spaces in a variable name, so for multi-word names, use the underscore character to separate the words instead. Ex: number_of_players. Also be aware that some words are reserved by Python, so avoid naming your variables that way, e.g. the words if, type, print, etc… Also, Python is case sensitive, i.e. it is case sensitive, so firstname, Firstname and fIrStNaMe are 3 different variables.
But there are also conventions, implicit rules, to respect as much as possible for naming variables, in order to be understood by other programmers and to have a clear code:
- A variable name starts with a lower case letter, and is written entirely in lower case.
- When there are several words in our variable name, we separate these words with the underscore character.
- We use explicit names for our variables, e.g., to represent an age, our variable will not be named a but age.
- Ideally we use English names, English being the main language in programming.
Operations are what we can do with our variables, using operators. For numerical types, we have the basic operators: +, -, *…
They are simply used:
>>> 3 + 4
>>> 4 * 6
>>> 5 / 2
>>> 5 // 2 # Integer division operator (returns the quotient of the euclidean division)
>>> 5 % 2 # Modulo operator (returns the remainder of the whole division)
>>> 5**3 # Power operator
Notice the syntax I use in the code block: the >>> correspond to those in your interpreter, so I write the code as if I were writing it in the interpreter. If you don’t know what the interpreter is, I invite you to read the article mentionned at the beginning.
You can also use operators with other types. Be careful though, it has to make sense. Let’s try for example with strings.
>>> “Hello” + “World”
>>> “Hello” * 3
>>> “Hello” / “World” # No sense, you don’t split two strings, so it generates an error
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: unsupported operand type(s) for /: ‘str’ and ‘str’
There are also operators that shorten basic operations, here they are:
>>> a = 10
>>> a += 2 # a = a + 2 : 12
>>> a -= 2 # a = a — 2 : 10
>>> a *= 3 # a = a * 3 : 30
>>> a /= 3 # a = a / 3 : 10.0
Let’s say I want to get the integer part of a decimal number. This is easily done with type conversion. It is in fact a matter of changing the type of a variable. Be careful, once again, this conversion must make sense! You can’t change a string of characters like “Hello” into an integer… On the other hand, you can change a string like “10 ” to an integer. Similarly, you can change an integer into a string. Let’s see how to do it with some examples:
>>> int(3.4) # Convert a float to an int
>>> int(“10”) # Converting a str to an int
>>> str(10) # Convert int to str
>>> str(True) # Converting a bool to str
The syntax is very simple, we use the name of the type in which we want to convert our value, and we pass our value as an argument.
The last word
That’s all for this article. Thank you all for reading, I hope you enjoyed and learned a little bit more about Python basics. In the next article, we will cover conditions and loops.
If you have questions, don’t hesitate to leave a comment. See you soon for the following of your Python learning process !