Variables and Naming Conventions
What is a Variable?
A variable is a name that stores a value. Think of it as a labeled box where you can put data and use it later in your code.
x = 5
name = “Alice”
is_logged_in = True
- You use the = symbol (assignment operator) to assign a value to a variable.
- Variables do not need a type declaration. Python figures it out automatically.
Why Use Variables?
- To store user input
- To reuse values without repeating them
- To make your code more readable and maintainable
Examples:
age = 25
greeting = “Hello”
pi = 3.14159
is_admin = False
You can also reassign values:
age = 30
Valid Variable Names
- Must start with a letter (a–z, A–Z) or underscore (_)
- Can include letters, digits (0–9), and underscores
- Case-sensitive (age and Age are different)
my_name = “Sarah”
_age = 20
score2 = 99
Invalid Variable Names
2cool = “nope” # starts with a number
user-name = “error” # contains a dash
class = “reserved” # ‘class’ is a keyword
Best Practices (PEP8 Guidelines)
Element | Style | Example |
---|---|---|
Variable names | snake_case | user_name , score_total |
Constants | ALL_CAPS | MAX_USERS = 10 |
Avoid single letters | Unless in loops | Prefer count over c |
Descriptive is better | Be clear | email_address > e |
Avoid These Mistakes
- Don’t name variables after built-in functions like list, str, input
input = “Hello” # Bad: overrides built-in input() function
- Don’t use spaces or special characters
user name = “Bob” # invalid
Python Keywords (Can’t be Variable Names)
Here are a few reserved keywords you can’t use as variable names:
False, True, None, if, else, elif, for, while, class, def, try, except, with, return, import, as, pass, break, continue, and, or, not, in, is
Quick Exercise:
Which of these are valid variable names?
1. user_age = 20
2. $salary = 50000
3. full name = “Amy”
4. _secret = “shhh”
5. def = “define”
Answers: 1 and 4 are valid.
Data types: int, float, str, bool
Python is a dynamically typed language, meaning you don’t need to specify the data type — Python figures it out automatically.
You can use the type() function to check the data type of any value or variable.
x = 10
print(type(x)) # <class ‘int’>
Integer (int)
- Whole numbers (positive or negative) without decimals
- Unlimited size (up to your machine’s memory)
age = 30
year = 2025
temperature = -5
type(age) # <class ‘int’>
You can do math with integers:
a = 10
b = 3
print(a + b) # 13
print(a – b) # 7
print(a * b) # 30
print(a // b) # 3 (floor division)
print(a % b) # 1 (modulus)
print(a ** b) # 1000 (exponent)
Float (float)
- Numbers with decimal points
- Used for measurements, precise calculations, etc.
pi = 3.14159
weight = 65.5
gpa = 3.75
type(pi) # <class ‘float’>
Be careful with floating point precision:
print(0.1 + 0.2) # 0.30000000000000004
You can convert between int and float:
int(3.9) # 3
float(4) # 4.0
String (str)
- Text values wrapped in quotes
- Can use single ‘, double “, or triple “”” for multiline
name = “Alice”
greeting = ‘Hello’
quote = “””Python is fun!”””
type(name) # <class ‘str’>
String operations:
full_name = “John” + ” ” + “Doe” # Concatenation
print(len(full_name)) # Length of the string
print(name.upper()) # “ALICE”
print(name.lower()) # “alice”
print(name[0]) # “A”
You can use f-strings for formatting:
age = 25
print(f”My age is {age}”)
Boolean (bool)
- Only two values: True or False (capitalized)
- Used for conditions and logic
is_active = True
is_admin = False
type(is_active) # <class ‘bool’>
Booleans often come from comparisons:
print(5 > 3) # True
print(10 == 5) # False
Used in if statements:
logged_in = True
if logged_in:
print(“Welcome!”)
else:
print(“Please log in.”)
Type Conversion Summary:
Function | Converts to | Example |
---|---|---|
int() |
Integer | int("10") → 10 |
float() |
Float | float("3.14") → 3.14 |
str() |
String | str(123) → "123" |
bool() |
Boolean | bool(0) → False |
Empty values like 0, 0.0, “”, None, and [] are all considered False.
Type casting and input()
What is Type Casting?
Type casting means converting one data type into another — for example, changing a string into an integer.
Python has built-in functions to do this:
Function | Converts to | Example |
---|---|---|
int() |
Integer | int("10") → 10 |
float() |
Float | float("3.14") → 3.14 |
str() |
String | str(100) → "100" |
bool() |
Boolean | bool("hi") → True |
Examples of Type Casting:
x = “25”
y = int(x) # y becomes 25 (an int)
print(x, type(x)) # ’25’ <class ‘str’>
print(y, type(y)) # 25 <class ‘int’>
pi = “3.14”
print(float(pi)) # 3.14
number = 99
print(str(number)) # ’99’
input() Function
What is input()?
The input() function asks the user for input from the keyboard and always returns a string.
name = input(“What is your name? “)
print(“Hello, ” + name)
Even if the user enters numbers, Python treats them as strings:
age = input(“Enter your age: “)
print(age, type(age)) # ’25’ <class ‘str’>
Using input() with Type Casting
To use the input as a number, you must cast it manually:
# Get input and cast to int
age = int(input(“Enter your age: “))
print(age + 5) # Adds 5 to age
# Get input and cast to float
height = float(input(“Enter your height in meters: “))
print(“Your height + 0.1m =”, height + 0.1)
Be careful! If the user enters non-numeric text when casting to int() or float(), it will cause an error.
Pro Tip: Add Input Validation (Optional Advanced)
age_input = input(“Enter your age: “)
if age_input.isdigit():
age = int(age_input)
print(f”You will be {age + 1} next year.”)
else:
print(“Please enter a valid number.”)
Summary:
Concept | Example |
---|---|
String input | name = input("Name? ") |
Integer input | age = int(input("Age? ")) |
Float input | price = float(input("Price? ")) |
Cast to string | str(123) → "123" |
Cast to boolean | bool("hello") → True |
Arithmetic, comparison, and logical operators
1. Arithmetic Operators
Used for mathematical operations.
Operator | Description | Example | Result |
---|---|---|---|
+ |
Addition | 5 + 2 |
7 |
- |
Subtraction | 5 - 2 |
3 |
* |
Multiplication | 5 * 2 |
10 |
/ |
Division | 5 / 2 |
2.5 |
// |
Floor Division | 5 // 2 |
2 |
% |
Modulus (remainder) | 5 % 2 |
1 |
** |
Exponentiation | 5 ** 2 |
25 |
Examples:
a = 10
b = 3
print(a + b) # 13
print(a – b) # 7
print(a * b) # 30
print(a / b) # 3.333…
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 1000
2. Comparison Operators
Used to compare values, returning a boolean result (True or False).
Operator | Description | Example | Result |
---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
> |
Greater than | 5 > 3 |
True |
< |
Less than | 3 < 5 |
True |
>= |
Greater or equal | 5 >= 5 |
True |
<= |
Less or equal | 3 <= 5 |
True |
Examples:
x = 10
y = 20
print(x == y) # False
print(x != y) # True
print(x < y) # True
print(x >= 10) # True
These are often used in if statements to control program flow.
3. Logical Operators
Used to combine multiple conditions.
Operator | Description | Example | Result |
---|---|---|---|
and |
True if both are True | True and True |
True |
or |
True if at least one is True | True or False |
True |
not |
Inverts the condition | not True |
False |
Examples:
x = 5
y = 10
print(x > 0 and y > 0) # True
print(x < 0 or y > 0) # True
print(not(x == 5)) # False
Example with All Three:
age = int(input(“Enter your age: “))
if age >= 18 and age < 65:
print(“You are an adult.”)
elif age >= 65:
print(“You are a senior.”)
else:
print(“You are a minor.”)
Summary:
Arithmetic
+ – * / // % **
Comparison:
== != > < >= <=
Logical:
and or not
Would you like:
- Practice problems with solutions?
- A mini quiz or interactive worksheet?
- Visual charts/infographics for these?