Python Variables

Python Variables

Python Variables: Variables are containers for storing data values.

What exactly is a python?

Creating Variables

Python does not have a command for declaring variables. When you first assign a value to a variable, it is created.

For Example:

x = 10
y = "Techcoders"
print(x)
print(y)

Output

10
Techcoders

Python variables do not require to be declared with a specific type, and they can even change the type after being set.

For Example:

x = 10     # x is of type int
x = "Techcoders" # x is now of type str
print(x)

Output

Techcoders

Casting

If you want to define the data type of a variable, then it can be done with casting.

For Example:

x = str(5)
y = int(5)
z = float(5)
print(x)
print(y)
print(z)

Output

5
5
5.0

Get The Type of a variable

With the type() function, you can get the data type of a variable.

For Example:

x = 10
y = "Techcoders"
print(type(x))
print(type(y))

Output

<class 'int'>
<class 'str'>

Single or Double Quotes

String variables can be declared using single or double quotes.

For Example:

x = "Techcoders"
print(x)
#double quotes are the same as single quotes:
x = 'Techcoders'
print(x)

Output

Techcoders
Techcoders

Case-Sensitive

Variable names are case-sensitive. Python is a case-sensitive programming language, which means that uppercase and lowercase characters are treated differently. This also applies to identifiers. When naming identifiers, you should avoid using the same name in different cases. It is always better to choose names that are easy to remember.

For Example:

This will create two variables.

a = 10
A = "Techcoders"
print(a)
print(A)
#A will not overwrite a

Output

4
Techcoders

Python Variable Names

A variable can have a small name such as x and y or a more defined name such as age, carname, total_volume, etc. Here are some rules for Python variables.

  • Variable names must begin with a letter or an underscore character.
  • The variable names can not begin with a number
  • Variable names can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age, and AGE are three different variables)
  • Variable names can not be any of the Python keywords.

Here are legal Python variable names.

For Example:

myvar = "Techcoders"
my_var = "Techcoders"
_my_var = "Techcoders"
myVar = "Techcoders"
MYVAR = "Techcoders"
myvar2 = "Techcoders"

print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)

Output

Techcoders
Techcoders
Techcoders
Techcoders
Techcoders
Techcoders

Here are illegal Python variable names.

For Example:

2myvar = "Techcoders"
my-var = "Techcoders"
my var = "Techcoders"

Output

Traceback (most recent call last):
  File "/usr/lib/python3.8/py_compile.py", line 144, in compile
    code = loader.source_to_code(source_bytes, dfile or file,
  File "<frozen importlib._bootstrap_external>", line 846, in source_to_code
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./prog.py", line 1
    2myvar = "Techcoders" 
     ^
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.8/py_compile.py", line 150, in compile
    raise py_exc
py_compile.PyCompileError:   File "./prog.py", line 1
    2myvar = "Techcoders"
     ^
SyntaxError: invalid syntax

Keep in mind that variable names are case-sensitive.

Multi Words Variable Names

Variable names that contain more than one word can be difficult to read. There are several methods you can use to improve their readability.

Camel Case

In the Camel Case, each word except the first word begins with a capital letter.

myVariableName = "Techcoders"

Pascal Case

In Pascal Case, each word starts with a capital letter.

MyVariableName = "Techcoders"

Snake Case

In the Snake Case, each word is separated by an underscore character.

my_variable_name = "Techcoders"

Python Variables – Assign Multiple Values

In Python, you can assign values to multiple variables in a single line.

For Example:

x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Output

Orange
Banana
Cherry

Note: If the number of variables does not match the number of values, an error will occur.

One Value to Multiple Variables

You can assign the same value to multiple variables on the same line.

For Example:

x = y = z = "Orange"
print(x)
print(y)
print(z)

Output

Orange
Orange
Orange

Unpack a Collection

If you have a set of values in the form of a list, tuple, etc., Python allows you to extract the values into variables. This is known as unpacking.

For Example:

Unpack a list:

fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)

Output

apple
banana
cherry

Python – Output Variables

To output variables, the Python print() method is frequently used.

For Example:

x = "Python is awesome"
print(x)

Output

Python is awesome

You output multiple variables separated by a comma in the print() function:

For Example:

x = "Python"
y = "is"
z = "awesome"
print(x, y, z)

Output

Python is awesome

You can also output multiple variables using the + operator:

For Example:

x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

Output

Python is awesome

Keep note: without the space character following “Python” and “is,” the output would be “Pythonisawesome”.

The + character functions as a mathematical operator for numbers:

For Example:

x = 5
y = 10
print(x + y)

Output

15

When you use the + operator to combine a string and a number in the print() method, Python gives you the following error:

For Example:

x = 5
y = "Techcoders"
print(x + y)

Output

TypeError: unsupported operand type(s) for +: 'int' and 'str'

To output multiple variables in the print() method, use commas to separate them, which also supports different data types.

For Example:

x = 5
y = "Techcoders"
print(x, y)

Output

5
Techcoders

Python – Global Variables

Global variables are variables that are created outside of a function (as in all of the examples above). Everyone can use global variables, both inside and outside of functions.

Now, create a variable outside a function and use it inside it.

For Example:

x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()

Output

Python is awesome

Note that if you want to create a variable with the same name within a function, this variable will be local, and can only be used within the function itself. But, the same-named global variable will remain global and with its original value.

Now, create a variable within a function with the same name as the global variable.

For Example:

x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)

Output

Python is fantastic
Python is awesome

The global Keyword

Typically, when you create a variable within a function, that variable is local, and can only be used within that function. But, if you want to create a global variable within the function, you can use the global keyword. Thus, if you are using the global keyword, the variable belongs to the global class.

For Example:

def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

Output

Python is fantastic

Additionally, use the global keyword if you want to change a global variable within a function.

If you want to change the value of a variable within a function, you must refer to the variable using the global keyword.

For Example:

x = "perfect"
def myfunc():
global x
x = "perfect"
myfunc()
print("Python is " + x)

Output

Python is perfect

1 thought on “Python Variables”

  1. Pingback: Python Numbers - Techcoders

Comments are closed.

Scroll to Top