×
By the end of this chapter, you should be able to:
Declaring and assigning a variable in Python is quite easy; just use =
to assign a value to a name. If you want to indicate an absence of value, you can assign a variable to the value None
.
a = 1 b = "YOLO" nothing = None
In Python you can also do multiple assignment with variables separated by a comma. This is quite common with Python so make sure to try this out. Here's a basic example:
a, b = 1, 2 a # 1 b # 2
Valid:
_cats = "meow" abc123 = 1970
Invalid:
2cats = 1 # SyntaxError hey@you = 1 # SyntaxError
lower_snake_case
. This means that all words should be lowercase, and words should be separated by an underscore.CAPITAL_SNAKE_CASE
usually refers to constantsmyVariable = 3 # Get outta here, this isn't JavaScript! my_variable = 3 # much better AVOGADRO_CONSTANT = 6.022140857 * 10 ** 23 # https://en.wikipedia.org/wiki/Avogadro_constant __no_touchy__ = 3 # someone doesn't want you to mess with this!
As we mentioned in the last chapter, Python has quite a few built in data types, including:
True
or False
values aka Boolean valuesWe can see the type of an object using the built in type
function.
type(False) # bool type("nice") # str type({}) # dict type([]) # list type(()) # tuple type(None) # NoneType
Note that Python has no concept of "primitives" like other languages such as JavaScript. In JS, strings and numbers are primitive types while arrays and objects are composite types, for example. In Python, all data types are objects. We'll revisit this when we talk about Python OOP.
Python is highly flexible about assigning and reassigning variables to any type at any time:
awesomeness = None awesomeness = 33.5 awesomeness = True
We call this dynamic typing, since variables can change types readily. By contrast, C/C++ are statically-typed languages, which mean the variables are typed when they are declared:
int x = 5; x = false; // COMPILE-TIME ERROR
However, Python is NOT weakly or "loosely"-typed; it is a strongly-typed language. That means that while variables can be dynamically reassigned to different types, you cannot implicitly convert variables between types like this:
x = 3 y = " cats" x + y # TypeError !!!!
This is a contrast from JavaScript, which is weakly-typed:
var x = 3; var y = " cats"; x + y; // 3 cats
We call this weak typing, because JavaScript implictly converts x into a string without yelling at you. It assumes you want to convert the value, whereas you have to do that explicitly in a strongly-typed language such as Python:
x = 3 y = " cats" str(x) + y # 3 cats
In conclusion, Python is a dynamically-typed and strongly-typed language.
When you're ready, move on to Strings