Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Python Variables

1. Understanding Variables

Variables serve as named memory locations within a program where temporary data is stored. In Python, variables reside in the computer’s temporary memory (RAM) and are created dynamically upon assignment.

– A variable is a symbolic name assigned to a memory location, acting as the basic storage unit in a program.

2. Rules for Variable Naming

To maintain consistency and clarity, certain rules govern variable naming in Python:

– Variable names must commence with a letter or an underscore.
– They cannot begin with a number.
– Variable names may consist of alphanumeric characters and underscores (A-z, 0-9, _).
– Python is case-sensitive, distinguishing between uppercase and lowercase characters.
– Reserved words or keywords cannot be used as variable names.

3. Creating Variables

Python does not require explicit declarations for variables. They are instantiated at the moment of assignment.

Example:

“`python
# Variable declarations
x = 123
y = “African Students”
z = 10.234

# Print variables
print(x)
print(y)
print(z)
“`

Output:
123
African Students
10.234

4. Assigning Values to Multiple Variables

Assigning a single value to multiple variables or assigning different values to multiple variables is straightforward in Python.

Example:

“`python
# Assigning a single value to multiple variables
a = b = c = 10

print(a)
print(b)
print(c)
“`

Output:
10
10
10

Example:

“`python
# Assigning different values to multiple variables
a, b, c = 1, 20.2, “African Students”

print(a)
print(b)
print(c)

“`

Output:
1
20.2
African Students

5. Python – Output Variables

In Python, you can output variables using the `print()` function. This function takes one or more arguments, which can be variables, strings, or expressions, and prints them to the standard output (usually the console).

Here’s how you can output variables in Python:

“`python
# Define variables
x = 10
y = “Hello, world!”
z = 3.14

# Output variables using the print() function
print(“The value of x is:”, x)
print(“The value of y is:”, y)
print(“The value of z is:”, z)
“`

Output:
“`
The value of x is: 10
The value of y is: Hello, world!
The value of z is: 3.14
“`

In the example above, we define three variables `x`, `y`, and `z` with different data types (integer, string, and float). We then use the `print()` function to output the values of these variables along with descriptive messages.

You can also concatenate variables and strings within the `print()` function to customize the output further:

“`python
# Output variables with customized messages
print(“The value of x is ” + str(x))
print(“The value of y is ‘” + y + “‘”)
print(“The value of z is ” + str(z))
“`

Output:
“`
The value of x is 10
The value of y is ‘Hello, world!’
The value of z is 3.14
“`

Here, we convert non-string variables to strings using the `str()` function before concatenating them with strings.

In Python 3.6 and later versions, you can also use f-strings (formatted string literals) for more concise and readable output:

“`python
# Output variables using f-strings
print(f”The value of x is {x}”)
print(f”The value of y is ‘{y}'”)
print(f”The value of z is {z}”)
“`

Output:
“`
The value of x is 10
The value of y is ‘Hello, world!’
The value of z is 3.14
“`

f-strings allow you to embed expressions and variables directly within strings by prefixing them with the `f` character. This provides a convenient way to format output with variables in Python.

6. Determining Data Types of a variable

The `type()` function in Python allows us to discern the data type of a variable.

Example:

“`python
x = 100
y = “Africa”
z = 10.234

print(type(x))
print(type(y))
print(type(z))
“`

Output:
<class ‘int’>
<class ‘str’>
<class ‘float’>

6. Global and Local Variables

Variables declared inside a function possess local scope, while those outside have global scope. Local variables are accessible only within the function where they are defined, while global variables can be accessed throughout the program.

Example:

“`python
x = 100 # Global variable

def func():
y = 200 # Local variable
print(x + y)

func()
“`

Output:
300

Here’s another illustration of how you may define and use global variables in Python:

“`python
# Define a global variable
global_var = 10

# Define a function that uses the global variable
def func():
# Access the global variable within the function
print(“Inside the function:”, global_var)

# Call the function
func()

# Modify the global variable
global_var = 20

# Print the modified global variable
print(“Outside the function:”, global_var)
“`

Output:
“`
Inside the function: 10
Outside the function: 20
“`

In the example above, `global_var` is a global variable defined outside of any function. The `func()` function accesses the global variable and prints its value. Later, we modify the global variable outside of the function, and its modified value is printed outside of the function.

However, if you want to modify a global variable inside a function, you need to use the `global` keyword to indicate that the variable is global. Otherwise, Python will treat it as a local variable within the function’s scope:

“`python
# Define a global variable
global_var = 10

# Define a function that modifies the global variable
def modify_global():
# Use the global keyword to indicate that global_var is a global variable
global global_var
global_var = 30

# Call the function to modify the global variable
modify_global()

# Print the modified global variable
print(“Modified global variable:”, global_var)
“`

Output:
“`
Modified global variable: 30
“`

In this example, the `modify_global()` function modifies the value of the global variable `global_var` using the `global` keyword. As a result, the modified value of `global_var` is printed outside of the function.

It’s important to use global variables judiciously, as they can make the code less modular and harder to maintain. In many cases, it’s preferable to pass variables as arguments to functions rather than relying on global variables.

7. Deleting Variables

Python allows the deletion of variables using the `del` command.

Example:

“`python
a = 123
print(a) # Output: 123

del a
print(a) # Error: NameError: name ‘a’ is not defined
“`

EXERCISES

1. Circle Area Calculator:
Write a program that prompts the user to input the radius of a circle. Calculate the area of the circle using the formula ( pi times r^2 ) and store it in a variable. Print the result.

2. Quadratic Equation Solver:
Create a program that solves a quadratic equation of the form ax2+bx+c=0ax2+bx+c=0. Prompt the user to input the values of coefficients aa, bb, and cc. Store these values in variables, calculate the roots of the equation using the quadratic formula, and print the solutions.

3. BMI Calculator:
Create a program that calculates the Body Mass Index (BMI) of a person. Prompt the user to enter their weight in kilograms and height in meters. Store these values in variables, calculate the BMI using the formula BMI=weightheight2BMI=height2weight​, and print the result.

Join the conversation