Python Fundamentals


Python is a general-purpose programming language that is used for a wide variety of tasks, including Web development, Software development, Data analysis, Machine learning, Scientific computing, System Administration, and Automation.

Python is a popular language because it is

  • Relatively easy to read, learn and use
  • Powerful and versatile
  • Open source and free to use
  • Well-supported by a large community of developers

There is a lot that one can learn with Python, from parsing data to reading/writing files on the computer. This article highlights fundamental concepts that I have learned through the years of working with Python.

Objective

In order to learn about frameworks such as Django and Flask, you should have a basic understanding of Python which is why I wrote this article. Python fundamentals provide the building blocks of these frameworks and learning them will help you as they have helped me to navigate into learning them. I would not have created web apps in Django without first understanding the fundamentals explained below.

Data Types and Variables

A data type is a classification for data, which tells the compiler or interpreter how the data should be stored and manipulated. It defines the size and format of the data, as well as the operations that can be performed on it while a variable is a named location in memory that stores a value of a specific data type. The value of a variable can change during the execution of a program, hence the name variable.

Data Types in Python

Python has a rich set of built-in data types, they are as follows:

String Data Types

This data type is commonly used in Python and is used to store text. It has the following features:

  • Represents a sequence of Unicode characters.
  • Enclosed in either single quotes '' or double quotes "".

Strings in Python are immutable, meaning that once a string is created, it cannot be changed. However, you can perform various operations on strings, such as concatenation, slicing, and formatting, to manipulate and work with them. For more on string data type, refer to the Python string documentation.

Numeric Types

These data types are used in Python to store numbers such as integers, floating point numbers, and complex numbers. An integer represents whole numbers (positive, negative, or zero) without fractional or decimal parts. e.g. -2, 10, 2300, etc. Float/floating-point represents real numbers (numbers with fractional parts) e.g. 2.12, 0.03, -6.12, etc. For more on the numeric data types, refer to the Python numeric type documentation.

Sequence Types

These data types are used to store ordered collections of data such as lists, tuples, and range objects. Lists are mutable data structures i.e. can be changed and consist of a collection of items e.g. [1,2,3], ['Dog', 12, 'Query', True], etc. Tuples are an immutable collection of items e.g (1, "Joe", 34, 3.14), etc., and can be created using a pair of parentheses to denote the empty tuple: (), using a trailing comma for a singleton tuple: a, or (a,)

 or separating items with commas: a, b, c or (a, b, c). Range is an immutable sequence of numbers, used in looping for a specific number of times in for loops. For more on the sequence data types, refer to the Python sequence type documentation.

Mapping Types

These data types are used to store key-value pairs where each key is unique. Mappings are mutable objects meaning that they can be changed. There is currently only one standard mapping type in Python, the dictionary. The dictionary can be created by dict() or empty parentheses as {}. An example of the dictionary is {"name": "John", "age": 25}. The Python documentation has detailed information on the mapping data type.

Binary Types

These data types are used to store binary data. They include bytes, bytearray, and memoryview. Bytes objects are immutable sequences of single bytes. Bytearray is a mutable sequence type that represents an array of bytes. It is similar to a list, but its elements are restricted to integer values between 0 and 255 (inclusive), which correspond to the range of a byte. memory view is an object that provides a way to access the internal data of an object in a memory-efficient manner without making a copy. It allows you to interact with the underlying data buffer of an object, such as a bytes, bytearray, or array.array, without creating a new object in memory. Refer to Python's Binary data type section of the documentation.

Set Types

Sets are used to store multiple items in a single variable and can also be referred to as a collection that is unordered, unchangeable*, and unindexed. They are immutable and only support the removal and addition of new items. One unique property of these types is that they do not allow duplicates, therefore, being used to filter out any duplicates in a given collection. They include set and  frozenset. In a frozen set, the elements are fixed, unlike in sets therefore, cannot add or remove elements. To create a set in Python, use the set() or create a set with existing elements in curly braces i.e. x = {"Jane", "Mike", "Alonso"}. Refer to Python's set data type section of the documentation.

The Python official documentation has more details on built-in Types which include the ones highlighted above.

Summary

Data Type Short Description Illustration
str String my_str = "Joseph Kariuki" or some_nums = "123456789"
int Integer my_num = 12
float Floating-point number our_num = 3.142
complex Complex number z = 3 + 2j
list List fruits = ["Orange", "Banana", "Avocado", "Apple", "Apricot"]
tuple Tuple cardinal_points = ("North", "South", "East", "West")
range Range hours = range(25)
dict Dictionary languages = {1: "Python", 2: "JavaScript", 3: "Go", 4: "Rust"}
bytes Bytes my_bytes = b"hello, world!"
bytearray ByteArray my_bytearray = bytearray(b"hello, world!")
memoryview MemoryView my_memoryview = memoryview(b"hello, world!")
set Set misc_items = {1, "Jane", True, "Nairobi", 123, 1 + 2j}
frozenset Frozenset fixed_misc_items = frozenset(misc_items} (variable name referred from above)

 

Operators in Python

Operators are symbols or special characters that perform operations on one or more operands (values or variables) like the ones illustrated in the previous section. They allow you to perform various computations, comparisons, and logical operations. Python provides a wide range of operators, which can help when developing software. The groups of operators in Python include:

Arithmetic Operators

These operators are used to perform mathematical operations on numbers. For example, the + operator is used to adding two numbers, and the * operator is used to multiply two numbers. Other arithmetic operators include:

  • subtraction -
  • division /
  • floor division // the result is a float
  • modulus % 
  • exponential **

Assignment Operators

These operators are used to assign values to variables. For example, the = operator is used to assign a value to a variable, and the += operator is used to add a value to a variable and assign the result to the variable. The list also includes:

+=, -=, *=, /=, //=, %=, **= which perform corresponding arithmetic operations and assignments to the left operand.

Logical Operators

These operators are used to combine logical expressions. For example, the and operator is used to combine two logical expressions and determine if both expressions are true, and the or operator is used to combine two logical expressions and determine if either expression is true. Here are more illustrations:

  • and: Returns True if both operands are True.
  • or: Returns True if at least one operand is True.
  • not: Returns the opposite of the operand's logical value

Bitwise Operators

These operators are used to perform bitwise operations on numbers. For example, the & operator is used to perform a bitwise AND operation on two numbers, and the | operator is used to perform a bitwise OR operation on two numbers.

  • & (bitwise AND), | (bitwise OR), ^ (bitwise XOR): Perform bitwise operations on the binary representation of operands.
  • ~ (bitwise NOT): Flips the bits of the operand.
  • << (left shift), >> (right shift): Shift the bits of the operand left or right by the specified number of positions.

Membership Operators

Membership operators are used to determine if a value is a member of a sequence i.e. if a number is in a provided list.

  • in: Returns True if a value is present in a sequence.
  • not in: Returns True if a value is not present in a sequence.

Identity Operators

Identity operators compare if any two objects are actually the same. This is different from equality check.

  • is: Returns True if two variables refer to the same object.
  • is not: Returns True if two variables do not refer to the same object.

These are the main categories of operators in Python. Each operator has specific rules and behaviors depending on the types of operands it operates on. Operators allow you to perform a wide range of operations and computations in Python, making it a powerful language for various tasks.

Comparison Operators

Used to compare two values and determine if they are equal, greater than, less than, etc.

  • == (equal to): Checks if two operands are equal.
  • != (not equal to): Checks if two operands are not equal.
  • < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to): Perform the corresponding comparisons.

Conditional Statements

Conditional statements in Python are used to control the flow of execution of a program. They allow you to make decisions based on the values of variables or the result of comparisons.

If Statement

An if statement is used to execute a block of code if a condition is true.

if x > 8:
    print("x is greater than 8")

If-else Statement

An if-else statement is used to execute one block of code if a condition is true, and another block of code if the condition is false.

if x > 6:
    print("x is greater than 6")
else:
    print("x is not greater than 6")

If-elif-else Statement

An elif statement is used to execute a block of code if a condition is true, but only if the previous if or elif statements were not true.

if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")

Conditionals can also be nested, meaning one conditional statement can be inside another as shown in the example below.

x = 16
if x > 0:
    if x % 2 == 0:
        print("x is a positive even number")
    else:
        print("x is a positive odd number")
else:
    print("x is non-positive")

Conditional statements are fundamental for implementing logic and making decisions in your code based on different conditions. They enable you to control the flow of execution and create dynamic behavior in your Python programs.

Loops

Loops in Python are used to repeat a block of code a certain number of times or until a certain condition is met. There are two main types of loops in Python:

  • For loops: For loops are used to iterate over a sequence of elements, such as a list, a tuple, or a string.
  • While loops: While loops are used to execute a block of code as long as a condition is true.

For loop

This loop is used to iterate over a sequence of elements, such as a list, a tuple, or a string. For more details, refer to the Python documentation reference. An example:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

While Loop

The while loop repeatedly executes a block of code as long as a given condition is true. For more details, refer to the Python documentation reference. The condition is checked before each iteration. An example is shown below:

count = 0
while count < 5:
    print(count)
    count += 1

Here are some of the other features of loops in Python:

  • Break statement: The break statement is used to exit a loop prematurely.
  • Continue statement: The continue statement is used to skip the current iteration of a loop.
  • Else clause: The else clause is executed when the loop is finished, even if the loop was exited prematurely.

These loop structures and control statements provide the necessary tools to perform repetitive tasks, iterate over sequences, and implement different algorithms in Python.

Functions

A function is a named block of reusable code that performs a specific task. It allows you to organize your code into logical units and perform the same operation multiple times without duplicating code. Functions make your code modular, easier to read, and promote code reuse, and maintainability. In Python, Functions are defined using the def keyword. The def keyword is followed by the name of the function, the parameters that the function takes, and the body of the function. The body of the function is enclosed in curly braces. An example of a function:

def fac(n):
    if n == 0:
        return 1
    else:
        return n * fac(n - 1)

The function above is commonly used and its work is to calculate the factorial of a number n. Functions can be called using the name of function syntax, which in this case is fac() but we should include the parameter to be fac(6) which calculates the factorial of 6. Functions can have parameters, which are placeholders for the values that are passed to the function when it is called. Parameters allow functions to accept different inputs and make the code more flexible.

Types of Functions in Python

Functions can be classified into several types based on their purpose and behavior. Here are some common types of functions in Python:

  • Built-in functions
  • Lambda functions
  • User-defined functions
  • Recursive functions

Built-in Functions

Python provides a set of built-in functions that are available for use without the need for any import statements. These functions are part of the Python language itself and perform a variety of tasks, such as mathematical operations, string manipulation, input/output operations, type conversions, and more. We have used some of them in previous sections. Examples of built-in functions include len(), id(), zip(), print() and len() that are just a few among many well-detailed in Python documentation.

Lambda Functions

Lambda functions, also known as anonymous functions, are functions without a name. They are defined using the lambda keyword and are typically used for simple and one-line operations. The lambda keyword is followed by the parameters that the function takes, and the body of the function, which is a single expression. Lambda functions are commonly used in conjunction with built-in functions in certain situations.

double = lambda x: 4 * x

print(double(5))

This code defines a lambda function called double. The double function takes one parameter, x. The body of the function is a single expression, which multiplies x by 4. The double function is then called with the argument 5. The double function returns the value 20.

User-defined Functions

As the name suggests, user-defined functions are created by users themselves to perform specific tasks. These functions are defined using the def keyword and can have parameters and a return value This is similar to the function created in the introduction section. User-defined functions allow you to encapsulate a block of code and reuse it whenever needed, promoting code modularity and readability. Use the example for calculating factorial in the intro section as a reference. Understanding and utilizing these different types of functions can greatly enhance your ability to write efficient and modular code.

Recursive functions

Recursion is a method of solving a problem by breaking it down into smaller and smaller subproblems until the subproblems are simple enough to be solved directly. A good real-life example could be the proverbial Russian doll which comes as a full set with a doll inside another such that, whenever one uncovers the first one for example, another doll that is inside is exposed, and one continues until there are no more dolls to uncover. Recursive functions can be a powerful approach to solving problems that can be divided into smaller subproblems. Examples of recursive functions include:

  • Binary search algorithm function
    • def binary_search(arr, target, low, high):
          if low > high:
              return -1
          mid = (low + high) // 2
          if arr[mid] == target:
              return mid
          elif arr[mid] > target:
              return binary_search(arr, target, low, mid - 1)
          else:
              return binary_search(arr, target, mid + 1, high)

      array = [2, 4, 6, 8, 10, 12, 14]
      target = 10
      index = binary_search(array, target, 0, len(array) - 1)
      print(index)  # Output: 4

          

  • Fibonacci sequence function
    • def fibonacci(n):
          if n <= 1:
              return n
          else:
              return fibonacci(n - 1) + fibonacci(n - 2)

      result = fibonacci(6)
      print(result)  # Output: 8

  • Factorial function (example in the introduction section)

However, it's important to ensure that recursive functions have proper base cases to avoid infinite recursion.

Data Structures

Data structures provide a means of organizing data so that it can be easily accessed and manipulated. Data structures are used in almost every programming language, and they are essential for efficient programming and are a fundamental part of Computer Science. Since there are illustrations in previous sections, we will not give detailed definitions here. Data structures in Python programming language include:

Lists

Lists are one of the most commonly used data structures in Python. They are ordered, mutable, and can store a collection of items of different types. Lists are defined using square brackets [] or list() and can be modified by adding, removing, or modifying elements.

Tuples

Tuples are an immutable sequence data type that can store any type of data. Tuples are similar to lists, but they cannot be modified once they are created. Tuples are defined using parentheses () or tuple() and are often used to represent a collection of related values.

Sets

Sets are a collection of unique elements. Sets are efficient for checking if an element is in the set, but they can be inefficient for accessing elements by index. They are defined using curly braces {} or the set() function. Sets are useful for tasks like removing duplicates or testing membership.

Dictionaries

Dictionaries are key-value data structure that stores data in a mapping. Dictionaries are efficient for accessing data by key, but they can be inefficient for accessing data by index. They are defined using curly braces {} and colons : to separate keys and values.

By understanding the different types of data structures and their strengths and weaknesses, you can choose the right data structure for the specific problem that you are trying to solve. Python provides modules and libraries that offer more specialized data structures, such as arrays, stacks, queues, linked lists, heaps, and more. These data structures serve different purposes and are chosen based on the specific requirements of your program.

Conclusion


Learning Python's fundamental concepts provides you with a solid foundation to explore its vast capabilities, leverage its ecosystem, and apply it to solve real-world problems efficiently. It equips you with valuable skills that are highly transferable and sought after in the tech industry. Please read more on Python fundamentals from the following additional sources:

  1. Real Python
  2. Python official documentation
  3. Free code camp
  4. Corey Schafer's Python tutorials
 

Related articles

Comments

There are no comments yet.

Captcha* captcha
ABOUT ME
JosephKariuki

Hi, thanks for visiting! My name is Joseph Kariuki, a software developer and this is my website. I am consistently seeking solutions to various problems using coding. This site does not contain ads, trackers, affiliates, and sponsored posts.

DETAILS

Published: June 26, 2023

TAGS
fundamentals python
CATEGORIES
Python Fundamentals