Variables & Data Types contains an exhaustive information about these concepts, this guide provides a Python specific reference.
One of the most basic things to do in a Python program is to declare a variable and set it equal to a value of some data type. We’ll talk more about data types later.
num_of_students = 10 # integer
student_name = "James" # string
test_score = 5.4 # float
working_status = True # boolean
Variables can store a number of different types of data in Python.
num_of_students = 10 # declare variable of type integer
print(type(num_of_students)) # prints <class 'int'>
student_name = "James" # declare variable of type string
print(type(student_name)) # prints <class 'str'>
test_score = 5.4 # declare variable of type string
print(type(test_score)) # prints <class 'float'>
working_status = True # declare variable of type boolean
print(type(working_status)) # prints <class 'bool'>
Python is a dynamically typed language, meaning that the data/variable type is determined at run time. This also means that Python allows us to change the type of data assigned to a variable.
x = 1
print(type(x)) # prints <class 'int'>
x = "Hello World"
print(type(x)) # prints <class 'str'>
In general, this can get us into trouble when pass our variables and data through to different operations or functions that require specific types of data. Try executing the following code:
x = input("x: ") # prompt user for keyboard input
y = x + 1 # throws error because x is a string
The following program will cause an error (or exception) in Python. Why is this?
+
is a mathematical operator that can only perform addition on integers or float data types.
input()
is a Python function that outputs the string of characters entered by the user on the keyboard, in this case it was stored in a variable x
.
Simply put, it does not make sense to add a string with an integer and so Python complains that we are trying to do something nonsensical in the program.
To fix this problem, we can perform a type conversion to convert the string to an integer.
In Python, we can convert data from one type to another using the type casting operators.
x = input("x: ") # prompt user for keyboard input
print(type(x)) # prints <class 'str'>
x = int(x) # convert x to an integer
print(type(x)) # prints <class 'int'>
y = x + 1 # add 1 to x and assign the result to y
<aside> 🔥 Let’s refactor our code into a more efficient statement.
</aside>
x = int(input("x: ")
y = x + 1