Back to Python
2026-02-017 min read

JS 2021 (Python Programming)

Learn JS 2021 (Python Programming) step by step with clear examples and exercises.

Why This Matters

Learning Python is crucial for JavaScript developers who want to broaden their skillset and tackle more complex projects. Python's versatility makes it an ideal choice for various domains such as data science, machine learning, web development, system scripting, and collaboration with other developers who prefer Python.

Python's clean, easy-to-read syntax allows developers to write code that is not only efficient but also easier to understand and maintain. This can significantly reduce the time spent on debugging and improve overall productivity.

Prerequisites

To get the most out of this lesson, you should have a solid understanding of:

  1. Basic JavaScript syntax and concepts (variables, functions, loops, etc.)
  2. Familiarity with a code editor like Visual Studio Code or Atom
  3. A good grasp of the command line or terminal
  4. Understanding of data structures such as arrays and objects in JavaScript
  5. Knowledge of common algorithms and data structures used in programming
  6. Basic understanding of object-oriented programming principles (optional but beneficial)
  7. Familiarity with Git for version control (optional but recommended)
  8. Basic understanding of Unix/Linux command line tools (optional but recommended)

Core Concept

Python has a clean, easy-to-read syntax that sets it apart from other programming languages. Here's an overview of some key elements:

Variables

Declare variables using the = operator:

my_variable = "Hello, World!"
print(my_variable) # Output: Hello, World!

Python automatically infers variable types.

Data Types

Python has several built-in data types:

  1. Integers (e.g., 5, 99)
  2. Floating-point numbers (e.g., 3.14, 0.007 )
  3. Strings (enclosed in quotes, e.g., "Hello" or 'World')
  4. Lists (ordered collections enclosed in square brackets, e.g., [1, 2, 3])
  5. Tuples (immutable ordered collections enclosed in parentheses, e.g., (1, 2, 3))
  6. Dictionaries (unordered key-value pairs enclosed in curly braces, e.g., {"name": "John", "age": 30})
  7. Booleans (True and False)
  8. None (represents the absence of a value)
  9. Sets (unordered collection of unique elements enclosed in curly braces with no keys, e.g., {1, 2, 3})
  10. Byte strings (enclosed in single quotes and prefixed with b, e.g., b'Hello')

Control Structures

Python has several control structures to manage the flow of execution:

  1. Conditional statements using if, elif, and else
  2. Loops with for and while
  3. Functions defined using the def keyword
  4. Exception handling using try, except, finally, and raise
  5. Context managers (using with) for working with resources that require explicit management, such as files or network connections
  6. Generators for creating iterable objects on-demand
  7. Decorators for modifying function behavior at runtime
  8. Comprehensions for creating collections using concise syntax

Modules and Packages

Python organizes code into modules and packages for reusability and better organization. To use a module, import it using the import statement:

import math # Importing the math module
print(math.sqrt(16)) # Output: 4.0

Python's standard library contains many useful modules for various tasks, such as file I/O, networking, and mathematical functions. Additionally, thousands of third-party packages are available to extend Python's functionality even further.

Worked Example

Let's create a simple Python script that calculates the Fibonacci sequence up to a given number n.

def fibonacci(n):
fib_sequence = [0, 1]

while len(fib_sequence) < n:
next_number = fib_sequence[-1] + fib_sequence[-2]
fib_sequence.append(next_number)

return fib_sequence[:n]

n = int(input("Enter the number of Fibonacci numbers to calculate: "))
result = fibonacci(n)
print(result)

Running the script

Save this code in a file named fibonacci.py. Run it from the command line using the following command:

python fibonacci.py

Common Mistakes

  1. Forgetting to import necessary modules
  2. Using = instead of == for comparison (assignment vs equality)
  3. Neglecting to handle edge cases in conditional statements
  4. Misusing Python's indentation rules, which determine code block structure
  5. Not properly closing multi-line strings with a newline character (\n)
  6. Using print() multiple times for the same output, which concatenates outputs by default
  7. Assuming that variables have a specific type and not handling mixed types in operations
  8. Forgetting to close files after reading or writing data
  9. Not properly using context managers when working with resources that require explicit management
  10. Incorrectly implementing exception handling, leading to unhandled exceptions
  11. Misusing list comprehensions by trying to perform complex operations inside them (use functions instead for better readability)
  12. Overlooking the difference between mutable and immutable data structures when passing them as arguments to functions
  13. Not understanding the concept of a global scope and local scope, leading to unexpected variable behavior
  14. Ignoring Python's built-in debugging tools like pdb for troubleshooting issues
  15. Failing to document code using comments or docstrings, making it harder for others to understand and maintain

Subheadings under Common Mistakes:

Best Practices for Avoiding Common Mistakes

  1. Import necessary modules at the beginning of your script
  2. Use meaningful variable names
  3. Handle edge cases in conditional statements
  4. Follow Python's indentation rules consistently
  5. Properly close files and manage resources using context managers
  6. Document your code with comments and docstrings
  7. Use functions to perform complex operations instead of list comprehensions when necessary
  8. Understand the difference between mutable and immutable data structures
  9. Familiarize yourself with Python's built-in debugging tools like pdb
  10. Organize your code using modules, packages, and functions for better readability and maintainability

Practice Questions

  1. Write a Python script to find the factorial of a number using recursion.
  2. Create a Python function that takes a list of numbers as input and returns the sum of all even numbers.
  3. Write a Python program that calculates the average of a list of numbers.
  4. Implement a function to reverse a string in Python.
  5. Given two lists of integers, write a Python function that finds the intersection (common elements) between them.
  6. Write a Python script to find the largest prime number in a given range.
  7. Create a Python program that generates Fibonacci numbers up to a specific point and prints their sum.
  8. Implement a Python function that sorts a list of strings lexicographically (alphabetical order).
  9. Write a Python script to find the longest common subsequence between two strings.
  10. Create a Python program that implements the binary search algorithm on a sorted list of numbers.
  11. Write a Python script to find all permutations of a given string using recursion.
  12. Implement a function to check if a given number is prime in Python.
  13. Write a Python script to generate and print the first n terms of an arithmetic progression (AP).
  14. Create a Python program that calculates the sum of all Fibonacci numbers up to a specific point using recursion.
  15. Implement a function to find the smallest multiple of two numbers that is also divisible by their greatest common divisor.

FAQ

  1. Why is Python's syntax so simple?

Python was designed with readability in mind, making it easier for beginners to learn and understand.

  1. What are some popular Python libraries for data science and machine learning?

Some popular libraries include NumPy, Pandas, SciPy, Scikit-learn, TensorFlow, and PyTorch.

  1. How do I install additional Python packages?

You can use the pip package manager to install additional packages. Run pip install package_name in your terminal or command prompt.

  1. What is the difference between lists and tuples in Python?

Lists are mutable, meaning you can change their contents, while tuples are immutable, meaning they cannot be modified once created.

  1. Why does Python have dynamic typing?

Dynamic typing allows for greater flexibility by not requiring variables to have a specific type. However, it can lead to errors if mixed types are used in operations without proper handling.

  1. What is the difference between pass and None in Python?

pass is a placeholder for empty statements or blocks, while None represents the absence of a value.

  1. Why does Python use indentation to define code blocks?

Python uses indentation to determine the structure of code blocks because it makes the code more readable and easier to understand.

  1. What is PEP 8, and why is it important for writing Python code?

PEP 8 is a style guide for Python code that provides recommendations on naming conventions, whitespace usage, and other coding best practices. Adhering to PEP 8 helps maintain consistency in Python codebases and makes it easier for others to read and understand the code.

JS 2021 (Python Programming) | Python | XQA Learn