
Python lets you create variables simply by assigning a value to the variable, without the need to declare the variable upfront. The value assigned to a variable determines the variable type. Different types may support some operations that others don't.
Python lets you create variables simply by assigning a value to the variable, without the need to declare the variable upfront. The value assigned to a variable determines the variable type. Different types may support some operations that others don't.
names can not contain any of these symbols:
:'",<>/?|\!@#%^&*~-+it's considered best practice (PEP8) that names are lowercase with underscores
list and strl (lowercase letter el), O (uppercase letter oh) and I (uppercase letter eye) as they can be confused with 1 and 0Python uses dynamic typing, meaning you can reassign variables to different data types. This makes Python very flexible in assigning data types; it differs from other languages that are statically typed.
my_dogs = 2
my_dogs
my_dogs = ['Sammy', 'Frankie']
my_dogsThe variable assignment follows name = object, where a single equals sign = is an assignment operator
a = 5
aHere we assigned the integer object 5 to the variable name a. Let's assign a to something else:
a = 10
aYou can now use a in place of the number 10:
a + aPython lets you reassign variables with a reference to the same object.
a = a + 10
print(a)There's actually a shortcut for this. Python lets you add, subtract, multiply and divide numbers with reassignment using +=, -=, *=, and /=.
a += 10
print(a)
#############
a *= 2
print(a)You can check what type of object is assigned to a variable using Python's built-in type() function. Common data types include:
a=5
type(a)
a = (1,2)
type(a)This shows how variables make calculations more readable and easier to follow.
my_income = 100
tax_rate = 0.1
my_taxes = my_income * tax_rate
print(my_taxes)You should now understand the basics of variable assignment and reassignment in Python.
Sign in to join the discussion and post comments.
Sign in