Python Fundamentals
Intro to Python
Python is a high-level, general-purpose language used in a variety of applications. Often associated with data science but also used in web development, game development, and for building desktop apps.
[Some Context 😀]
The term “high-level programming language” refers to a programming language that is designed to be easily understood and used by humans. High-level languages are often closer to human language and are more abstract, providing a higher level of abstraction from the low-level details of the computer’s architecture.
In contrast, low-level languages, such as assembly language or machine code, are closer to the hardware and provide more direct control over the computer’s resources. While low-level languages offer more control, they are often more challenging to learn and use, and they may require more code to accomplish tasks that can be done more concisely in high-level languages.(e.g., C, C++, Fortran,..)
Here are some characteristics of high-level programming languages
- Abstraction
High-level languages provide a higher level of abstraction, allowing programmers to focus on the problem they are trying to solve rather than the details of the computer’s hardware.
- Readability
High-level languages are designed to be easily readable and writable by humans. They often use natural language constructs and have a syntax that is closer to human language, making the code more understandable.
- Portability
Programs written in high-level languages are generally more portable because they are not tied to the specifics of a particular computer architecture. They can be run on different platforms with minimal or no modification.
- Productivity
High-level languages typically come with features and libraries that simplify common programming tasks, leading to increased productivity.
- Automatic Memory Management
Many high-level languages, including Python, provide automatic memory management, relieving the programmer from the responsibility of manually allocating and deallocating memory.
Installing Required Frameworks
Before we can write any code, we need to install a couple of items. For starters, we need to download a version of the language. Navigate to this website:
https://www.python.org/downloads/
And download the appropriate version of Python for your operating system.
Open the installer. Do check the ‘Add Python to PATH’ checkbox as you begin the installation and then continue following the next steps normally to complete the process.
That’s really all you need to write and run Python code!
You can use Visual Studio Code as an IDE, but if you don’t like visual studio code, you can just write Python code in a text editor (e.g. Notepad++) and run it through the terminal/cmd prompt with the line:
python <filename>
Or use and online IDE, such as replit.com
Writing Python Code
Printing
In Python, the print() function is used to display output. The print() function is a built-in function that allows you to output text or other data to the console or standard output. It’s commonly used for debugging, displaying information to the user, or just printing the results of a program.
Variables
Variables are the building blocks on which the rest of the program is written. They represent data and values that a program keeps track of and changes as it runs. Together, they represent the state of the program. Each variable has a name, a type, and a value. There are many different kinds of data that a variable can hold and the type describes exactly that. In Python, we don’t explicitly assign a type to a variable; that is interpreted automatically depending on the kind of data it holds and unlike in many other languages, variable types can change in Python.
https://medium.com/@adinasocaci.simona/python-101-primitive-data-types-f349943c2e98
Integers (int)
Integers represent whole numbers without any decimal point.
Example: 5, -10, 1000.
In Python, integers can be positive or negative.
Floats (float)
Floats represent numbers with decimal points.
Example: 3.14, -0.5, 2.0.
Floats can represent a wider range of numbers than integers.
Booleans (bool)
Booleans represent binary values indicating truth or falsehood.
There are only two possible boolean values: True and False.
Booleans are often used in conditional statements and logical operations.
Strings (str)
Strings represent sequences of characters enclosed in single (‘) or double (“) quotes.
Example: ‘Hello’, “Python”, ‘123’.
Strings are used to represent text data.
Checking Data Type
In Python, you can use the type() function to check the data type of a variable.
It’s important to note that Python is dynamically-typed, meaning the type of a variable is determined at runtime. You can reassign a variable to a different type, and the interpreter will adjust accordingly:
In the above example, the variable x starts as an integer and is later assigned a string value. The type() function reflects this change in the data type.
Operators
Operations allow us to programmatically change variable values rather than reassigning them manually. Seeing as we have already used the assignment operator ( = ) to assign a value to a variable, we will see 3 other kinds: arithmetic, comparison, and logical operators.
Arithmetic operators
Addition +:
Adds two numbers.
Subtraction -
Subtracts the right operand from the left operand.
Multiplication *
Multiplies two numbers.
Division /
Divides the left operand by the right operand. The result is a floating-point number.
Floor Division //
Similar to division but rounds down to the nearest whole number.
Modulus %
Returns the remainder of the division of the left operand by the right operand.
Exponentiation **
Raises the left operand to the power of the right operand.
Logical Operators
In Python, logical operators are used to perform logical operations on Boolean values. These operators allow you to combine or modify Boolean expressions.
Logical AND (and)
Returns True if both operands are True, otherwise returns False.
Logical OR (or)
Returns True if at least one of the operands is True, otherwise returns False.
Logical NOT (not)
Returns the opposite of the operand. If the operand is True, not returns False, and vice versa.
These logical operators are often used in conditional statements (if, elif, else) and in combination with conditional operators (such as ==, !=, <, >, <=, >=) to create complex conditions.
Here’s an example that uses logical operators in an if statement:
In this example:
- The and operator is used to check if both x and y are positive.
- The or operator is used to check if at least one of x or y is positive.
- The not operator is not used in this particular example but could be applied to check the negation of a condition.
Conditional Operators
Equal ==
Checks if two values are equal.
Not Equal !=
Checks if two values are not equal.
Greater Than >
Checks if the left operand is greater than the right operand.
Less Than <
Checks if the left operand is less than the right operand.
Greater Than or Equal To >=
Checks if the left operand is greater than or equal to the right operand.
Less Than or Equal To <=
Checks if the left operand is less than or equal to the right operand.
Lists
In Python, a list is a versatile and mutable data structure that allows you to store and manipulate a collection of items. Lists are defined by enclosing the items in square brackets [ ] and separating them with commas.
Thus, lists offer us the ability to store multiple values within a single variable.
Creating Lists
You can create a list by enclosing elements in square brackets.
Lists can contain elements of different types:
Accessing Elements
You can access elements in a list using indexing.
Python uses 0-based indexing, meaning the first element is at index 0:
You can also use negative indexing to access elements from the end of the list:
Slicing
You can create a sublist (slice) by specifying a range of indices:
Omitting the start or end index means the slice will go to the beginning or end of the list:
Modifying Lists
Lists are mutable, meaning you can change their elements:
You can also append elements to the end of the list:
[Just making sure😀]
As we number things from 1, 2, 3… Python starts numbering from 0.
So, the first element in a list will be 0 in python terms/indexes, thus list[0].
As seen in the below photo, the first element is element 0 which is “apple”; element 2 is list[1] = “banana”, and so on.
List Operations
Concatenation
You can concatenate two lists using the + operator:
Repetition
You can repeat a list using the * operator:
List Methods
Python provides several built-in methods for working with lists.
Here are a few:
len()
Returns the number of elements in a list:
append()
Adds an element to the end of the list:
insert()
Inserts an element at a specific position:
remove()
Removes the first occurrence of a specified value:
pop()
Removes and returns the element at a specified index (or the last element if no index is specified):
index()
Returns the index of the first occurrence of a specified value:
count()
Returns the number of occurrences of a specified value:
sort()
Sorts the elements of a list in ascending order:
reverse()
Reverses the order of the elements in a list:
Tuples
In Python, a tuple is a collection data type that is similar to a list, but with some key differences. Tuples are immutable, meaning their elements cannot be changed after creation. They are defined using parentheses ( ) instead of square brackets [ ].
Creating Tuples
You can create a tuple by enclosing elements in parentheses:
Tuples can contain elements of different types:
A tuple with a single element must have a trailing comma to distinguish it from a parenthesized expression:
Accessing Elements
You can access elements in a tuple using indexing, similar to lists, but you cannot modify them.
You can also use negative indexing:
Slicing
You can create a sub-tuple (slice) by specifying a range of indices:
Omitting the start or end index means the slice will go to the beginning or end of the tuple:
Tuple Operations
Concatenation
You can concatenate two tuples using the + operator:
Repetition
You can repeat a tuple using the * operator:
Tuple Methods
Tuples have fewer built-in methods compared to lists, as they are immutable.
Here are a couple of methods.
count()
Returns the number of occurrences of a specified value:
index()
Returns the index of the first occurrence of a specified value:
Lists vs Tuples
Lists and tuples are both data structures in Python used to store collections of items, but they have some key differences.
Mutability:
- Lists are mutable, meaning you can modify their elements after creation. You can add, remove, or modify items in a list.
- Tuples are immutable, meaning once they are created, their elements cannot be changed. You cannot add, remove, or modify items in a tuple.
Syntax:
- Lists are created using square brackets [].
- Tuples are created using parentheses ().
Use Cases:
- Use lists when you need a mutable, ordered collection. Lists are suitable when you want to store a collection of items that may change during the course of your program.
- Use tuples when you need an immutable, ordered collection. Tuples are useful when you want to ensure that the data remains constant throughout your program.
Use in Data Structures:
- Lists are often used for dynamic collections of items, such as in stacks, queues, or dynamic arrays.
- Tuples are often used for fixed collections of items, such as coordinates, settings, or records.
Dictionaries
Dictionaries attach their values to keys rather than storing them at specific positions or indexes.
The benefit of using a dictionary is that if we need to access a specific element, we don’t need to know its position (as we would have to if we stored it in a list); we only need the key under which we stored it.
Creating Dictionaries
You can create a dictionary by enclosing key-value pairs in curly braces {}:
Accessing Values
You can access values in a dictionary using the keys:
If a key is not present, attempting to access it will result in a KeyError.
Modifying Dictionaries
Dictionaries are mutable, so you can add, update, or delete key-value pairs:
Dictionary Methods
Dictionaries have several built-in methods. Here are a few:
keys(): Returns a view of all keys in the dictionary.
values(): Returns a view of all values in the dictionary.
items(): Returns a view of all key-value pairs in the dictionary.
If Statements
Now that we’re familiar with some of the building blocks, let’s introduce some logic and decision making into our code.
The if statement is a way to execute code only if some test returns true. The test is a boolean (True or False) and is often just comparing some variable value to another.
In Python, simple if statements are used to conditionally execute a block of code based on a single condition.
In this example, the indented block of code under the if statement is executed only if the condition x > 5 is True. In this case, since x is indeed greater than 5, the print statement will be executed.
You can also include an else block to specify what should be executed if the condition is False:
In this example, the else block is executed because the condition y > 5 is False. Therefore, the second print statement will be executed.
You can also use the elif (short for “else if”) statement to check multiple conditions in sequence:
Here, the conditions are checked in sequence. If z is greater than 0, the first print statement is executed. If z is less than 0, the second print statement is executed. If neither condition is met, the else block is executed.
While Loops
Now that we can perform tests and execute code once, the next step is to be able to perform tests and execute code multiple times as long as some condition continues to be true. For this, we use loops. Loops provide a way to execute code multiple times without having to type the same code again and again.
Here’s an example of a simple while loop:
In this example, the while loop will continue to execute the indented block of code as long as the condition count < 5 is True. The loop increments the count variable in each iteration and prints its value. The loop stops when count becomes 5.
You can use the break statement to exit a while loop prematurely based on a certain condition:
In this example, the while True creates an infinite loop. The loop is exited prematurely when the number variable becomes greater than 5 due to the break statement.
You can also use the else block with a while loop. The else block is executed when the loop condition becomes False:
In this example, the else block is executed after the while loop completes its iterations because the condition i < 5 becomes False.
For Loops
In Python, a for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or other iterable objects. This acts the same as a while loop but it runs a preset number of times. We put into the loop when to start and when to stop so we know how many times it will run.
In this example, the for loop iterates over each element in the fruits list, and the fruit variable takes on each value in turn. The loop prints each fruit.
You can use the range() function to create a sequence of numbers and iterate over it:
This for loop prints numbers from 1 to 5. The range(1, 6) generates a sequence of numbers starting from 1 up to (but not including) 6.
You can use the break statement to exit a for loop prematurely based on a certain condition:
In this example, the loop stops prematurely if the value of fruit is “banana” due to the break statement.
You can also use the else block with a for loop. The else block is executed after the for loop completes its iterations, unless the loop was terminated by a break:
In this example, the else block is executed because the for loop completes its iterations without encountering a break statement.
Functions
Functions are just contained blocks of code that run only when we choose. They remain dormant until we call on the function, at which point the code within the function is run. The benefit of doing this is that we can hide away code and choose to run it at specific times. This also allows us to execute the same functionality at potentially many different points in the program without having to rewrite the code; we can simply call upon the function and it runs the code in its body.
Defining a Function
function_name: The name of the function.
parameters: Inputs that the function accepts.
return: Optional keyword to return a value from the function.
Example of a Simple Function
Function with Return Value
Classes and Objects
In Python, classes and objects are fundamental concepts in object-oriented programming (OOP).
Classes
A class is a blueprint for creating objects. It defines a set of attributes and methods that the objects created from the class will have. Think of a class as a template or a prototype.
__init__: The constructor method, called when an object is created. It initializes the object’s attributes.
self: A reference to the instance of the class. It is used to access the object’s attributes and methods.
Example of a Class
Objects
An object is an instance of a class. It is a concrete realization of the class blueprint, with specific values for its attributes. In the example above, dog1 and dog2 are objects created from the Dog class.
Inheritance
Inheritance is a concept where a new class (subclass) can inherit attributes and methods from an existing class (superclass). It promotes code reuse and allows for the creation of more specialized classes.
In this example, the Cat class inherits from the Animal class, and it has its own method purr. Instances of Cat have access to both Animal’s attributes and methods and their own.
Encapsulation
Encapsulation is the bundling of data (attributes) and the methods that operate on that data within a single unit (a class). It helps in controlling access to the internal details of a class and promotes data hiding.
In this example, the balance attribute is encapsulated within the BankAccount class, and its access and modification are controlled through methods.
Congratulations on making it to the end of the fundamentals course!
Thank you for reading! 💖
Follow me |Subscribe to know when I publish a story
Like this lesson? Buy me a coffee and show your appreciation ✨