Variables and Data Types
What is a Variable?¶
In Python, a variable is a symbolic name that acts as a reference or pointer to an object. Once you assign an object to a variable, you can refer to that object by its name throughout your script.
For example, if we want to store the number of households in a barangay:
num_households = 120Now, num_households holds the value 120. We can use this name in calculations.
num_householdsOutput
120Naming Rules¶
When naming variables for the Census or surveys, follow these strict rules:
Start with a letter or underscore:
_farm_idorfarm_id(Valid).2nd_farm(Invalid).Letters, numbers, underscores only: No spaces or special symbols like
$,@, or-.Case-sensitive:
Crop_Typeandcrop_typeare different variables.Descriptive is better: Use
total_productioninstead oft.Avoid Keywords: Don’t use Python reserved words like
print,list,str,int,if, orelse.
Data Types¶
Python supports various data types.
| Type | Description | Example |
|---|---|---|
Integer (int) | Whole numbers | num_carabaos = 15 |
Float (float) | Decimal numbers | land_area_ha = 2.5 |
String (str) | Text sequences | crop_variety = "RC-216" |
Boolean (bool) | True or False values | is_irrigated = True |
| List | Ordered collection of items | provinces = ["Cavite", "Bohol"] |
Dictionary (dict) | Key-value pairs | farm_stats = {"yield": 4.5, "type": "Rainfed"} |
Note on Strings: You can use single quotes (') or double quotes ("). To include a special character like a new line, use \n.
Non-code text¶
Comments¶
Comments start with #. Python ignores them. se them to explain your thought process or clarify complex logic.
# This is a comment. It will be ignored when running the code.Docstrings¶
Docstrings are used to document functions, classes, modules, and methods. They are enclosed in triple quotes (“”") and provide detailed explanations of what the code does, its parameters, return values, and usage examples.
def calculate_yield(area, avg_yield_per_ha):
"""
Calculate total crop yield based on area and average yield per hectare.
Parameters:
area (float): The area in hectares.
avg_yield_per_ha (float): Average yield per hectare.
Returns:
float: Total yield.
Example:
>>> calculate_yield(2.5, 4.5)
11.25
"""
return area * avg_yield_per_ha You can access docstrings using help(function_name) or function_name.__doc__
What does the function below show?
help(calculate_yield)Output
Help on function calculate_yield in module __main__:
calculate_yield(area, avg_yield_per_ha)
Calculate total crop yield based on area and average yield per hectare.
Parameters:
area (float): The area in hectares.
avg_yield_per_ha (float): Average yield per hectare.
Returns:
float: Total yield.
Example:
>>> calculate_yield(2.5, 4.5)
11.25
Escape Characters¶
Escape characters are used to insert characters that are illegal in a string such as new lines, tabs, or quotes.
You can insert a new line using \n.
print("Kumusta\nMundo!")Output
Kumusta
Mundo!
You can insert a tab using \t.
print("Kumusta\n\tMundo!")Output
Kumusta
Mundo!
You can add a single quote ' by wrapping the string in double quotes " or using the \ escape character.
print("Mundo'y magiging ikaw.")Output
Mundo'y magiging ikaw.
print('Mundo\'y magiging ikaw.')Output
Mundo'y magiging ikaw.
Scope¶
Variable scope¶
refers to the region of a program where a variable can be accessed or modified
crucial for preventing naming conflicts and managing data effectively
Global and local scope¶
Global scope
variables declared outside of any function have a global scope
can be accessed from any part of the program
uses ALLCAPS naming by convention
Local scope
variables declared inside a function have a local scope
are only accessible within that function
# example of global scope variable
X = 100
def print_x():
print(X)
print_x()Output
100
def print_x():
x = 50 #variable only accessible inside of the print_x function
print(x)
print_x()Output
50
When a global and local variable share the same name¶
the local variable takes precedence
What value is printed in the code snippet below?
x = 100 # Global variable
def print_x():
x = 50 # Local variable with the same name
print(x)
print_x()Output
50
Scope hierarchy¶
variables in an inner scope can access variables in an outer scope, but not vice versa
What values are printed in the code snippet below?
X = 100 # Global variable
def outer_function():
y = 50 # Outer function's variable
def inner_function():
z = 10 # Inner function's variable
print(X, y, z)
inner_function()
outer_function()Output
100 50 10