A Python variable is a reserved memory location to store values. In other words, a variable in a Python program gives data to the computer for processing.
Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc. Variables can be declared by any name or even alphabets like a, aa, abc, etc. For example let’s declare variable "a" and print it:
a = "Hello World!" print (a)
This example will print out "Hello World!" to the console. You can also redeclare a variable.
a = "Hello!" print (a) a = "GoodBye!" print (a)
This example will print out "Hello!" to the console then on a new line it will print "GoodBye!". Since Python uses dynamically typed variables you can change the type of data that you are saving in that variable:
a = "Hello!" print (a) a = 100 print (a)
This example will print out "Hello!" to the console then on a new line it will print 100. In python you can also concatenate variables, though this depends heavily on the datatype of each variable. For example:
this will add the variables together
a = 1 b = 99 print(a + b)
concatenate a string and a number
a = "Hello!" b = 123 print(a + str(b))
concatenate two strings
a = "Hello!" b = "Goodbye!" print(a + b)
As we see in this example, we have to cast the number in the second print() to a string otherwise we would get a type error.
In Python there are also local and global variables. In the example code below we print() variable a then run a function that sets a to "Goodbye!" and prints it then prints a again.
a = "Hello!" print(a)
def someFunction(): a = "Goodbye!" print(a)
someFunction() print(a)
WIth this code the output we get will be:
Hello! Goodbye! Hello!
This is due to creating a global variable a set to "Hello!" and a local variable in someFunction() also called a that is set to "Goodbye!". In order to modify the global variable a inside of someFunction() you need to use the global keyword:
a = "Hello!" print(a)
def someFunction(): global a = "Goodbye!" print(a)
someFunction() print(a)
WIth this code the output we get will be:
Hello! Goodbye! Goodbye!
You can also delete a variable using the command de:
del
Leave a comment