You are currently viewing Variables in Python : Everything you should clearly know as a beginner.

Variables in Python : Everything you should clearly know as a beginner.

  • Post author:
  • Post category:Python

What are variables?

Variables are the most basic building block of a program. A program usually contains instructions to tell the computer what to do, as well as data that is used by the program. With help of variables, you can label data with descriptive names and store information in computer programs that can be referenced and manipulated.

Assigning value to variable

To assign a value to a variable, you use the = symbol. You put the variable name on the left and the value you want to store in the variable on the right. Variable names can be short (like x and y) or descriptive (like age, FIRST_NAME, lastname)

x = 5

Rules for naming variables

1) Must start with a letter or the underscore character

2) Cannot start with a number

3) Should only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

4) Variable names are case-sensitive (name, Name and NAME are three different variables)

5) The reserved words(keywords) cannot be used naming the variable

x = 5
_x_ = 3
my_09 = 4.5

In Python, you do not need to declare variables before using them, or declare their type. A variable is created the moment you first assign a value to it.

x = 4
name ="theshecoder"
price = 2.4

We can also assign the same value to several variables simultaneously.

x = y = z = 5

Types of Variables

Number

In programming whole numbers like 1, and 2, and 3 are called integers, or an int.

We also have decimal numbers that are called floats. So 1.5, that’s a float

Then, we have complex numbers that have real parts and imaginary parts. 

my_number = 7 # int
my_float = 7.0 # float
my_complex = 7j # complex

Boolean

Boolean data type returns only two possible values that is True or False. It is used to check whether an expression is True or False.

a=5
b=7
print(a>b) # False
print(b>a) # True

String

Strings are sequences of characters. For example, "coder" is a string containing sequence of characters 'c', 'o', 'd', 'e' and 'r'. We use single quotes or double quotes to represent a string in Python.

my_string = "hello"
string2 = "I am the she coder"

Sequence

There are two types of sequential data type :-

List

Lists are used to store multiple items in a single variable. Lists are created using square brackets. We can store different data types in a list. List items are ordered, changeable, and allow duplicate values. Indexing start from 0 to n-1.

my_list =  ["name", 3.4, False, 55, "age", "name"]

Tuple

Tuples are similar to Lists i.e. they store multiple items of different data types in a single variable. Tuples are created using round brackets. Tuple items are ordered, unchangeable, and allow duplicate values. Indexing start from 0 to n-1.

my_tuple =  ("name", 3.4, False, 55, "age", "name")

Set

Sets store multiple items of different data types in a single variable. They are unordered, unchangeable, unindexed, and do not allow duplicate values. Once a set is created, you cannot change its items, but you can remove items and add new items. Sets are created using curly brackets.

my_set =  {"name", 3.4, False, 55}

Mapping

Dictionaries store data values in key: value pairs. They are ordered (after Python 3.6), changeable and do not allow duplicates. Dictionaries are created using curly brackets.

my_dict = {
  "name": "Grace",
  "age": 20,
  "food": "Tuna"
}

Type Conversion and Type Casting

Now, python performs type conversion to directly convert one data type to another.

There are two types of Type Conversion in Python:

1) Implicit Type Conversion or Type Conversion of variables

2) Explicit Type Conversion or Type Casting of variables

In Implicit Type Conversion data types are automatically converted by the Python interpreter without any user interaction. In the examples given below, the float value is not being converted into an integer because python by default converts data into a wider-sized data type without any loss of information.

print(20/4) #gives 5.0
print(5+4.0) #gives 10.0
print(4*4.0) # gives 16.0
print(2**2.0) # gives 4.0

In Explicit Type Conversion the data type is converted manually by the user as per requirement. In explicit type conversion, there is a risk of data loss since we are forcing an expression to be changed in some specific data type. In below examples, when you cast from a float to an int, Python does not round for you. To round it off we need to use the round() function. 

print(int(20/4)) #gives 5
print(float(2)) # gives 2.0
print(int(8.999)) #gives 8
print(round(8.999)) # gives 9

Global and Local Variables

Local variables are the ones that are defined and declared inside a function. They can not be called outside the function.

def f():
    x = 5
    print(x)

f() 

Global variables are the types of variables that are declared outside of every function of the program and can be accessed by all the functions. To access the global variable, we use the global keyword.

x = 5

def f():
    global x
    print(x)

f()