Fundamentals of programming
In this article, we will take a deep dive into the fundamentals of programming using Python.
1 Primitive Data Types
Let’s start with the 4 primittive data types in Python. We will discuss other non-primitive data types later.
Type | Description | Examples |
---|---|---|
str | String | “cat”, “7” |
int | Integer | -23, 112 |
float | Floating point number | 2.0, -2.4 |
bool | Boolean value | True, False |
2 Variables
In Python, a variable is created when a value is assigned to it.
|
|
Python is a weakly typed language, which means that it is less tightly coupled to a specific type. Because of this, variables do not need to be declared with a type. In fact, we can even change its type by casting a different data type.
|
|
Rules for naming variables in Python:
- Must start with an English letter or underscore(
_
), not numbers - Can only contain alpha-numeric characters and underscores
- No space in between the characters. Instead, we can use underscores or camel case. (eg.
a_long_variable
,aLongVariable
) - Variable names are case sensitive (eg.
age
,Age
,AGE
are all different variables) - Cannot be a keyword
Keywords are reserved words in Python. We cannot use a keyword as a variable name, function name or any other identifier.
- Examples:
False
,import
,for
,while
,return
Naming conventions
-
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
-
Variable and constanrs names follow the same convention as function names.
-
camelCase is used only to conform to pre-existing conventions
-
StudlyCaps is used when naming classes
3 Operators
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations.
Operator | Description | Example |
---|---|---|
+ | Addition | x + 2 |
- | Subtraction | y - z |
* | Multiplication | x * y |
/ | Division | x / y |
% | Modulo (returns the remainder in a division) | x % 3 |
** | Exponent | x ** y |
Assignment Operators
Assignment operators are used to assign values to variables.
Operator | Example | Equivalent to |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 5 | x = x + 5 |
-= | x -= 5 | x = x - 5 |
*= | x *= 5 | x = x * 5 |
/= | x /= 5 | x = x / 5 |
Comparison Operators
Comparison operators are used to compare values.
Operator | Description | Example |
---|---|---|
> | Greater than | x > y |
< | Less than | x < y |
<= | Less than or equal to | x <= y |
>= | More than or equal to | x >= y |
== | Equal to | x == y |
!= | Not equal to | x != y |
==
is used for comparison while=
is used for assignment.
Logical Operators
Logical operators are used to perform logical operations.
Operator | Description | Example |
---|---|---|
and | True if both operands are true | x AND y |
or | True if either operand is true | x OR y |
not | True if operand is false | NOT x |
4 Input/Output
Getting user input:
|
|
Combining variables and user input and outputting it:
|
|
5 Non-primitive Data Types
Non-Primitive data types are more complex data types. They don’t just store a value, but rather a collection of values in various formats.
5.1 Lists
A list is an ordered sequence of items. The items in a list can have different data types.
To declare a list, use []
:
|
|
We can also extract an item or a range of items of a list by stating the index of the items we want within []
. [x:y]
means range from x to y. In Python, index starts from 0.
|
|
Lists are mutable, which means that the value of elements of a list can be changed.
|
|
5.2 Tuples
A tuple is an ordered sequence of items just like lists. The only difference is that tuples are immutable. Once created, they cannot be modified.
To declare a list, use ()
:
|
|
5.3 Sets
A set is an unordered collection of unique items.
To declare a set, use {}
:
|
|
Since sets are unordered, indexing has no meaning.
|
|
5.4 Dictionaries
A dictionary is a unordered collection of key-value pairs. It is generally used when dealing with lots of data.
To declare a dictionary, use {key:value}
:
|
|
- We use key to retrieve the respective value. But not the other way around.
type()
is used to check the type of a variable or value.- Indexing dictionaries is also redundant as they are unordered.
6 Flow control
Flow control refers to the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated.
6.1 if…else Statements
if...elif...else
statements are used in Python for decision making.
if statement
|
|
if…else statement
|
|
if…elif…else statement
|
|
6.2 For loops
A for loop is used to iterate over a sequence of objects. Let’s take a look at this program that finds the sum of all numbers in a list:
|
|
6.3 While loops
A while loop is used to iterate over a block of code as long as the condition is true.
|
|
6.4 break and continue
The break
statement terminates the loop containing it when the test expression is satisfied.
|
|
The continue
statement is used to skip the rest of the code inside a loop for the current iteration only.
|
|
7 Functions
A function is a group of organised code that performs a single task.
Advantages of using functions:
- Helps break our program into smaller parts, making it easier to manage.
- Makes the code reusable and avoids repetition.
7.1 User-defined functions
User-defined functions are functions defined by the user. The syntax of a function is as shown:
|
|
def
is the keyword for defining a function- Parameters are the values we pass to a function.
- A function can have zero, one or more parameters.
|
|
Calling a function
To call a function, simply type the function name with appropriate arguments.
|
|
Function parameters are the names listed in the function’s definition. Function arguments are the real values passed to the function.
Functions with no parameters
|
|
7.2 Built-in functions
Built-in functions are functions that are built into Python. For example, the len()
function returns the length of an object and the range()
function returns a sequence of numbers.
|
|
To learn about more built-in functions, click here.
7.3 Scope
The scope of a variable is the region where it is accessible.
Local scope
- A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
Global scope
-
A variable created in the main body of the Python code is a global variable and belongs to the global scope.
-
If you need to create a global variable, but are stuck in the local scope, you can use the
global
keyword.
|
|
- In the example above, we can see that the value of
x
is 20 initially. Even thoughmy_func()
changed the value ofx
to 10, it did not affect the value outside the function.- This is because the variable
x
inside the function is local to the function while thex
outside of the function have a global scope.- Although both variables have the same name, they have different scopes. To avoid confusion, it is good practice to use different variable names.
8 File Handling
In Python, a file operation takes place in the following order: open a file → read or write → close the file.
8.1 Opening files
To open files, use Python’s in-built function open()
|
|
Mode | Description |
---|---|
r | Opens a file for reading. |
w | Opens a file for writing. Creates a new file if it does not exist and overrides the file if it already exists. |
a | Opens an existing file and appends to the end of the file. |
t | Opens in text mode(default). |
+ | Opens a file for reading and writing(updating). |
8.2 Writing to files
To write into files, use Python’s in-built function write()
.
|
|
To close files, use Python’s in-built functionclose()
.
8.3 Reading files
To read files, open the file in read mode and use Python’s in-built function read()
.
|
|
seek()
method chnages our current file position.tell()
method changes returns our current position(in bytes).readline()
method reads individual lines of a file.readlines()
method reads all the lines and returns them as each line a string element in a list.writelines()
method inserts multiple strings at a single time.
Example: Combining the methods
|
|
Output:
|
|
References: