Variables in Python
Definition
- A variable is a container for a value.
- Each variable should have a unique name.
Data Types
There are four basic data types discussed:
- Strings
- Integers
- Floats
- Booleans
1. Strings
- A string is a series of text which can be enclosed in double or single quotes. (Preference: double quotes)
- Example of a string variable:
first_name
.
- To assign a variable: use the assignment operator (
=
).
- Print a string variable using a print statement without quotes.
- Use f-strings for formatted output:
- Syntax:
f"{variable}"
- Example:
print(f"Hello, {first_name}")
2. Integers
- An integer is a whole number.
- Example: A person's age (e.g.,
age = 25
).
- Print an integer variable without quotes:
- Example:
print(f"You are {age} years old.")
- Integers can be used in arithmetic expressions.
3. Floats
- A float is a floating point number that includes a decimal portion.
- Example: Price (e.g.,
price = 10.99
).
- Print a float variable:
- Example:
print(f"The price is ${price}")
- Other examples include GPA (e.g.,
gpa = 3.2
) and distance (e.g., distance = 5.5
).
4. Booleans
- A boolean is either True or False.
- Example:
is_student = True
.
- Booleans are often used within if statements.
Examples of Booleans
is_for_sale
- checks if an item is for sale.
is_online
- checks if someone is online.
Conclusion
- Variables are a reusable container for a value.
- Four basic data types: Strings, Integers, Floats, and Booleans.
Assignment
- Post four variables in the comments section:
- A string
- An integer
- A float
- A boolean
- Aim for unique examples.