Python is a popular high-level programming language that is used for a wide range of applications, including web development, data analysis, machine learning, and more.
Python is known for its simplicity, ease of use, and versatility, making it a great language for beginners and experts alike.
In this tutorial, we'll cover the basics of Python programming, including syntax, data types, variables, functions, object-oriented programming, and more. By the end of the tutorial, you'll have a solid foundation in Python and be ready to tackle more advanced topics and projects.
Python has a simple and easy-to-learn syntax. Here are some of the basic syntax elements:
# This is a comment
print("Hi!")# This is also a comment
x = 5
y = 3
z = x + y
print(z)# Output: 8
Python supports a variety of data types, including:
Numbers: integer, float, complex
# Numbers
x = 5
y = 3.14
z = complex(1, 2)
print(x,y,z) # Output: 5 3.14 (1+2j)
Strings
# Strings
s1 = "Hello!"
s2 = """This is a
multi-line string"""
print(s1,s2,s3) # Output: Hello! This is a
multi-line string
Lists
Example
fruits = ["apple", "banana", "cherry"]
Accessing elements
print("First fruit:", fruits[0]) # Output: apple
Appending elements
fruits.append("orange")
print("After appending:", fruits)
# Output: ['apple', 'banana', 'cherry', 'orange']
Inserting elements at specific positions
fruits.insert(1,"grape")
print("After inserting at index 1:", fruits)
# Output: ['apple', 'grape', 'banana', 'cherry', 'orange']
Removing elements by value
fruits.remove("banana")
print("After removing 'banana':",fruits)
# Output: ['apple', 'grape', 'cherry', 'orange']
Removing elements by index
popped_fruit = fruits.pop(1)
print("After popping:",fruits)# Output: ['apple', 'cherry', 'orange']
print("Popped fruit:",popped_fruit)# Popped fruit: grape
Sorting a list (in-place)
fruits.sort()
print("Sorted fruits:",fruits)
# Output: ['apple', 'cherry', 'orange']
Sorting a list (without modifying original list)
sorted_fruits = sorted(fruits)
print("Sorted (non-destructive):",sorted_fruits)
# Output: ['apple', 'cherry', 'orange']
Slicing lists
sliced_fruits = fruits[1:3]
print("Sliced fruits:",sliced_fruits)
# Output: ['cherry', 'orange']
Reversing a list
reversed_fruits = list(reversed(fruits))
print("Reversed fruits:",reversed_fruits)
# Output: ['orange', 'cherry', 'apple']
Tuples
Accessing elements
numbers = (1, 2, 3)
print("Second number:",numbers[1])
# Output: 2
Counting occurrences of a value
numbers = (1, 2, 3)
count_of_twos = numbers.count(2)
print("Count of twos:", count_of_twos)# Output: 1
Finding index of a value
numbers = (1, 2, 3)
index_of_three = numbers.index(3)
print("Index of three:", index_of_three)# Output: 2
Combining tuples
other_numbers = (4, 5, 6)
combined_numbers = numbers + other_numbers
print("Combined tuple:", combined_numbers)# Output: (1, 2, 3, 4, 5, 6)
Unpacking tuples
x, y, z = numbers
print("Unpacked numbers:", x, y, z)# Output: Unpacked numbers: 1 2 3
Checking membership
is_in_tuple = 4 in combined_numbers
print("Is 4 in tuple?",is_in_tuple)# Output: True
Tuple to list conversion
numbers_list = list(numbers)
print("Tuple to list:", numbers_list)# Output: [1, 2, 3]
List to tuple conversion
other_numbers_tuple = tuple(other_numbers)
print("List to tuple:", other_numbers_tuple)# Output: (4, 5, 6)
Sets
Adding elements
colors = { "red", "green", "blue" }
colors.add("yellow")
print("After adding 'yellow':", colors)# Output: {'green', 'blue', 'red', 'yellow'}
Removing elements
colors.remove("green")
print("After removing 'green':", colors)
# Output: {'blue', 'red', 'yellow'}
Checking membership
is_red_in_colors = "red" in colors
print("Is 'red' in colors?", is_red_in_colors)
# Output: True
Set union
more_colors = {"orange", "purple", "green"}
all_colors = colors.union(more_colors)
print("All colors:", all_colors) # Output: { 'yellow', 'purple', 'blue', 'orange', 'green', 'red' }
Set intersection
common_colors = colors.intersection(more_colors)
print("Common colors:", common_colors) # Output: { 'green' }
Clearing a set
colors.clear()
print("After clearing:", colors) # Output: set()
Set difference
unique_to_colors = colors.difference(more_colors)
print("Unique to colors:", unique_to_colors)
# Output: { 'blue', 'red', 'yellow' }
Set symmetric difference
symmetric_diff = colors.symmetric_difference(more_colors)
print("Symmetric difference:", symmetric_diff)
# Output: { 'yellow', 'purple', 'blue', 'orange', 'red' }
Dictionaries
Creating a dictionary
my_dict = {
"key1": "value1",
"key2": "value2"
}
Accessing values
print(my_dict["key1"]) # Output: value1
print(my_dict["key2"]) # Output: value2
Adding a new key-value pair
my_dict["key3"] = "value3"
print(my_dict)
# Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Removing a key-value pair
del my_dict["key2"]
print(my_dict)
# Output: {'key1': 'value1', 'key3': 'value3'}
Check if key exists
print("key1" in my_dict)
# Output: True if key exists, False otherwise
Get list of keys
print(my_dict.keys())
# Output: dict_keys(['key1', 'key2', 'key3'])
Get list of values
print(my_dict.values())
# Output: dict_values(['value1', 'value2', 'value3'])
Get list of key-value pairs
print(my_dict.items())
# Output: dict_items([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')])
Booleans
Operations
a = True
b = False
# Logical AND
print(a and b) # Output: False
# Logical OR
print(a or b) # Output: True
# Logical NOT
print(not a) # Output: False
In Python, variables are used to store data values. A variable is created when a value is assigned to it using the "=" operator. For example:
x = 5
y = "Hello, world!"
In this example, we've created two variables: "x" and "y". "x" is assigned the value of 5, which is an integer, and "y" is assigned the value of "Hello, world!", which is a string.
Python has several built-in data types, including integers, floating-point numbers, strings, booleans, and more. These data types can be combined using operators to perform operations on them. Some common operators include:
Fere are some examples of using operators with variables:
Variable Assignments
x = 10
y = 5
Logical Operations
print(not x) # Output: False
print(x > 3 and y < 6) # Output: true
print( x > 3 or y < 3) # Output: true
Arithmetic Operations
print(x + y) # Output: 15
print(x - y) # Output: 5
print(x * y) # Output: 50
print(x / y) # Output: 2.0
print(x % y) # Output: 0
print(x ** y) # Output: 100000
Comparison Operations
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: True
print(x < y ) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False
Assignment Operations
x += 5
print(x) # Output: 15
x -= 5
print(x) # Output: 10
x *= 2
print(x) # Output: 20
x /= 2
print(x) # Output: 10.0
x %= 3
print(x) # Output: 1.0
x **= 2
print(x) # Output: 1.0
Conditional statements and loops are fundamental concepts in programming that allow you to control the flow of your code. They enable you to make decisions based on certain conditions and perform repetitive tasks efficiently.
Conditional statements are used to execute different blocks of code depending on whether a certain condition is true or false. In Python, we use the if
, for
, and while
statements to create conditional statements.
1. the if
statement
if condition1:
# execute code if condition1 is true
elif condition2:
# execute code if condition2 is true
else:
# execute code if none of the above conditions are true
Here's an example that uses conditional statements to determine whether a number is positive, negative, or zero:
num = -5
if num > 0:
# print "Positive number" if num is greater than 0
elif num == 0:
# print "Zero"
else:
# print "Negative number"
2. the for
statement
Here's an example that uses a for
loop to iterate over a list and print each item:
fruits = ["apple", "banana", "cherry"]
# iterate through the fruits list
for fruit in fruits:
print(fruit)
# list comprehension for printing fruits
[print(fruit) for fruit in fruits]
It is also possibe mix them as needed
fruits = ["apple", "banana", "cherry"]
# Iterate through the fruits list and print only if fruit is "cherry"
[print(fruit) for fruit in fruits if fruit == "cherry"]
# or
for fruit in fruits:
if fruit == "cherry"
print(fruits)
1. the while
statement
Here's an example that uses a while
loop to print the numbers from 1 to 5:
num = 1
while num < 5:
print(num) num += 1
List comprehensions provide a concise way to create lists based on existing lists. They are a more Pythonic way of iterating over a list and transforming its elements.
# list comprehension example
original_list = [1, 2, 3, 4, 5]
new_list = [item * 2 for item in original_list]
print(newList) # [2, 4, 6, 8, 10]
In this example, we create a new list newList
based on an existing list originalList
. The new list is created using a list comprehension, which consists of the expression item * 2
followed by a for
statement that specifies how to iterate over the elements of the original list.
List comprehensions can also include conditional statements to filter the elements of the original list. Here's an example that creates a new list containing only the even numbers from the original list:
original_list = [1, 2, 3, 4, 5]
new_list = [item * 2 for item in original_list if item % 2 == 0]
print(newList) # [2, 4]
In this example, we add a conditional statement to the list comprehension using the if
keyword. The conditional statement checks whether each element of the original list is even (item % 2 === 0
), and only the even elements are included in the new list.
In addition to list comprehensions, Python also supports dictionary comprehensions, which provide a concise way to create dictionaries based on existing dictionaries.
original_dict = {"apple": 1, "banana": 2, "cherry": 3}
# Iterate through the original dictionary and multiply each value by 2
new_dict = {key: value * 2 for key, value in original_dict.items()}
# Print the new dictionary
print(new_dict) # {"apple": 2, "banana": 4, "cherry": 6}
In this example, we create a new dictionary newDict
based on an existing dictionary originalDict
. The new dictionary is created using a dictionary comprehension, which consists of the expression value * 2
followed by a for
statement that specifies how to iterate over the key-value pairs of the original dictionary.
Dictionary comprehensions can also include conditional statements to filter the key-value pairs of the original dictionary. Here's an example:
original_dict = {"apple": 1, "banana": 2, "cherry": 3}
# Iterate through the original dictionary and multiply each value by 2 if value is greater than 1
{key: value * 2 for key, value in original_dict.items() if value > 1}
# Print the new dictionary
print(new_dict) # {"banana": 4, "cherry": 6}
As you can see, dictionary comprehensions are similar to list comprehensions, but they produce dictionaries instead of lists. They can be a very powerful tool for manipulating dictionaries in a concise and readable way.
Functions and modules are essential building blocks of any Python program. They allow you to break down your code into smaller, reusable pieces that can be organized and maintained more easily. Here are some examples of functions and modules in Python:
A function is a block of code that performs a specific task. Functions help to make your code more modular and reusable, and can also take in inputs and return outputs.
To define a function in Python, use the def
keyword followed by the function name and its arguments in parentheses. The code inside the function should be indented, and the function can optionally return a value using the return
keyword.
Here's a basic example:
def add_numbers(x, y):
return x + y
result = add_numbers(5, 10)
print(result) # Output: 15
In this example, we call the add_numbers
function with the arguments 5
and 10
, and store the result in a variable called result
. Finally, we print the result using the print
function, which outputs 15
.
Here's an example of a function that takes in a list of numbers and returns the sum:
def sum_numbers(numbers):
result = 0
for num in numbers:
result += num
return result
my_numbers = [1, 2, 3, 4, 5]
total = sum_numbers(my_numbers)
print(total) # Output: 15
In this example, we define a function called sum_numbers
that takes in a list of numbers called numbers
, and returns their sum. We initialize a variable called result
to 0, and then use a for
loop to iterate through the list of numbers and add each one to the result. Finally, we return the result.
To call a function, simply use its name followed by its arguments in parentheses. In the example above, we call the sum_numbers
function with the list of numbers [1, 2, 3, 4, 5]
and store the result in a variable called total
. We then print the result, which is 15
.
Functions can also have optional arguments with default values. Here's an example:
def greet(name, greeting="Hello"):
print(greeting + ", " + name + "!")
greet("Alice") # Output: "Hello, Alice!"
greet("Bob", "Hi") # Output: "Hi, Bob!"
In this example, we define a function called greet
that takes in two arguments, name
and greeting
, with a default value of "Hello". We then print out the greeting followed by the name.
When we call the function with just one argument (greet("Alice")
), it uses the default value for greeting
and prints "Hello, Alice!". When we call the function with both arguments (greet("Bob", "Hi")
), it uses the provided value for greeting
and prints "Hi, Bob!".
A module is a file that contains Python code, which can be imported and used in other Python files. Modules help to organize your code and keep related functionality together. Here's an example of a module calledmath_utils.py
that defines some mathematical functions:
# math_utils.py
def add_numbers(a, b):
return a + b
def multiply_numbers(a, b):
return a * b
def subtract_numbers(a, b):
return a - b
In this example, we define three functions for adding, multiplying, and subtracting numbers. We can then import this module into another Python file and use these functions. Here's an example of how we can use this module in a file called main.py
:
# main.py
import math_utils
result1 = math_utils.add_numbers(5, 10)
result2 = math_utils.multiply_numbers(5, 10)
result3 = math_utils.subtract_numbers(5, 10)
print(result1) # Output: 15
print(result2) # Output: 50
print(result3) # Output: -5
math_utils
module and use its functions to perform some basic arithmetic operations. We call the add_numbers
function with the arguments 5
and 10
, which returns the sum of the two numbers. We then call the multiply_numbers
function with the same arguments, which returns their product. Finally, we call the subtract_numbers
function with the same arguments, which returns their difference. We store the results in variables called result1
, result2
, and result3
, respectively, and print them to the console.Object-Oriented Programming (OOP) is a programming paradigm that emphasizes the use of objects, which are instances of classes, to represent and manipulate data. Here are some of the key concepts in OOP:
To create a class in Python, you use the class
keyword followed by the name of the class. Here's an example of a simple class that represents a bank account:
class BankAccount: # Define a class called BankAccount
def __init__(self, account_number, balance):# Constructor method to initialize account number and balance
self.account_number = account_number # Set the account number
self.balance = balance # Set the balance
def deposit(self, amount): # Method to deposit money into the account
self.balance += amount # Add the deposited amount to the balance
def withdraw(self, amount): # Method to withdraw money from the account
if amount <= self.balance: # Check if there are sufficient funds
self.balance -= amount # Subtract the withdrawn amount from the balance
else: # If there are insufficient funds, print a message
print("Insufficient funds")
def get_balance(self): # Method to retrieve the current balance
return self.balance # Return the balance
my_account = BankAccount("123456789", 1000) # Create a new BankAccount object
my_account.deposit(500) # Deposit 500 into the account
my_account.withdraw(2000) # Withdraw 2000 from the account
print(my_account.get_balance()) # Output: 1500
In this example, we define a class called BankAccount
that has four methods: __init__
, deposit
, withdraw
, and get_balance
. The __init__
method is a special method that is called when an object is created from the class and is used to initialize the object's attributes. The other three methods are used to modify the object's state by depositing or withdrawing money and getting the account balance.
Encapsulation is the concept of hiding the internal details of an object from the outside world and providing a public interface for interacting with the object. This is achieved in OOP through the use of access modifiers, such as public, private, and protected. These access modifiers control which parts of an object can be accessed from outside the object's class. In Python, access modifiers are implemented using underscores before the attribute or method name.
class Dog: # Define a class called Dog
def __init__(self, name, age): # Constructor method to initialize name and age
self.name = name # Set the dog's name
self.age = age # Set the dog's age
def bark(self): # Method for the dog to bark
print("Woof!") # Output: "Woof!"
my_dog = Dog("Rufus", 3) # Create a Dog instance with name "Rufus" and age 3
my_dog.bark() # Output: "Woof!"
Abstraction is the concept of simplifying complex systems by breaking them down into smaller, more manageable parts. In OOP, abstraction is achieved by defining abstract classes and interfaces. An abstract class is a class that cannot be instantiated on its own and must be subclassed to be used. An interface is a collection of abstract methods that define a contract for classes that implement the interface. Python does not have built-in support for interfaces, but they can be emulated using abstract base classes.
class Car: # Define a class called Car
def start(self): # Method to start the car
pass # Placeholder implementation
def stop(self): # Method to stop the car
pass # Placeholder implementation
class Honda(Car): # Define a class called Honda inheriting from Car
def start(self): # Method to start a Honda
print("Starting Honda") # Output: "Starting Honda"
def stop(self): # Method to stop a Honda
print("Stopping Honda") # Output: "Stopping Honda"
my_honda = Honda()
my_honda.start() # Output: "Starting Honda"
my_honda.stop() # Output: "Stopping Honda"
Polymorphism is the ability of objects to take on multiple forms or have multiple behaviors depending on the context in which they are used. In Python, polymorphism is achieved through the use of duck typing, which is a concept that allows objects to be used as if they are of a certain type based on their behavior, rather than their class. For example, if an object has a method called "quack", it can be used as if it were a duck object, even if it is not actually a duck.
class Animal: # Define a class called Animal
def make_sound(self): # Method to make a sound
pass # Placeholder implementation
class Cat(Animal): # Define a class called Cat inheriting from Animal
def make_sound(self): # Method to make a cat sound
print("Meow") # Output: "Meow"
class Dog(Animal): # Define a class called Dog inheriting from Animal
def make_sound(self): # Method to make a dog sound
print("Woof") # Output: "Woof"
def animal_sounds(animal): # Function to produce animal sounds
animal.make_sound()
my_cat = Cat()
my_dog = Dog()
animal_sounds(my_cat) # Output: "Meow"
animal_sounds(my_dog) # Output: "Woof"
Inheritance is the concept of creating a new class from an existing class by inheriting its attributes and methods. In Python, inheritance is implemented using the syntax class ChildClass(ParentClass):
. The child class inherits all the attributes and methods of the parent class and can also define its own attributes and methods. Inheritance is useful for creating classes that share common functionality, such as different types of animals or vehicles.
class Vehicle: # Define a class called Vehicle
def __init__(self, make, model, year): # Constructor method to initialize vehicle details
self.make = make
self.model = model
self.year = year
def start(self): # Method to start the vehicle
print("Starting vehicle")
class Car(Vehicle): # Define a class called Car inheriting from Vehicle
def stop(self): # Method to stop the car
print("Stopping car")
my_car = Car("Honda","Civic", 2022)
print(my_car.make) print(my_car.model) # Output: "Civic"
print(my_car.year) # Output: 2022
my_car.start() # Output: "Starting vehicle"
my_car.stop() # Output: "Stopping car"
File input/output (I/O) is an important aspect of programming. It allows you to read from and write to files on your computer. Python provides many ways to work with files. In this section, we'll explore some of the basics of file I/O in Python.
The first step in working with a file is to open it. To do this, we use the built-in open()
function. The open()
function takes two arguments: the path to the file and the mode in which the file should be opened. The mode can be "r" for reading, "w" for writing, or "a" for appending. For example, to open a file called "example.txt" for reading, we would use the following code:
file = open("example.txt", "r") # you can use a path like '/Users/ProjectsFolder/example.txt'
Once the file is open, we can perform various operations on it such as reading or writing data.
In this example, we first open the file "example.txt" in read mode. We then use the read()
method to read the contents of the file into a variable called "contents". Finally, we use the console.log()
function to print the contents of the file in the browser console.
const readFile = () => {
// Open the file in read mode
const file = open("/example.txt", "r");
// Read the contents of the file
const contents = file.read();
// Close the file
file.close();
// Print the contents of the file in the browser console
console.log(contents);
}
In Python, exceptions are raised when errors or other exceptional events occur during program execution. Exception handling allows us to gracefully handle these exceptions, preventing our program from crashing and allowing us to handle errors in a controlled manner.
When an exception is raised, Python looks for a matching exception handler in the current function, then in the calling function, and so on up the call stack until it finds a handler. If it does not find a handler, the program will crash and an error message will be displayed.
Here is some of the common used built-in exceptions
We can use the try
and except
statements to catch and handle exceptions in our code. The try
block contains the code that may raise an exception, and the except
block contains the code that handles the exception. For example:
try:
# Some code that may raise an exception
except ExceptionType:
# Code to handle the exception
In the example above, if an exception of type ExceptionType
is raised in the try
block, Python will execute the code in the except
block to handle the exception.
Here is an example that demonstrates how to use exception handling in Python to catch and handle a ZeroDivisionError
:
try:
# Perform a division that may raise a ZeroDivisionError
result = 10 / 0
except ZeroDivisionError:
# Handle the ZeroDivisionError
print("Cannot divide by zero!")
In Python, you can also handle multiple exceptions using a single except
block. Here's an example that demonstrates this:
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
result = a / b
print("Result:", result)
except (ValueError, ZeroDivisionError) as e:
print("Error:", e)
print("Please enter a valid number and make sure the second number is not zero.")
In this example, we're trying to divide two numbers that the user inputs. If either of the inputs is not a valid integer, or if the second input is zero, a corresponding exception will be raised. We're using a single except
block to handle both of these exceptions, and printing an appropriate error message to the user.