Python Variables


Variables store information in your programs, including, text, sentences, numbers, sets of data and everything else. You make variables, assign it a value and then refer to it later as needed. Variables are memory containers for storing data values. Variables are like nouns in language. ouns identify people, things or places. Variables in Python point to values. If we have a variable called Age that contains 29, the variable Age points to a specific location in computer memory that contains the value 29. A variable is a container with a specific name.

Python has no command for declaring a variable. You do not need to declare your variables in Python because a type will be applied to the variable based on what is assigned to it. Data types can change based on the value

How do you assign variables? Use the equals sign. If you want to assign 29 to age, write age = 29. You can assign more than one variable on a line of code. To assign 2 to x, “Bob” to y and 29 to age, type the following: x, y, age = 2, “Bob”, 29. You can assign the number 17 to three variables at one like this: x = y = z = 17.

The print() function is often used to output variables.

Types

Every variable you make has a data type. Python is dynamically typed. What does that mean? The same variable can change type later in the program but it can only have one type at any one time. The types are integer, floating point, complex, string, list tuple, boolean and dictionary.

You can explicitly change a type. Suppose you have age set to 29 in a variable called age. You want to print out the string “Your age is 29”. You can use this code: print(“Your age is ” + str(age)). You will get an error with this code: print(“Your age is ” + age).

Collections

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

y = [1,2,3,4,5]  # create a list
y.append(17)  # appends at the end
print(y)  # [1, 2, 3, 4, 5, 17]
y.pop()  # removes the last element which was 17 in our case
y.remove(2)  # removes the second element
print(y)

Below is code for a dictionary.

thisdict = dict(name = "Bob", age = 36, country = "Canada")
print(thisdict["country"])

Leave a Reply