Python Fundamentals: Variables, Data Types, and Control Flow
Keywords and identifiers are fundamental elements in programming languages used to define variables, functions, and other constructs, with keywords being reserved words that have special meanings, and identifiers being names given to user-defined entities.
Comments in programming serve the essential purpose of making the source code more understandable and maintainable by providing textual annotations that explain the logic, purpose, or any additional information about the code. They help programmers and collaborators to read, debug, and update the code efficiently without affecting its execution.
There are two main types of comments:
- Single-line comments start with specific symbols like // in languages such as C, Java, and JavaScript, and they comment out everything from the symbols to the end of the line. They are used to explain a single line or part of code concisely.
- Multi-line comments begin and end with designated symbol pairs like /* and */ in C-style languages and can span several lines. They are useful for commenting out blocks of code or providing longer explanations.
Comments also serve practical roles such as temporarily disabling code during debugging or development and documenting the rationale behind coding decisions for future reference. Effective comments should be clear, concise, relevant, and kept up to date to maximize their value in collaborative and long-term projects.
Python variables are containers that store data values. In Python, variables do not require explicit declaration before use; a variable is created at the moment a value is assigned to it. This process is called initialization, where you assign an initial value to a variable using the assignment operator (=). For example, `age = 25` creates a variable named `age` and assigns it the integer value 25.
### Declaration, Assignment, and Initialization
- Python variables are created by simply assigning a value to a name. You do not need to declare the variable type explicitly.
- The assignment operator `=` is used to assign values, and Python dynamically determines the variable’s data type based on the value assigned.
- Variables can be initialized right when assigned, like `count = 0` or `price = 49.95`.
- Variables can also be reassigned to different data types later in the program, reflecting Python’s dynamic typing.
### Reading Variables
- Once a variable has been assigned a value, you can read (access) its stored value by simply using its name in expressions or statements.
- For example, if `name = "John"`, printing `print(name)` will output John.
### Variable Naming Restrictions
- Variable names must start with a letter (A-Z, a-z) or an underscore (_), but cannot start with a digit.
- Names can contain letters, digits (0-9), and underscores only. - Variable names are case-sensitive (`age`, `Age`, and `AGE` are different variables). - Spaces are not allowed in variable names; use underscores to separate words instead (e.G., `student_name`). - Variable names cannot be Python reserved keywords (such as `if`, `for`, `while`, `class`, etc.).
### Types of Python Variables
Python variables can hold values of various data types, including:
- Integers (`int`), e.G., `number = 10`
- Floating-point numbers (`float`), e.G., `price = 9.99`
- Strings (`str`), e.G., `name = "Python"`
- Booleans (`bool`), e.G., `flag = True`
- Complex numbers (`complex`)
- Collections: lists, tuples, dictionaries, sets, etc.
Because Python is dynamically typed, a variable can be reassigned from one type to another, such as changing an integer variable to a string later.
☑️ Python Boolean Data Type (bool)
* Definition: A data type that can only hold one of two values: True or False.
* Case-Sensitivity: Note that True and False must start with a capitals letter; they are built-in keywords.
* Usage: Fundamental for control flow (like if statements and while loops) and logical operations.
* Numeric Equivalence: Boolean values are subtypes of integers, where True is evaluated as 1 and False is evaluated as 0 in numeric contexts.
is_sunny = True
is_raining = False
# Example in an operation:
# print(True + 5) # Output: 6 (because True acts as 1)
🐍 Python Data Types Overview
Python is an object-oriented language, and every variable is an object of a specific data type. As a dynamically typed language, Python handles data type declaration implicitly rather than requiring the programmer to declare it explicitly.
🔠 Implicit Declaration of Data Types
In Python, the data type of a variable is determined automatically at runtime based on the value assigned to it. This is known as implicit declaration or dynamic typing.
* No Explicit Type Needed: You don't use keywords like int, str, or bool when creating a variable.
* Type Inference: Python's interpreter infers the correct type from the literal value on the right side of the assignment operator (=).
* Mutability of Type: A variable's type can change if you assign a value of a different type to it later on (though this is often discouraged for code clarity).
| Concept | Python Example | Inferred Type |
|---|---|---|
| Integer Assignment | count = 10 | <class 'int'> |
| String Assignment | message = "Hello" | <class 'str'> |
| Float Assignment | ratio = 3.14 | <class 'float'> |
🔢 Python Numbers
Python supports three distinct numerical types:
1. Integers (int)
* Definition: Whole numbers, positive or negative, without a decimal point.
* Range: Integers in Python 3 have unlimited precision, meaning their size is only limited by the amount of memory available.
x = 100 # Standard integer
y = -50000000 # Large negative integer
2. Floating-Point Numbers (float)
* Definition: Numbers that contain a decimal point. They are used to represent real numbers.
* Precision: Floats are typically represented using IEEE 754 double-precision standard, which gives high precision but is not perfectly infinite (which can sometimes lead to tiny rounding errors).
pi = 3.14159
temperature = 98.6
3. Complex Numbers (complex) * Definition: Numbers written in the form a + bj, where a is the real part and b is the imaginary part, and j (or i in math) is the imaginary unit (\sqrt{-1}).
* Usage: Primarily used in engineering and scientific computing.
c = 5 + 3j
# Accessing parts:
# print(c.Real) # Output: 5.0
# print(c.Imag) # Output: 3.0
📝 Python Strings (str)
* Definition: A sequence of characters (letters, numbers, symbols, spaces). Strings are the fundamental data type for handling text.
* Immutability: Strings are immutable, meaning once created, their content cannot be changed. Any operation that seems to "change" a string actually creates a new string object.
* Declaration: Can be defined using single quotes ('...'), double quotes ("..."), or triple quotes ("""...""" or '''...''') for multi-line strings.
name = "Charlie"
greeting = 'Hello there!'
# Multi-line string
poem = """
Twinkle, twinkle,
little star.
"""
Operators in programming are special symbols used to perform operations on variables and values. Here is an overview of key operators and their precedence:
Arithmetic Operators:
- Used for mathematical calculations such as addition (+), subtraction (-), multiplication (*), division (/), and modulus (%) which gives the remainder.
- Also includes unary operators like unary plus (+) and unary minus (-) that indicate positive or negative values.
- Increment (++) and decrement (--) operators increase or decrease a value by one respectively and are often used in loops.
Comparison or Relational Operators:
- Used to compare two values or expressions.
- Common operators include equal to (==), not equal to (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
- Returns a Boolean value indicating the truth of the comparison.
Logical Operators:
- Combine multiple conditions/expressions.
- Include AND (&&), OR (||), and NOT (!) operators.
- Used to create complex conditional statements by combining multiple Boolean expressions.
Identity Operators:
- Check if two entities are the same object in memory.
- In many languages, identity operators are like `is` and `is not` (e.G., in Python).
- Used to compare if two variables reference the same object rather than just having the same value.
Operators Precedence:
- Determines the order in which parts of an expression are evaluated when multiple operators are present.
- Arithmetic operators follow standard math precedence: parentheses first, then unary operators, multiplication/division/modulus next, and addition/subtraction last.
- Comparison operators are evaluated after arithmetic calculations.
- Logical operators have lower precedence, with NOT having higher priority than AND, which is higher than OR.
- Increment/decrement usually have high precedence close to unary operators.
Python control flow statements allow programs to make decisions and control the execution sequence based on conditions. Here are the key decision-making structures:
Simple If Structure:
- Syntax:
```python
if condition:
# code to execute if condition is True
```
- Executes the block only if the condition is true. If false, it skips the block.
If-Else Structure:
- Syntax:
```python
if condition:
# code if condition is True
else:
# code if condition is False
```
-
Provides two paths: one for when the condition is true and another for when it is false.
If-Elif-Else Structure:
- Syntax:
```python
if condition1:
# code if condition1 is True
elif condition2:
# code if condition2 is True
else:
# code if none of the above conditions are True
```
- Allows multiple conditions to be checked consecutively. The first true condition’s block is executed, and the rest are ignored.
Nested If Structure:
- This involves placing one if statement inside another.
- Syntax:
```python
if condition1:
if condition2:
# code if both condition1 and condition2 are True
```
- Useful for checking multiple dependent conditions in layers.
These structures manage how Python decides which code to run, enabling dynamic behavior in programs based on different scenarios.[1][3][10]
English with a size of 14.36 KB