DEV Community

Ahmed Gouda
Ahmed Gouda

Posted on • Edited on • Originally published at ahmedgouda.hashnode.dev

Python Variables and Expressions

Variables and Expressions

Declare a Variable

# Declare a variable and initialize it
v = 1
print(v)
Enter fullscreen mode Exit fullscreen mode

Output: 1         (Integer)

Re-declare a Variable

# Declare a variable and initialize it
v = 1
print(v)

# re-declaring the variable works
v = "abc"
print(v)
Enter fullscreen mode Exit fullscreen mode

Output: abc         (String)

So even if the variable has already been declared you can simply redeclare it and that works.

Concatenate Different Types

# ERROR: variables of different types cannot be combined
print( "abc" + 1 )
Enter fullscreen mode Exit fullscreen mode

Output: error        TypeError: can only concatenate str (not "int") to str

This is happening because Python is a strongly typed language even though you don't have to declare the type of a variable before you use it. What's happening is when Python goes to execute the code it infers a specific type for a value or a variable. You can't go back and change the type or combine it with other types.

Global and Local Variables

# Global vs. local variables in functions
Variable = "ABC"

#Define Some Function
def Function():
    Variable = "XYZ"
    print(Variable)
#End of Function

Function()
print(Variable)
Enter fullscreen mode Exit fullscreen mode

Output:

XYZ
ABC
Enter fullscreen mode Exit fullscreen mode

The reason is because inside the function the function gets it own local copy of whatever variables you declare inside the function. So the two variables even if they have the same name are considered two separate variables by the Python interpreter.

Using global
# Global vs. local variables in functions
Variable = "ABC"

#Define Some Function
def Function():
    global Variable
    Variable = "XYZ"
    print(Variable)
#End of Function

Function()
print(Variable)
Enter fullscreen mode Exit fullscreen mode

Output:

XYZ
XYZ
Enter fullscreen mode Exit fullscreen mode

The function here is now operating on the global variable. Since we told the function that Variable is now global this assignment Variable = "Local" affects the Variable that's outside the function.

Delete Variable Definition

# Global vs. local variables in functions
Variable = "ABC"

#Define Some Function
def Function():
    global Variable
    Variable = "XYZ"
    print(Variable)
#End of Function

Function()
print(Variable)

#Delete Variable Definition
del Variable
print(Variable)
Enter fullscreen mode Exit fullscreen mode

Output:

XYZ
XYZ
NameError: name 'Variable' is not defined
Enter fullscreen mode Exit fullscreen mode

So essentially what this means is that you can undefine variables in real time by using the del statement.

Top comments (0)