CODE: Python Variables and Data Types

In programming, variables are like containers that store data values. They allow us to work with information by giving it a name, making the code easier to read and reuse. Python also supports constants, which are values meant to stay unchanged throughout the program.

Understanding how to use variables and constants is one of the first steps toward writing meaningful Python programs.

Variables in Python

A variable is created by assigning a value to a name using the = operator.

  • Python does not require you to declare the type of a variable explicitly—its type is determined automatically based on the value assigned.
  • Example:
  • python
    name = "Amr"       # A string variable
    age = 30           # An integer variable
    height = 1.82      # A float variable
    is_student = True  # A boolean variable

  • Variables can hold different types of data at different times, since Python is dynamically typed.
  • The name of a variable should be descriptive, following good practices such as snake_case (e.g., user_nametotal_price).

Constants in Python

Python does not have built-in syntax for constants like some languages, but developers use naming conventions to indicate that a value should not be changed.

  • A constant is usually written in uppercase letters with underscores:
  • python
    PI = 3.14159
    MAX_USERS = 100

  • Although nothing prevents changing these values, treating them as constants is a good practice for clarity and maintainability.
  • Constants are especially useful for values that have a universal meaning in your program, like mathematical constants or configuration limits.

Reassignment and Dynamic Typing

Python allows variables to change their type when reassigned.

  • Example:
  • python
    x = 10        # Initially an integer
    x = "Python"  # Now reassigned as a string

  • This flexibility is powerful, but it can also introduce errors if not used carefully. It’s best to use clear naming and consistent types.

Data Types in Python (Integers, Floats, Strings, Booleans)

In Python, every value has a data type that defines what kind of information it represents and how it can be used. Unlike some languages where you must declare types explicitly, Python determines the type automatically. Understanding these basic data types is essential, as they form the foundation of all Python programs.


Integers (`int`)

Integers represent whole numbers without a fractional part.

  • Example:
  • python
    age = 25
    temperature = -5
    year = 2025

  • Integers can be positive, negative, or zero.
  • Python can handle very large integers automatically without overflow, unlike many other languages.

Floats (`float`)

Floats represent numbers with decimal points (also known as floating-point numbers).

  • Example:
  • python
    pi = 3.14159
    weight = 72.5

  • Floats are used in calculations that require precision, like measurements or scientific computations.
  • Be aware of rounding errors, since floats are stored in binary and may not always represent decimals exactly.

Strings (`str`)

Strings are sequences of characters, used for working with text.

  • Strings are written inside single or double quotes:
  • python
    name = "Amr"
    greeting = 'Hello, World!'

  • Strings support many operations, such as concatenation (+), repetition (*), and indexing:
  • python
    print(name[0])   # Output: A
    print(name[:2])  # Output: Am

  • They also come with powerful built-in methods like .upper().lower().replace(), and .split().

Booleans (`bool`)

Booleans represent truth values: True or False.

  • They are often the result of comparisons or logical operations:
  • python
    is_student = True
    is_adult = age >= 18   # Evaluates to True if age is 18 or more

  • Booleans are crucial in controlling program flow with conditions and loops.

Type Conversion and Input/Output

Programs often need to take input from users, display results, and sometimes convert data from one type to another. In Python, these operations are simple and flexible. Mastering type conversion and input/output (I/O) is essential for building interactive programs.


Type Conversion

Type conversion allows you to change a value from one data type to another. Python provides built-in functions for this.

  • Common conversions:
  • python
    # Converting to integer
    x = int("10")     # "10" (string) → 10 (int)
    
    # Converting to float
    y = float("3.14") # "3.14" (string) → 3.14 (float)
    
    # Converting to string
    z = str(100)      # 100 (int) → "100" (string)
    
    # Converting to boolean
    flag = bool(1)    # 1 → True

  • This is useful when reading input (which is always a string) or performing operations requiring specific types.

Taking Input

The input() function lets you get input from the user.

  • Example:
  • python
    name = input("Enter your name: ")
    print("Hello,", name)

  • By default, input() returns a string, so you often need type conversion for numbers:

python
age = int(input("Enter your age: "))
print("Next year, you will be", age + 1)

This makes programs interactive and user-driven.


Displaying Output

Python uses the print() function to display output.

  • Example:
  • python
    print("Welcome to Python!")

  • You can print multiple values at once:
  • python
    print("Name:", name, "Age:", age)

  • Python also supports formatted strings for cleaner output:
  • python
    print(f"Hello {name}, you are {age} years old.")

This makes output more readable and professional.