Bootstrap FreeKB - Python (Scripting) - Defining variables
Python (Scripting) - Defining variables

Updated:   |  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 dictionary (key:value pairs)
  • var5 is null
#!/usr/bin/python3
var1 = "bar"
var2 = True
var3 = 123
var4 = { "foo": "Hello", "bar": "World" }
var5 = 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)}")

 

The following should be displayed.

var1 = <type 'str'>
var2 = <type 'bool'>
var3 = <type 'int'>
var4 = <type 'dict'>
var5 = <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}")

 

Which should print the following.

var1 = bar
var2 = True
var3 = 123
var4 = {'foo': 'Hello', 'bar': 'World'}
var5 = 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

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter f9b0bf in the box below so that we can be sure you are a human.