AllTechnologyProgrammingWeb DevelopmentAI
    CODING IS POWERFUL!
    Back to Blog

    Python Basics

    20 min read
    January 21, 2025
    Python Basics

    Why Learn Python?

    Python has emerged as one of the most popular programming languages in recent years, and for good reason. Its simplicity and versatility make it an excellent choice for beginners and seasoned developers alike. Here's a deep dive into why you should consider learning Python:

    Ease of Learning

    One of Python's most significant advantages is its readability. The syntax is clean and straightforward, resembling plain English, which makes it easier to understand and write code. This low learning curve allows beginners to grasp programming fundamentals quickly and start building projects sooner.

    Versatility and Wide Range of Applications

    Python is a highly versatile language used in numerous fields. Some of the key areas where Python shines include:

    • Web Development: Python frameworks like Django and Flask are used to build robust and scalable web applications.
    • Data Science and Analysis: Libraries like Pandas, NumPy, and Matplotlib make Python the go-to language for data manipulation, analysis, and visualization.
    • Machine Learning and AI: Python is at the forefront of machine learning and AI, with powerful libraries like TensorFlow and PyTorch.
    • Automation and Scripting: Python's scripting capabilities make it perfect for automating repetitive tasks, saving time and resources.
    • Game Development: While not its primary strength, Python is used for creating simple games using libraries like Pygame.

    This wide range of applications ensures that you will be able to leverage your Python knowledge in many different domains, making it a valuable skill to acquire.

    Large and Supportive Community

    Python has a massive and active community of developers. This means you will find a plethora of resources, tutorials, libraries, and frameworks to help you learn and solve problems. If you encounter any difficulties, you are likely to find answers on forums or community pages. The community’s support is invaluable for both beginners and experienced developers.

    Abundance of Libraries and Frameworks

    Python's extensive library ecosystem is a key reason for its popularity. Libraries like NumPy for numerical computation, Pandas for data manipulation, Scikit-learn for machine learning, and TensorFlow and PyTorch for deep learning make complex tasks much simpler. These libraries significantly reduce development time, enabling you to achieve more with less code. Frameworks like Django and Flask help build robust web applications quickly and efficiently.

    High Demand in the Job Market

    Given Python’s versatility and popularity, there is a high demand for Python developers in the job market. Learning Python can open doors to many different career opportunities in web development, data science, machine learning, and more. This makes Python an excellent investment for your future.

    Conclusion

    Learning Python is an excellent investment of your time and effort. Its ease of learning, versatility, and wide applicability make it a valuable skill in today’s tech-driven world. Whether you are a beginner or a seasoned developer, Python is a language worth mastering.

    Setting Up Python

    Embarking on your Python journey begins with setting up your environment. This crucial first step ensures you have everything you need to write, run, and experiment with Python code. Let's walk through the process of installing Python on your system.

    Choosing Your Python Version

    Before diving into the installation, it's important to choose the right Python version. Generally, you have two main options: Python 3 and Python 2. Python 2 reached its end-of-life and is no longer supported, so it's strongly advised to use Python 3 for all new projects. Python 3 has seen many improvements, new features, and is actively maintained. So, for the purpose of this guide, we are going to focus on setting up Python 3.

    Installation Steps

    On Windows

    • Visit the official Python website: python.org.
    • Go to the "Downloads" section and select the latest version of Python 3 for Windows.
    • Run the installer. Make sure to check the "Add Python to PATH" option during the installation process.
    • After installation, open the command prompt (cmd) and type python --version to check if Python is installed correctly. You should see the python version printed on the terminal.

    On macOS

    • Python is usually pre-installed on macOS, but it's often an older version. Therefore it's better to install the latest version. Visit python.org.
    • Go to the "Downloads" section and select the latest version of Python 3 for macOS.
    • Run the installer and follow the on-screen instructions.
    • Open your terminal and type python3 --version or python --version to verify that Python 3 is successfully installed. (The alias python might point to a pre-installed version). You should see the python version printed on the terminal.

    On Linux

    • Python is often pre-installed on most Linux distributions. But just in case if it's not, install it using the command below.
    • Open your terminal and based on the distribution run one of the following commands:
      sudo apt update (for Debian/Ubuntu) and then sudo apt install python3
      OR
      sudo yum update (for CentOS/Fedora) and then sudo yum install python3
      OR
      sudo pacman -Syu (for Arch/Manjaro) and then sudo pacman -S python
    • To verify installation run python3 --version or python --version. You should see the python version printed on the terminal.

    Text Editor or IDE

    While you can write Python code in any basic text editor like Notepad, using a code editor or an Integrated Development Environment (IDE) greatly enhances your coding experience. Some recommended options include:

    • VS Code (Visual Studio Code): A free, lightweight code editor with a wide array of extensions for Python development.
    • PyCharm: A dedicated IDE by JetBrains specifically designed for Python, offering a robust set of features.
    • Sublime Text: A popular code editor that's fast, flexible, and supports Python development through plugins.
    • Atom: A highly customizable editor developed by GitHub with Python support via packages.

    Conclusion

    Congratulations! You have successfully set up Python on your system. With Python and your chosen text editor or IDE ready, you're all set to begin your Python programming journey. In the next sections, we will write your first Python code!

    Your First Python Code

    Let's dive into the exciting world of Python programming. This section will guide you through writing and executing your very first lines of Python code. It's a fundamental step towards building amazing applications.

    The Print Statement

    The print() function is a cornerstone of Python. It allows you to display information, such as text and numbers, on your console. Let's try it out.

    Hello, World!

    The traditional first program in any language is often "Hello, World!". In Python, it's incredibly simple:

            
                print("Hello, World!")
            
        

    This single line of code tells Python to display the text "Hello, World!" on the screen.

    Running Your Code

    To run this, you'll need to:

    • Open a text editor and paste the code into it.
    • Save the file with a .py extension (e.g., hello.py).
    • Open your terminal or command prompt.
    • Navigate to the directory where you saved the file.
    • Type python hello.py and press Enter.
    You should then see "Hello, World!" printed in your terminal.

    Printing Numbers

    You can also use print() to display numbers:

            
                print(42)
            
        

    This code will print the number 42 to the console.

    Printing Multiple Items

    You can print multiple items by separating them with commas within the print() function.

            
                print("The answer is", 42)
            
        

    This will output: The answer is 42

    Congratulations! You've written and executed your first Python code. Keep exploring, and you'll soon be creating much more complex programs.

    Variables in Python

    In Python, a variable is a symbolic name that refers to a memory location where a value is stored. Think of it as a container that holds data. Variables are fundamental to programming as they allow us to store and manipulate information within our code.

    Variable Naming Rules

    Python has specific rules for naming variables:

    • Variable names must start with a letter (a-z, A-Z) or an underscore (_).
    • The rest of the variable name can consist of letters, numbers (0-9), and underscores.
    • Variable names are case-sensitive (e.g., myVariable and myvariable are different).
    • You cannot use Python keywords (e.g., if, else, for, while) as variable names.

    Creating Variables

    Creating a variable in Python is straightforward. You use the assignment operator (=) to assign a value to a variable. Python is dynamically typed, which means you don't need to explicitly declare the data type of a variable; it's inferred automatically based on the value you assign.

            
    age = 30
    name = "Alice"
    height = 5.8
    is_student = True
            
        

    In the above example:

    • age is an integer variable.
    • name is a string variable.
    • height is a float variable.
    • is_student is a boolean variable.

    Reassigning Variables

    The value of a variable can be changed at any point in your code by assigning it a new value. For example:

                
    count = 10
    print(count) # Output: 10
    count = 20
    print(count) # Output: 20
                
            

    Variable Scope

    The scope of a variable refers to the part of the program where that variable is accessible. Python has different scopes like local, global, and non-local, which you'll learn more about later.

    Best Practices

    • Choose descriptive variable names that clearly indicate the purpose of the variable.
    • Use lowercase with words separated by underscores for variable names (e.g., user_name instead of userName or UserName). This is called snake_case and is the convention in Python.

    Understanding variables is crucial for writing effective and clean code. They enable you to store and manage data, making your programs dynamic and flexible.

    Data Types

    In Python, data types are classifications that specify the type of value a variable can hold. Understanding data types is crucial for writing correct and efficient code. Python is a dynamically typed language, meaning you don't have to explicitly declare the data type of a variable; the interpreter infers it based on the assigned value.

    Common Data Types

    • Numeric Types: These represent numerical values.
      • int: Represents integer numbers (e.g., 10, -5, 0).
      • float: Represents floating-point numbers (e.g., 3.14, -2.5, 0.0).
      • complex: Represents complex numbers (e.g., 2+3j).
    • String Type: Represents a sequence of characters.
      • str: Used to store text (e.g., "hello", 'Python').
    • Boolean Type: Represents logical values.
      • bool: Can have two values: True or False.
    • Sequence Types: Represent ordered collections of items.
      • list: An ordered, mutable (changeable) collection of items (e.g., [1, 2, "apple"]).
      • tuple: An ordered, immutable (unchangeable) collection of items (e.g., (1, 2, "apple")).
      • range: Represents a sequence of numbers, often used for looping (e.g., range(5)).
    • Set Types: Represent unordered collections of unique items.
      • set: An unordered collection of unique elements (e.g., {1, 2, 3}).
      • frozenset: An immutable version of a set.
    • Mapping Type: Represents key-value pairs.
      • dict: A collection of key-value pairs where keys are unique (e.g., {"name": "Alice", "age": 30}).
    • Binary Types: Represent sequences of bytes.
      • bytes: Immutable sequences of single bytes (e.g., b"hello").
      • bytearray: Mutable sequences of single bytes.
      • memoryview: Allows direct access to the memory of objects.
    • None Type:
      • NoneType: Represents the absence of a value (None).

    Checking Data Types

    You can use the type() function to check the data type of a variable:

    
    x = 10
    print(type(x))  # Output: 
    y = 3.14
    print(type(y))  # Output: 
    z = "hello"
    print(type(z))  # Output: 
    

    Type Conversion

    Sometimes you need to convert a value from one data type to another. This is called type casting. Python provides built-in functions for this:

    • int(): Converts to an integer.
    • float(): Converts to a float.
    • str(): Converts to a string.
    • list(): Converts to a list.
    • tuple(): Converts to a tuple.
    • set(): Converts to a set.
    • dict(): Converts to a dictionary.
    
    num_str = "123"
    num_int = int(num_str) # Converts string "123" to integer 123
    print(num_int, type(num_int))
    num_float = float(num_str)
    print(num_float, type(num_float))
    list_t = list("abc") # string abc to list ['a','b','c']
    print(list_t, type(list_t))
    

    Understanding and using appropriate data types is essential for writing robust and efficient Python programs. Be mindful of the type of data you are working with, and perform type conversions when needed.

    Basic Operators

    In Python, operators are special symbols that perform operations on values and variables. They are fundamental to any programming language as they allow us to manipulate data, perform calculations, and make comparisons. Let's delve into the basic operators available in Python:

    Arithmetic Operators

    These operators are used to perform mathematical calculations. Here are the main arithmetic operators:

    • Addition (+): Adds two values. For example, 5 + 3 results in 8.
    • Subtraction (-): Subtracts one value from another. For example, 7 - 2 results in 5.
    • Multiplication (*): Multiplies two values. For example, 4 * 6 results in 24.
    • Division (/): Divides one value by another. For example, 10 / 2 results in 5.0. (Note that the result is always a float).
    • Floor Division (//): Divides one value by another and returns the floor value (i.e., the integer part of the division). For example, 10 // 3 results in 3.
    • Modulo (%): Returns the remainder of a division. For example, 10 % 3 results in 1.
    • Exponentiation (**): Raises a value to the power of another. For example, 2 ** 3 results in 8.

    Assignment Operators

    Assignment operators are used to assign values to variables. The most common one is the equals sign =. Here are some combined assignment operators which perform an operation and an assignment at the same time:

    • =: Assigns a value to a variable. Example: x = 5.
    • +=: Adds a value to the variable and assigns the result. Example: x += 5 is equivalent to x = x + 5.
    • -=: Subtracts a value from the variable and assigns the result. Example: x -= 3 is equivalent to x = x - 3.
    • *=: Multiplies a value with the variable and assigns the result. Example: x *= 2 is equivalent to x = x * 2.
    • /=: Divides the variable by a value and assigns the result. Example: x /= 4 is equivalent to x = x / 4.
    • //=: Performs floor division on the variable by a value and assigns the result. Example: x //= 3 is equivalent to x = x // 3.
    • %=: Performs modulo on the variable by a value and assigns the result. Example: x %= 2 is equivalent to x = x % 2.
    • **=: Raises the variable to the power of a value and assigns the result. Example: x **= 3 is equivalent to x = x ** 3.

    Comparison Operators

    These operators are used to compare values. They always return a boolean value True or False.

    • Equal to (==): Returns True if two values are equal. For example, 5 == 5 results in True.
    • Not equal to (!=): Returns True if two values are not equal. For example, 5 != 3 results in True.
    • Greater than (>): Returns True if the left value is greater than the right value. For example, 8 > 4 results in True.
    • Less than (<): Returns True if the left value is less than the right value. For example, 2 < 6 results in True.
    • Greater than or equal to (>=): Returns True if the left value is greater than or equal to the right value. For example, 5 >= 5 results in True.
    • Less than or equal to (<=): Returns True if the left value is less than or equal to the right value. For example, 3 <= 7 results in True.

    Logical Operators

    These operators are used to combine or modify boolean expressions.

    • and: Returns True if both operands are True.
    • or: Returns True if at least one operand is True.
    • not: Returns True if the operand is False, and vice versa.

    Bitwise Operators

    Bitwise operators perform operations on the binary representation of integers.

    • Bitwise AND (&): Performs a bitwise AND operation.
    • Bitwise OR (|): Performs a bitwise OR operation.
    • Bitwise XOR (^): Performs a bitwise XOR (exclusive OR) operation.
    • Bitwise NOT (~): Performs a bitwise NOT (inversion) operation.
    • Left shift (<<): Shifts bits to the left.
    • Right shift (>>): Shifts bits to the right.

    Membership Operators

    These operators are used to test if a sequence is present in an object.

    • in: Returns True if a sequence is found in the object.
    • not in: Returns True if a sequence is not found in the object.

    Identity Operators

    These operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.

    • is: Returns True if both operands are the same object.
    • is not: Returns True if both operands are not the same object.

    Understanding these basic operators is crucial for writing effective Python code. As you progress, you'll use these to create dynamic and interactive applications.

    Control Flow

    Control flow is a fundamental concept in programming that dictates the order in which statements are executed. It allows you to create dynamic and complex programs that can react to different inputs and conditions. In Python, control flow is achieved using various keywords and constructs. Let's delve into some of these.

    Conditional Statements

    Conditional statements are used to execute code blocks based on whether a condition is true or false. The most common conditional statement is the if statement. Here’s how it works:

    
    if condition:
        # Code to execute if condition is true
    

    You can extend this using the elif (else if) keyword, and an optional else block:

    
    if condition1:
        # Code to execute if condition1 is true
    elif condition2:
        # Code to execute if condition2 is true
    else:
        # Code to execute if no condition above is true
    

    Looping Constructs

    Loops are used to repeat a block of code multiple times. Python offers two primary types of loops: for and while loops.

    For Loop

    The for loop is used to iterate over a sequence (like a list, tuple, string or range). Here's its basic structure:

    
    for item in sequence:
        # Code to execute for each item in the sequence
    

    While Loop

    The while loop executes a block of code as long as a specified condition is true:

    
    while condition:
        # Code to execute while condition is true
    

    Loop Control Statements

    Within loops, you can use special statements to modify the looping process:

    • break: Terminates the loop immediately.
    • continue: Skips the current iteration and moves to the next.

    The pass Statement

    The pass statement is a null operation, which is often used as a placeholder where syntactically some code is required, but logically you want no action. It’s very helpful when you're developing your code, and want to leave certain places empty.

    
    if condition:
      pass  # do nothing
    else:
      #Some code
    

    Example

    Let's put it all together in a simple example, suppose, we want to loop through a list of numbers, and print if the number is even or odd.

    
    numbers = [1, 2, 3, 4, 5]
    for num in numbers:
        if num % 2 == 0:
            print(f"{num} is even")
        else:
            print(f"{num} is odd")
    
    

    In this example, we use a for loop to iterate over the numbers list, check if each number is even or odd using an if-else condition, and then print the result.

    Join Our Newsletter

    Launching soon - be among our first 500 subscribers!

    Suggested Posts

    AI - The New Frontier for the Human Mind
    AI

    AI - The New Frontier for the Human Mind

    AI's growing presence raises critical questions about its profound effects on human psychology and cognition. 🧠
    36 min read
    8/9/2025
    Read More
    AI's Unseen Influence - Reshaping the Human Mind
    AI

    AI's Unseen Influence - Reshaping the Human Mind

    AI's unseen influence: Experts warn on mental health, cognition, and critical thinking impacts.
    26 min read
    8/9/2025
    Read More
    AI's Psychological Impact - A Growing Concern
    AI

    AI's Psychological Impact - A Growing Concern

    AI's psychological impact raises alarms: risks to mental health & critical thinking. More research needed. 🧠
    20 min read
    8/9/2025
    Read More
    Developer X

    Muhammad Areeb (Developer X)

    Quick Links

    PortfolioBlog

    Get in Touch

    [email protected]+92 312 5362908

    Crafting digital experiences through code and creativity. Building the future of web, one pixel at a time.

    © 2025 Developer X. All rights reserved.