Contents

Fundamentals of programming


In this article, we will take a deep dive into the fundamentals of programming using Python.

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

In Python, a variable is created when a value is assigned to it.

1
2
x = 5
y = "This is fun!"

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.

1
2
3
a = 3        # a is 3
b = str(3)   # b is "3" 
c = float(3) # c is 3.0

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
Tip

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

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

Getting user input:

1
input("Name: ")

Combining variables and user input and outputting it:

1
2
3
name = input("Name: ")
age = input("Age: ")
print("Hello", name, "you are", age, "years old.")

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.

A list is an ordered sequence of items. The items in a list can have different data types.

To declare a list, use []:

1
2
3
random_list = [1, "abc", 3.1415]
list_in_list = [1, [2, 3]]       
#You can even have lists inside a list. It is called a nested list.

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
a = [5,10,15,20,25,30,35,40]

# a[2] = 15
print("a[2] = ", a[2])

# a[0:3] = [5, 10, 15] 
print("a[0:3] = ", a[0:3])

# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])

Lists are mutable, which means that the value of elements of a list can be changed.

1
2
3
4
a = [1, 2, 3]
a[2] = 4
print(a)     
#[1, 2, 4] will be printed

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 ():

1
2
3
4
t = (5,'program', 1+3j)

# This generates an error as tuples are immutable
t[0] = 10 

A set is an unordered collection of unique items.

To declare a set, use {}:

1
2
3
4
5
6
7
set1 = {1, 2, 3, 4, 5}
print(set1)  
#prints {1, 2, 3, 4, 5}

set2 = {1, 1, 2, 3, 2}
print(set2) 
#prints {1, 2, 3}

Since sets are unordered, indexing has no meaning.

1
2
a = {1, 2, 3}
print(a[1]) #generates an error

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}:

1
2
d = {1:'value','key':2}
type(d) #returns <class 'dict'>
  • 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.

Flow control refers to the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated.

if...elif...else statements are used in Python for decision making.

if statement

1
2
3
num = 5
if num > 0:
    print(num, "is a positive number")

if…else statement

1
2
3
4
5
num = 5
if num > 0:
    print(num, "is a positive number")
else:
    print(num, "is a negative number")

if…elif…else statement

1
2
3
4
5
6
7
num = 5
if num > 0:
    print(num, "is a more than zero")
elif num == 0:
    print(num, "is zero")
else:
    print(num, "is less than zero")

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:

1
2
3
4
5
6
7
8
9
numbers = [1, 2, 3]

sum = 0 #variable to store the sum

#iterate over the list
for n in numbers:
    sum += n

print(sum) #returns 48

A while loop is used to iterate over a block of code as long as the condition is true.

1
2
3
4
5
6
7
8
# initialize sum and counter
sum = 0
i = 0

while i <= 5:
    sum += i
    i += 1 # update counter
print(sum) #returns 15(1+2+3+4+5)

The break statement terminates the loop containing it when the test expression is satisfied.

/images/post/CSC1024/break.png

1
2
3
4
5
6
7
for val in "string":
    if val == "i":
        break
    print(val)
# prints  s
#         t
#         r

The continue statement is used to skip the rest of the code inside a loop for the current iteration only. /images/post/CSC1024/continue.png

1
2
3
4
5
6
7
8
9
for val in "string":
    if val == "i":
        continue
    print(val)
# prints  s
#         t
#         r
#         n
#         g

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.

User-defined functions are functions defined by the user. The syntax of a function is as shown:

1
2
def function_name(parameters):
    #code
  • 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.
1
2
def sum(x, y): 
    return x + y

Calling a function

To call a function, simply type the function name with appropriate arguments.

1
2
3
4
5
def sum(x, y): 
    return x + y

sum(2, 3) 
# 2 and 3 are the arguments; x and y are the paramaters

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

1
2
3
4
5
def greeting():
    name = input("Enter your name: ")
    print("Hello", name)

greeting() #Asks user to input name a prints greeting

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.

1
2
3
4
5
print(len("apple")) #returns 5
print(len(["cats", "dogs", "naked mole rat"])) #returns 3
print(list(range(0))) #returns []
print(list(range(4))) #returns [0, 1 , 2, 3]
print(list(range(2, 4))) #returns [2, 3, 4]

To learn about more built-in functions, click here.

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def my_func():
	x = 10
	print("Value inside function:",x)

x = 20
my_func()
print("Value outside function:",x)

#Output: 
#Value inside function: 10
#Value inside function: 20
  • In the example above, we can see that the value of x is 20 initially. Even though my_func() changed the value of x 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 the x 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.

In Python, a file operation takes place in the following order: open a fileread or writeclose the file.

To open files, use Python’s in-built function open()

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#Syntax
f = open(filename, mode, encoding) #mode and encoding is optional

#opening a file in current directory
f = open("test.txt")  

#opening a file in read mode
f = open("test.txt", r)  

#opening a file in read mode and in utf-8 encoding
f = open("test.txt", r, "utf-8")  
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).

To write into files, use Python’s in-built function write().

1
2
3
4
5
6
7
8
9
#append mode(adds line to the end)
f = open("myfile.txt", "a") 
f.write("Today \n")
f.close()

#write mode(overwrites existing lines)
f = open("myfile.txt", "w")  
f.write("Tomorrow \n")
f.close()

To close files, use Python’s in-built functionclose().

To read files, open the file in read mode and use Python’s in-built function read().

1
2
3
4
5
f = open("myfile.txt", "r") 
f.read(2) #read the first 2 data 
f.read(5) #read the next 5 data
f.read() #read til the end f file
f.read() #further reading returns an empty string
  • 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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#Creating a file
file1 = open("myfile.txt", "w")
L = ["I love sleep \n", "I love food \n", "I love cats \n"]

#Writing data to a file
file1.write("Hello \n")
file1.writelines(L)
file1.close()

# seek(n) takes the file from the beginning to the n-th bit. 
file1.seek(0)
  
#read() function
print("Output of Read function is :")
print(file1.read())
print()

file1.seek(0)

#readline() function  
print("Output of Readline function is ")
print(file1.readline())
print()
  
#readlines() function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close() 

Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
Output of Read function is
Hello
I love sleep
I love food
I love cats

Output of Readline function is
Hello

Output of Readlines function is
["I love sleep \n", "I love food \n", "I love cats \n"]

References:

  1. W3Schools
  2. Programiz
  3. GeeksforGeeks