Short cours of python with quiz

This article is a beginner’s guide to learning Python through a short course and quiz. It provides a comprehensive and easy-to-understand explanation of each part of Python, accompanied by relevant examples. The course is structured to enable beginners to quickly grasp the fundamentals of Python programming, and the quiz at the end of the article helps reinforce their learning. Whether you’re new to coding or looking to expand your skills, this article is a great starting point for anyone interested in learning Python.

  1. Basic syntax

In Python includes the fundamental elements of the language that are used to create programs. This includes concepts such as variables and data types, arithmetic operators, comparison operators, logical operators, conditional statements (if/else), loops (for/while), and functions. Understanding these concepts is essential to writing functional Python code.

  • “Hello World” program
# This is a comment

# "Hello World" program
print("Hello, World!")
  • Variables and data types
# Variable assignment
x = 5
y = "Hello, World!"
  • Arithmetic operators
# Arithmetic operators
a = x + 2
b = x * 3
c = x / 2
d = x % 2
  • Comparison operators
# Comparison operators
if x == 5:
    print("x is equal to 5")
if y != "Goodbye":
    print("y is not equal to 'Goodbye'")
  • Logical operators
# Comparison operators
if x == 5:
    print("x is equal to 5")
if y != "Goodbye":
    print("y is not equal to 'Goodbye'")
  • Conditional statements (if/else)
# Conditional statements
if x < 0:
    print("x is negative")
elif x == 0:
    print("x is zero")
else:
    print("x is positive")
  • Loops (for/while)
# Loops
for i in range(5):
    print(i)
    
while x > 0:
    print(x)
    x -= 1
  • Functions
# Functions
def say_hello(name):
    print("Hello, " + name)
    
say_hello("John")
  1. Data structures:

In Python are used to store and organize data. Python provides a number of built-in data structures, including lists, tuples, dictionaries, and sets. Each of these data structures has its own set of methods and properties for working with the data it contains. Understanding how to use these data structures is essential to working with data in Python. Additionally, Python provides libraries for working with more complex data structures, such as arrays and graphs.

  • Lists
# Lists
fruits = ["apple", "banana", "cherry"]
print(fruits[1])        # Output: banana
fruits.append("orange")
print(fruits)           # Output: ['apple', 'banana', 'cherry', 'orange']
fruits.remove("cherry")
print(fruits)           # Output: ['apple', 'banana', 'orange']
  • Tuples
# Tuples
person = ("John", 25, "USA")
print(person[0])        # Output: John
# person[0] = "Jane"    # TypeError: 'tuple' object does not support item assignment
  • Dictionaries
# Dictionaries
person = {"name": "John", "age": 25, "country": "USA"}
print(person["age"])    # Output: 25
person["age"] = 30
print(person)           # Output: {'name': 'John', 'age': 30, 'country': 'USA'}
person["gender"] = "male"
print(person)           # Output: {'name': 'John', 'age': 30, 'country': 'USA', 'gender': 'male'}
  • Sets
# Sets
fruits = {"apple", "banana", "cherry"}
print("banana" in fruits)    # Output: True
fruits.add("orange")
print(fruits)               # Output: {'banana', 'orange', 'apple', 'cherry'}
fruits.remove("cherry")
print(fruits)               # Output: {'banana', 'orange', 'apple'}
  1. File handling:

File handling in Python refers to the process of reading from and writing to files on a computer’s file system. Python provides built-in functions and modules for performing file handling tasks, including opening and closing files, reading and writing data to files, and navigating through the contents of a file. File handling is essential for many real-world applications, such as data processing, log analysis, and file management. It is important to understand how to properly handle files in Python to ensure that data is processed correctly and efficiently.

  • Opening and reading files
# Reading from a file
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

# Reading from a file line by line
file = open("example.txt", "r")
for line in file:
    print(line)
file.close()
  • Writing to files
# Writing to a file
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()

# Appending to a file
file = open("example.txt", "a")
file.write("\nThis is a new line.")
file.close()
  • Working with CSV files
import csv

# Writing to a CSV file
with open('example.csv', mode='w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['John', 25, 'New York'])
    writer.writerow(['Jane', 30, 'London'])
    writer.writerow(['Bob', 40, 'Paris'])

# Reading from a CSV file
with open('example.csv', mode='r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
  • Working with JSON files
import json

# Writing to a JSON file
data = {
    "name": "John",
    "age": 25,
    "city": "New York"
}
with open("example.json", "w") as file:
    json.dump(data, file)

# Reading from a JSON file
with open("example.json", "r") as file:
    data = json.load(file)
    print(data)
  1. Object-oriented programming:

Object-oriented programming (OOP) is a programming paradigm that emphasizes the use of objects and classes to represent real-world concepts in software development. In OOP, objects are instances of classes, which are templates that define the properties and behaviors of objects. Objects can interact with each other through methods, which are functions that are associated with classes.

OOP provides several advantages, including code reusability, modularity, and encapsulation. It allows developers to create complex systems that are easy to understand and maintain. OOP is widely used in many programming languages, including Python, Java, and C++.

Python supports OOP through the use of classes and objects. It allows developers to define their own classes and create objects based on those classes. Python also supports inheritance, which allows classes to inherit properties and methods from other classes. Additionally, Python supports polymorphism, which allows objects of different classes to be treated as if they are of the same class, simplifying code reuse.

  • Classes and objects
  1. we create a class called Person
  2. that represents a person’s name and age.
  3. We define a constructor method __init__ that takes two parameters name and age,
  4. which are used to set the name and age attributes of the object. We also define a
  5. get_details method that returns a string containing the name and age attributes of the object.
  6. We then create an instance of the Person class called person1 with the name “John” and age 25.
  7. We print the details of person1 using the get_details method.
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def get_details(self):
        return f"Name: {self.name}, Age: {self.age}"
    
person1 = Person("John", 25)
print(person1.get_details())
  • Inheritance
class Employee(Person):
    def __init__(self, name, age, salary):
        super().__init__(name, age)
        self.salary = salary

    def get_details(self):
        return f"Name: {self.name}, Age: {self.age}, Salary: {self.salary}"
    
employee1 = Employee("Jane", 30, 50000)
print(employee1.get_details())
  • Polymorphism
class Shape:
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

shapes = [Rectangle(5, 10), Circle(7)]
for shape in shapes:
    print(f"Area: {shape.area()}")
  • Encapsulation
class BankAccount:
    def __init__(self, account_number, balance):
        self.__account_number = account_number
        self._balance = balance  # protected attribute

    def deposit(self, amount):
        self._balance += amount

    def withdraw(self, amount):
        if amount <= self._balance:
            self._balance -= amount
        else:
            print("Insufficient balance")

    def get_account_number(self):
        return self.__account_number
    
    def get_balance(self):
        return self._balance
    
account1 = BankAccount("123456", 5000)
print(account1.get_account_number())  # prints "123456"
print(account1.get_balance())         # prints "5000"
account1._balance = 10000             # accessing protected attribute
print(account1.get_balance())         # prints "10000"
account1.__account_number = "789012"  # accessing private attribute
print(account1.get_account_number())  # prints "123456"
  • Abstraction
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width
    
    def area(self):
        return self.length * self.width

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
        
    def area(self):
        return 3.14 * self.radius * self.radius

# creating objects of Rectangle and Circle classes
rectangle = Rectangle(5, 10)
circle = Circle(7)

# calling the area method of each object
print(rectangle.area())   # prints "50"
print(circle.area())      # prints "153.86"
  1. Web development:
  • Flask framework
  • Django framework
  • Working with HTML and CSS
  • Interacting with databases using SQL and SQLAlchemy
  1. Data analysis and visualization:
  • NumPy

NumPy is a popular library for scientific computing in Python. It provides support for large, multi-dimensional arrays and matrices, along with a variety of mathematical functions to operate on them efficiently. Here’s an example that demonstrates how to use NumPy:

import numpy as np

# creating a one-dimensional array
arr1 = np.array([1, 2, 3, 4, 5])
print("One-dimensional array:")
print(arr1)
print("Shape of array:")
print(arr1.shape)
print()

# creating a two-dimensional array
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
print("Two-dimensional array:")
print(arr2)
print("Shape of array:")
print(arr2.shape)
print()

# performing element-wise operations
arr3 = np.array([1, 2, 3])
arr4 = np.array([4, 5, 6])
print("Element-wise addition:")
print(arr3 + arr4)
print("Element-wise multiplication:")
print(arr3 * arr4)
print()

# matrix operations
mat1 = np.array([[1, 2], [3, 4]])
mat2 = np.array([[5, 6], [7, 8]])
print("Matrix multiplication:")
print(np.matmul(mat1, mat2))
print("Matrix inverse:")
print(np.linalg.inv(mat1))
print()

# random number generation
rand_arr = np.random.rand(3, 3)
print("Random array:")
print(rand_arr)
  • Pandas (coming soon)
  • Matplotlib (coming soon)
  • Seaborn (coming soon)
  1. Machine learning:
  • Scikit-learn (coming soon)
  • Keras (coming soon)
  • TensorFlow (coming soon)
  • Natural Language Processing (NLP) with NLTK (coming soon)
  1. Miscellaneous topics:
  • Regular expressions (coming soon)
  • Error handling and debugging (coming soon)
  • Testing with unittest (coming soon)
  • Multithreading and multiprocessing. (coming soon)

Each of these categories can have several sub-topics and examples with code, so you can pick what suits you best and start exploring Python!