Python (Scripting) - Defining variables

by
Jeremy Canfield |
Updated: November 25 2024
| Python (Scripting) articles
Creating variables in Python is incredibly easy.
- var1 contains a string (bar)
- var2 contains a boolean (True)
- var3 contains a integer (123)
- var4 contains a list / array
- var5 contains a dictionary (key:value pairs)
- var6 is null
#!/usr/bin/python3
var1 = "bar"
var2 = True
var3 = 123
var4 = [ "Hello", "World" ]
var5 = { "foo": "Hello", "bar": "World" }
var6 = None
type can be used to validate each type.
print(f"var1 = {type(var1)}")
print(f"var2 = {type(var2)}")
print(f"var3 = {type(var3)}")
print(f"var4 = {type(var4)}")
print(f"var5 = {type(var5)}")
print(f"var6 = {type(var6)}")
The following should be displayed.
var1 = <type 'str'>
var2 = <type 'bool'>
var3 = <type 'int'>
var4 = <type 'list'>
var5 = <type 'dict'>
var6 = <type 'null'>
And you can print the value of each variable. Since var2 - var5 are not strings, str is used to print the value.
print(f"var1 = {var1}")
print(f"var2 = {var2}")
print(f"var3 = {var3}")
print(f"var4 = {var4}")
print(f"var5 = {var5}")
print(f"var6 = {var6}")
Which should print the following.
var1 = bar
var2 = True
var3 = 123
var4 = ['Hello', 'World']
var5 = {'foo': 'Hello', 'bar': 'World'}
var6 = None
And here is now you would convert a string to an integer.
#!/usr/bin/python3
var = "123"
var = int(var)
And here is now you would convert an integer to a string.
#!/usr/bin/python3
var = 123
var = str(var)
Let's say you define var1 inside of a function.
#!/usr/bin/python3
def Hello():
var1 = "Hello World"
Hello()
print(f"var1 = {var1}")
Running this script will return the following because the var1 variable is local to the Hello function.
NameError: name 'var1' is not defined
You can use global so that the var1 is global to the entire script.
#!/usr/bin/python3
def Hello():
global var1
var1 = "Hello World"
Hello()
print(f"var1 = {var1}")
The following can be done to undefine variables.
#!/usr/bin/python3
var1 = None
var2 = None
var3 = None
var4 = None
var5 = None
var6 = None
Did you find this article helpful?
If so, consider buying me a coffee over at