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:
- 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_name,total_price).
name = "Amr" # A string variable
age = 30 # An integer variable
height = 1.82 # A float variable
is_student = True # A boolean variable
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:
- 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.
PI = 3.14159
MAX_USERS = 100
Reassignment and Dynamic Typing
Python allows variables to change their type when reassigned.
- Example:
- This flexibility is powerful, but it can also introduce errors if not used carefully. It’s best to use clear naming and consistent types.
x = 10 # Initially an integer
x = "Python" # Now reassigned as a string
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:
- Integers can be positive, negative, or zero.
- Python can handle very large integers automatically without overflow, unlike many other languages.
age = 25
temperature = -5
year = 2025
Floats (`float`)
Floats represent numbers with decimal points (also known as floating-point numbers).
- Example:
- 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.
pi = 3.14159
weight = 72.5
Strings (`str`)
Strings are sequences of characters, used for working with text.
- Strings are written inside single or double quotes:
name = "Amr"
greeting = 'Hello, World!'
- Strings support many operations, such as concatenation (
+), repetition (*), and indexing:
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:
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:
- This is useful when reading input (which is always a string) or performing operations requiring specific types.
# 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
Taking Input
The input() function lets you get input from the user.
- Example:
- By default,
input()returns a string, so you often need type conversion for numbers:
name = input("Enter your name: ")
print("Hello,", name)
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:
print("Welcome to Python!")
- You can print multiple values at once:
print("Name:", name, "Age:", age)
- Python also supports formatted strings for cleaner output:
print(f"Hello {name}, you are {age} years old.")
This makes output more readable and professional.