Python Variables and Assignments
Learn about the different variables assignments and data types in Python. Explore Debugger and understand nature of variables.
Python Variables: From APIs to Database Storage (with JavaScript Connections)
Welcome! In this lesson, you’ll learn about Python variables and assignments, building on your experience with JavaScript. We’ll compare how both languages handle variables, data types, and objects, so you can transfer your coding skills and spot similarities and differences.
Lesson Goal:
- Understand how Python variables and assignments work, and how they compare to JavaScript.
- Work with and understand how to initialize and assign data to Python objects, just like you did with JavaScript objects.
- See how Python’s approach to variables, types, and objects is similar to and different from JavaScript.
Why connect JavaScript and Python? If you already know JavaScript, learning Python is easier when you see the parallels. Both languages use variables, data types, and objects, but the syntax and some behaviors are different. This lesson will help you bridge your knowledge and become a more versatile programmer.
Primitive and Reference Data Types: Python vs JavaScript
Just like JavaScript, Python has two main categories of data types: primitive types (which store simple values directly) and reference types (which store references to more complex data).
Primitive Data Types
In JavaScript: You learned about Number
, String
, Boolean
, Undefined
, Null
, Symbol
, and BigInt
as primitive types.
In Python: The most common primitive types are:
int
(integer numbers, like42
)float
(decimal numbers, like3.14
)str
(strings, like'hello'
)bool
(Boolean values:True
orFalse
)NoneType
(the special valueNone
, similar to JavaScript’snull
)
Python does not have undefined
, symbol
, or bigint
types, but the core idea is the same: these types hold simple, single values.
Reference Data Types
In JavaScript: You used Object
, Array
, and Function
as reference types. These store references (links) to more complex data structures.
In Python: The most common reference types are:
list
(like JavaScript arrays:[1, 2, 3]
)dict
(like JavaScript objects:{'name': 'Mario', 'score': 0}
)set
(a collection of unique values:{'apple', 'banana'}
)function
(functions are also objects in Python)
When you assign a reference type in Python, you are assigning a reference (a link) to the object, not a copy of the object—just like in JavaScript.
Why does this matter? Understanding the difference between primitive and reference types helps you predict how variables behave when you assign, copy, or modify them. This is a key skill for debugging and writing reliable code in both Python and JavaScript.
# Python Variables and Assignments Example
# --- Primitive Types ---
user_id = 101 # int: unique user ID
user_name = 'Alice' # str: user name
user_email = 'alice@example.com' # str: user email
is_active = True # bool: is the user active?
last_login = None # NoneType: no login yet
print('user_id:', user_id, '| type:', type(user_id))
print('user_name:', user_name, '| type:', type(user_name))
print('user_email:', user_email, '| type:', type(user_email))
print('is_active:', is_active, '| type:', type(is_active))
print('last_login:', last_login, '| type:', type(last_login))
# --- Reference Types ---
user_profile = { # dict: user profile as a dictionary
'id': user_id,
'name': user_name,
'email': user_email,
'active': is_active,
'scores': [0.91, 0.87, 0.76, 0.55, 0.92], # reference to a list of float: user scores
'roles': ['student', 'scrummer'], # reference to a list of str: user roles
'last_login': last_login
} # dict: user profile as a dictionary
print('user_profile:', user_profile, '| type:', type(user_profile))
# list: login history (empty to start)
login_history = []
print('login_history:', login_history, '| type:', type(login_history))
# set: unique permissions
permissions = set(['read', 'write', 'delete'])
print('permissions:', permissions, '| type:', type(permissions))
# function: a simple function to greet the user
def greet(user):
print(f"Hello, {user['name']}!")
print('greet:', greet, '| type:', type(greet))
greet(user_profile)
Hack: Python Dictionary
Why?
Defining user properties is key to most computer systems. Think about something you would want to track in a user profile (for example, a user’s favorite color, login count, or last activity).
Task:
Peform Key-Value Homework Hack
Python Classes and Objects
Classes
To better define users, you can create a class and instantiate multiple objects (instances) from it. This is how the User
class can work with API or database code:
# Define a User class to represent a user profile
# __init__ is the constructor; self refers to the instance
class User:
# Constructor to initialize user properties in the object
def __init__(self, user_id, name, email, active, scores, roles, last_login):
self.id = user_id
self.name = name
self.email = email
self.active = active
self.scores = scores
self.roles = roles
self.last_login = last_login
# String representation of the User object
def __repr__(self):
return (f'User(id={self.id}, name={self.name}, email={self.email}, active={self.active}, '
f'scores={self.scores}, roles={self.roles}, last_login={self.last_login})')
Make an Object
alice = User(101, 'Alice', 'alice@example.com', True, [0.91, 0.87, 0.76, 0.55, 0.92], ['student', 'scrummer'], None)
Dot Notation
You use dot notation to access or change properties and methods of an object:
object.property
to get or set a value
print(alice)
pring(alice.name)
Hack: Python Dictionary
Why?
Defining user properties is key to most computer systems. Think about something you would want to track in a user profile (for example, a user’s favorite color, login count, or last activity).
Task:
Peform Add-Dictionary Homework
'''
# --- Object Type ---
# Define a User class to encapsulate user data and behavior
'''
class User:
# Constructor to initialize user properties in the object
def __init__(self, user_id, name, email, active, scores, roles, last_login):
self.id = user_id
self.name = name
self.email = email
self.active = active
self.scores = scores
self.roles = roles
self.last_login = last_login
# String representation of the User object
def __repr__(self):
return (
f'User(id={self.id}, name={self.name}, email={self.email}, active={self.active}, ' f'scores={self.scores}, roles={self.roles}, last_login={self.last_login})'
)
def add_score(self, score):
self.scores.append(score)
def average_score(self):
return sum(self.scores) / len(self.scores) if self.scores else 0
alice = User(101, 'Alice', 'alice@example.com', True, [0.91, 0.87, 0.76, 0.55, 0.92], ['student', 'scrummer'], None)
john = User(102, 'John', 'john@example.com', True, [0.85, 0.80, 0.78, 0.90, 0.88], ['student'], None)
print(alice)
print(alice.name, round(alice.average_score(), 2), alice.scores)
alice.name = 'Alice Smith'
alice.add_score(0.95)
print(alice.name, round(alice.average_score(), 2), alice.scores)
print(john)
print(john.name, round(john.average_score(), 2), john.scores)
User(id=101, name=Alice, email=alice@example.com, active=True, scores=[0.91, 0.87, 0.76, 0.55, 0.92], roles=['student', 'scrummer'], last_login=None)
Alice 0.8 [0.91, 0.87, 0.76, 0.55, 0.92]
Alice Smith 0.83 [0.91, 0.87, 0.76, 0.55, 0.92, 0.95]
User(id=102, name=John, email=john@example.com, active=True, scores=[0.85, 0.8, 0.78, 0.9, 0.88], roles=['student'], last_login=None)
John 0.84 [0.85, 0.8, 0.78, 0.9, 0.88]
Hack: Python Class
Why?
Working with Python classes is key to keeping related data and actions together. In real-world applications, information collected from users (on the frontend) is often stored in backend objects created from classes. This helps organize your code and makes it easier to manage user data and behaviors.
Task:
Peform Add-Behavior Homework