Python Variables
Python variables are symbolic names that represent stored values in a program.
- serve as placeholders to store and manage data
- can be numbers, strings, lists, etc.
- don’t need to explicitly declare a variable’s data type
- it is dynamically inferred based on the assigned value
- variable names are case sensitive
Creating a Variable
- Python variables are not declared
- they are created as soon as they are assigned a value
- do not have a set type
- can change their type
- variables are case sensitive
x = 42
x = "Cisco South Router"Variable Name Rules
- Variable names can only contain letters, numbers, or an underscore.
- Variable names must start with either a letter or underscore.
- Variable names cannot start with a number.
- Variable names cannot contain special characters.
- Variable names cannot be a Python keyword (opens new tab).
Variables with Multiple Names
- use Camel case for variable names
chicagoFirewall = "192.168.26.254"
losAngelesFirewall = "192.168.28.254"- can also use Pascal case or snake case
Multiple Variables
- can assign values to multiple values in a single line
- e.g.,
x, y, z = "router", "switch", "firewall"
- e.g.,
- can assign the same value to multiple variables in a single line
- e.g.,
switch1 = switch2 = switch3 = "Juniper"
- e.g.,
Unpacking Collections
Unpacking involves extracting elements from iterable objects like lists or tuples and assigning them to individual variables.
ip_addresses = ["172.20.200.10", "172.20.200.11", "172.20.200.12"]
ip1, ip2, ip3 = ip_addressesOutput Variables
- output variables with
print()function- can output multiple variables:
print(a, b, c) - concatenate them with
+:print(a + b + c)- using different typed variables will result in error
- can output multiple variables:
Variable Scope
Variable scope in Python refers to the region of code where a variable can be accessed.
- Local scope is within a specific function
- Global scope extends throughout the entire program
- Variables defined within a function (local) are not accessible outside
global Keyword
- can create a global variable inside a function with
global- can also be used to change a global variable within a function
def routerAddress():
global ip1
ip1 = "10.10.100.250"
routerAddress()
print("The router address is " + ip1)