Python Variables

Variables in Python


  Machine Learning in Python

Summary : Variables are quite simply a placeholder for something. That something could be numbers, strings, booleans or any other object type.

We will explore what a variable can be, how it should be named, how variables should be assigned and how each of the variables types are used

Contents

What is a variable

A variable is quite simply a placeholder for something. Basically, variables can contain Numbers or Strings or Objects. Technically, even numbers and strings are objects, but we will discuss that later.

name = "Ajay Tech"
age  = 2

How do we know if a variable contains a string or a number ? Use the type ( ) function. We will discuss more about functions later – but for now think of them as a blackbox that just gets a task done – In this case, we want to find out if the variable name is an stringor not. For us, it does not matter where the function type ( ) gets this from – we just use it.

type(name)

str
type(age)

int

int means integer. That brings us to the next point. How many types of numbers are there ?

Types of Numbers

There are 3 types of numbers supported in Python.

  • int
  • float
  • complex

For example, the age variable above was an integer. What if you wanted to hold a negative value ? Say a discount of 30$ represented with a negative sign

discount = -30
type(discount)

int

So, integers can hold negative numbers as well. How big can these numbers get ? Can we store the age of the universe ? Thats 13 billion years. Let’s try it.

age_universe = 13000000000

That held ok – Let’s count the age of the universe in seconds. Basically multiply it by 365 days x 24 hours x 60 minutes x 60 seconds.

age_u_seconds = age_universe * 365 * 24 * 60 * 60
print ( age_u_seconds)
409968000000000000

So, basically an integer in Python can hold virtually insanely large numbers. And you can very well do all mathematical operations on them that you would typically do on numbers.

Let’s do a division operation and see what happens. Say, we want to calculate the age of the universe in months,

age_u_months = age_universe / 12 
age_u_months
1083333333.3333333

Now, we have decimals. Can an integer variable in Python hold decimal values ? No it can’t. For that you need a float. Let’s see.

type(age_u_months)
float

See, when we asked python to store the result in the variable _age_umonths, Python has automatically chosen to store the value in a float instead of an int. When people say that Python is a dynamically typed language, this is what they mean – We don’t have to explicitly let Python know what kind of data a variable needs to hold ( Like in C or C++ ). It is automatically decided for us.

Complex numbers are another type of number, that is used typically in scientific computation. For example, to store a complex number 1 + 2j , use

v = 1 + 2j
type(v)

complex

If you don’t understand complex numbers, that’s fine. Most of you might never need them.

Strings

A variable can also hold strings, like we have seen previously.

name = "Ajay Tech"

You can use single quotes or double quotes. Both mean the same thing.

name_s = 'Ajay Tech'
name_d = "Ajay Tech"

type(name_s)

str
type(name_d)
str

We will see in a later section that strings in python have many in-built functions for slicing, stripping etc.

Boolean

Another variable type is Boolean . It just takes 2 values – True or False. It is typically used to hold a function’s return value or the return value of an expression. For example, if a computer has a color monitor or not, use the variable has_color as follows.

has_color = True
type(has_color)
bool

This is not the same as a string “True”

We will explore more on boolean variables when we explore expressions.

Variable naming convention

When creating variables, make sure

  • it starts with a letter ( capital or small ) only
  • it does not contain any special characters ( except an underscore )
  • is NOT a reserved keyword

For example, the following are not valid variables.

_age
_age = 10
print ( _age)
10

Well, it works OK, but there is a specific meaning that python gives to a variable that starts with an underscore ( private variable ) and to understand it, we need to go into object oriented Python. For now, just remember that having an underscore at the beginning of the variable makes it special – use it only when you understand it. For all other casese, just don’t use underscore as the first letter.

  • 1_age
1_age = 2
 File "<ipython-input-27-957b2d800c96>", line 1
    1_age = 2
     ^
SyntaxError: invalid token

Having a number as the first letter is not a valid variable name. Python throws a Syntax error as shown above. How about these variables ?

  • name#
  • name#first
  • name@first
name# = "Ajay Tech"

'Ajay Tech'

Well, this works because, we have already declared a name variable and everything after the has( # ) is a comment. More on this later.

name@first = "Ajay Tech"
File "<ipython-input-30-97a3570cc45d>", line 1
    name@first = "Ajay Tech"
                            ^
SyntaxError: can't assign to operator

So, no special characters in the variable name.

Also, you cannot use reserved words for variable names, like name a variable as for

for = 1

File "<ipython-input-33-b26be1b49601>", line 1
    for = 1
        ^
SyntaxError: invalid syntax

How would you know all the reserved words ? Well, over time you would know them anyway. However, if you want the list, you can get them as below. You don’t have to memorize them though.

import keyword

print ( keyword.kwlist)

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Multiple Assignments

Sometimes it is convenient to assign multiple variables at the same time. A simple example would be

age, weight = 21, 101.5
print ( age )
print ( weight )

21
101.5

They will respective be assigned variables of type int and float.

type( age )
int
type( weight )
float

Question : Which of the following are floats
25 + .5j
25.5

Question : Which of the following are integers
25
25.5

Question – Which of the following are valid variable names in Python
name_1
1_name
name~1
name@1

Question – Which of the following is an invalid variable name in Python
True
true_false
false_1
true

Question – Which of the following is an invalid variable assignment
age = 21
age, sex = 21, “Male”
age, sex = (21, “Male”)
age, sex == 21, “Male”
age = 21 + 3

Challenge – Swap the two variables age_1 and age_2’s values.

age_1 = 21
age_2 = 22


solution

temp  = age_1
age_1 = age_2
age_2 = temp

print ( age_1 , age_2)

Python Variables Cheat sheet

%d bloggers like this: