Python is most popular programming language among data scientists across the world and like high level languages, python is easy to read, take less time to write and is portable. So in this post we will learn about basics of python which includes variables, numbers conditionals, functions, list, dictionary, set, expression etc…

1. Variable, Numbers and Strings

Variable

A variable is simply a container for data.

#for example
pi = 3.14
print(pi)
## 3.14

Numbers

Numbers help in carrying out calculations. In python number are categorized in different data-types. A type is way to define various data structures and containers and define the functionality associated with them.

👉 Types are implemented in python as classes.

To check if a number belongs to particular class use isinstance() and provide number as first argument and class name as second argument.

# isinstance(object, class)
isinstance(2, int)
## True

There are three numeric types in python :-

  1. int for integers
  2. float for decimals
  3. complex for complex numbers

Strings

Strings are sequences of characters just like your name.

#How to create a string ?

myname = 'Vidyasagar Bhargava'
print(myname)
## Vidyasagar Bhargava
print(f"The type of string is {type(myname)}")
## The type of string is <class 'str'>

In above example we used f-strings which provides a concise and convenient way to embed python expressions inside string literals for formatting.

👉 While defining string you can use single and double quotes for a single line of characters. Multiple lines are generally put in triple quotes.

String Methods

index

#to get index of substring in a string  
print(f"The index of 'V' in myname is {myname.index('V')}")
## The index of 'V' in myname is 0
print(f"The index of 'a' in myname is {myname.index('a')}")
## The index of 'a' in myname is 4

👉 Python is zero-indexed unlike R.

To check if a substring present in string

"i" in "Vidyasagar"
## True
"A" in "Vidyasagar"
## False

Breaking string based on some rule

new_string = "1:2:3:4"
new_string.split(":")
## ['1', '2', '3', '4']

👉 Space is default parameter in split method.

To access individual character in string.

# myname = Vidyasagar Bhargava defined earlier
print(myname[4]) #access fifth letter  
## a
print(myname[-4]) #access 4th letter from the end
## g

2. Conditionals

Loops

If you want to run an operation on a collection of items, then you can do it using for loops.

for item in iterable:
    your code here.

👉 An iterable is any object that can be looped on such as list, tuple, string etc.

countries = ["India", "United Kingdom", "United States", "China", "France"]

for country in countries:
    print(country)
## India
## United Kingdom
## United States
## China
## France

nested for loops

for country in countries:
    string_size = 0
    for alphabet in country:
        string_size += 1
    print(f"Name of country: is {country} which has length {string_size}")
## Name of country: is India which has length 5
## Name of country: is United Kingdom which has length 14
## Name of country: is United States which has length 13
## Name of country: is China which has length 5
## Name of country: is France which has length 6

looping on both indexes and items

for index, country in enumerate(countries):
    print(f"index is {index}")
    print(f"Country is {country}")
    print("--------------------------")
## index is 0
## Country is India
## --------------------------
## index is 1
## Country is United Kingdom
## --------------------------
## index is 2
## Country is United States
## --------------------------
## index is 3
## Country is China
## --------------------------
## index is 4
## Country is France
## --------------------------

While Statements

Use while statements when the block of code has to be run till the condition is true.

while condition:
    code block

We will use above countries example.

length = len(countries)
i = 0
while i < length:
    print(countries[i])
    i += 1
## India
## United Kingdom
## United States
## China
## France

If statements

Below is skeleton for if.. elif.. else syntax

if condition1:
        code_block1
elif condition2:
        code_block2
else:
       code_block3

let’s take an example

num = 10
if num == 12:
    print("number is 12")
elif num == 10:
    print("number is 10")
else: 
    print("num is neither 10 nor 12")
## number is 10

Nested if statements

num = 10
if num > 5:
    if num < 20:
        print("num is between 5 an 20")
## num is between 5 an 20

3. Functions

  • Creating a function
  • Calling a function

Creating a function

Here is skeleton of function defintion

def name_of_the_function(arguments):
    '''
    function doctring
    '''
    body of the function
    return the return value or expression

let’s take an example

def add_numbers(num1, num2):
    '''returns  the sum of num1 and num2''' 
    result = num1 + num2
    return  result
    

Calling a function

add_numbers(5,6)
## 11

4. List, Dictionary, Set, Expression

List

  • List is a data structure which can be used to store multiple data at once.
  • The indexing is done with 0 as first index.
  • They are great to preserve sequence of data and then to iterate over them later for various purposes.
# Creating a list  

mobiles = ['nokia','samsung', 'apple','htc', 'oneplus', 'sony']
print(mobiles[0])
## nokia

Two dimensional list

mobiles = [['nokia','samsung', 'apple'],['htc', 'oneplus', 'sony']]
print(mobiles[0][1])
## samsung

Methods in lists

  • append()
  • insert()
  • extend()
  • index()
  • remove()
  • pop()
  • sort()
  • reverse()
    To add elements in the list use append() method.
list.append(elem)

example

# append()
mobiles = []
mobiles.append('googlepixel')
mobiles.append('lg')
mobiles.append('micromax')
print(mobiles)
## ['googlepixel', 'lg', 'micromax']

To add elements to the list at a particular index use insert() method.

list.insert(index, element)

example

# initiliazing a list
mobiles = ['nokia','samsung', 'apple','htc', 'oneplus', 'sony']
print(mobiles)

#insert 'googlepixel' at 2nd position 
## ['nokia', 'samsung', 'apple', 'htc', 'oneplus', 'sony']
mobiles.insert(2, 'googlepixel')
print(mobiles)
## ['nokia', 'samsung', 'googlepixel', 'apple', 'htc', 'oneplus', 'sony']

To add another list to the list use extend() method.

list.extend(another_list)

example

langs = ['R','Python','Scala']
langs.extend(['Julia', 'C++'])
print(langs)
## ['R', 'Python', 'Scala', 'Julia', 'C++']

To get the index number of element in the list use index() method.

list.index(elem)

example

index_of_Julia = langs.index('Julia')
print(index_of_Julia)
## 3

To remove elements from the list use remove() method.

list.remove(elem)

example

langs.remove('C++')
print(langs)
## ['R', 'Python', 'Scala', 'Julia']

To remove last element of the list use pop() method.

list.pop()

example

#print previous list
print(langs)

#pop the list
## ['R', 'Python', 'Scala', 'Julia']
langs.pop()

#print current list
## 'Julia'
print(langs)
## ['R', 'Python', 'Scala']

👉 If the index is provided in pop() method then it will remove element at particular index.


numbers = [10, 20, 30, 40, 50]

numbers.pop(1)
## 20
print(numbers)
## [10, 30, 40, 50]

To sort the list use sort() method.

list.sort()

example

# initialize an unsorted list 

numbers = [7,1,9,3,5,2]
print(numbers)

# sort the list 
## [7, 1, 9, 3, 5, 2]
numbers.sort()
print(numbers)
## [1, 2, 3, 5, 7, 9]

To reverse the list use reverse() method.

list.reverse()
# initialize  a list
numbers = [7,1,9,3,5,2]
print(numbers)

# reverse the list
## [7, 1, 9, 3, 5, 2]
numbers.reverse()
print(numbers)
## [2, 5, 3, 9, 1, 7]

Functions over lists :

  • len()
  • enumerate()
  • sorted()

To get the length of list use len() function.

mobiles = ['nokia','samsung', 'apple','htc', 'oneplus', 'sony']
print(f"The length of the list mobile is {len(mobiles)}")
## The length of the list mobile is 6

To get the index and value of the list use enumerate() function.

for indx,name in enumerate(mobiles):
    print(f"Index is {indx} for mobile :{name}")
## Index is 0 for mobile :nokia
## Index is 1 for mobile :samsung
## Index is 2 for mobile :apple
## Index is 3 for mobile :htc
## Index is 4 for mobile :oneplus
## Index is 5 for mobile :sony

To sort over the list use sorted() function. However unlike sort() method here original list is preserved.

#initialize the list
numbers = [5, 6,2,1,8,7]

#get the sorted list  
print(sorted(numbers))

#get the original list
## [1, 2, 5, 6, 7, 8]
print(numbers)
## [5, 6, 2, 1, 8, 7]

Dictionary

A dictionary is set of unordered key, value pairs.The keys must be unique and they are stored in an unordered manner.

#creating a dictionary 

employees  = {'name' : ['Sundar','Elon', 'Satya'], 'company' : ['Google', 'Tesla', 'Microsoft'], 'birth_country' :['Ind','SA', 'Ind']}

#printing the dictionary
print(employees)
## {'name': ['Sundar', 'Elon', 'Satya'], 'company': ['Google', 'Tesla', 'Microsoft'], 'birth_country': ['Ind', 'SA', 'Ind']}
print(type(employees))
## <class 'dict'>

Getting values in a dictionary

print(employees['name'])
## ['Sundar', 'Elon', 'Satya']

You can use get() method as well to get the values. The only difference is that in get() method you can set default value.

print(employees.get('name'))
## ['Sundar', 'Elon', 'Satya']
print(employees.get('designation', 'default'))
## default

looping over dictionary

for k, v in employees.items():
    print(f"key is : {k}")
    print(f"value is : {v}")
    print("--------------------")
## key is : name
## value is : ['Sundar', 'Elon', 'Satya']
## --------------------
## key is : company
## value is : ['Google', 'Tesla', 'Microsoft']
## --------------------
## key is : birth_country
## value is : ['Ind', 'SA', 'Ind']
## --------------------

Adding elements to dictionary

employees ={}
employees['name'] = 'Jeff'
employees['company'] = 'Amazon'

print(employees)
## {'name': 'Jeff', 'company': 'Amazon'}

Using update() method we can add other dictionary.

other_dictionary = {'birth_country' : 'US'}
employees.update(other_dictionary)
print(employees)
## {'name': 'Jeff', 'company': 'Amazon', 'birth_country': 'US'}

Delete elements of a dictionary


# initiailize a dictionary  

employees  = {'name' : ['Sundar','Elon', 'Satya'], 'company' : ['Google', 'Tesla', 'Microsoft'], 'birth_country' :['Ind','SA', 'Ind']}
print(employees)

# delete the key value pair with key 'birth_country'
## {'name': ['Sundar', 'Elon', 'Satya'], 'company': ['Google', 'Tesla', 'Microsoft'], 'birth_country': ['Ind', 'SA', 'Ind']}
del employees['birth_country']
print(employees)
## {'name': ['Sundar', 'Elon', 'Satya'], 'company': ['Google', 'Tesla', 'Microsoft']}

👉 There is another way using pop() method which has advantage like if there is non-existent key you can pass default value.

print(employees.pop('Salary', None))
## None

Sets

  • A Set is an unordered collection of data with no duplicate elements.
  • Sets are iterable and mutable.

Set can be created by calling the set() function with a sequence or other iterable object.

# creating a empyty set
SetA = set()
print(SetA)

# creating a set with a string  
## set()
SetA = set("Vidyasagar")
print(SetA)

# Creating a set with a list 
## {'d', 'r', 's', 'g', 'y', 'a', 'i', 'V'}
SetA = set(["India", "China", "US"])
print(SetA)

#creating a set withlist of repeated number
## {'US', 'India', 'China'}
SetA = set([1,2,4,5,5,5,6,6,7,7,7])
print(SetA)
## {1, 2, 4, 5, 6, 7}

👉 Set is useful in removing duplicate enteries.

Methods on Sets

  • add()
  • update()
  • discard()
  • remove()
  • copy()
  • clear()
  • pop()

To add element to a set use add() method.

set.add(element)

example

SetA = set([1,2,3,4])
print(SetA)

#adding an element 5
## {1, 2, 3, 4}
SetA.add(5)
print(SetA)
## {1, 2, 3, 4, 5}

👉 You can add a tuple to set using add() method.

SetA = set([1,2,3,4])
print(SetA)
## {1, 2, 3, 4}
SetA.add((9,10))
print(SetA)
## {1, 2, 3, 4, (9, 10)}

Using update() method we can pass list and it will update Set with the elements.

set.update(element)

example

SetA = set([1,2,3,4])
print(SetA)
## {1, 2, 3, 4}
SetA.update([5,6])
print(SetA)
## {1, 2, 3, 4, 5, 6}

Using discard() and remove() method you can to remove element from the set.

SetA = set([1,2,3,4])
print(SetA)
## {1, 2, 3, 4}
SetA.discard(3)
print(SetA)
## {1, 2, 4}

remove() method

SetA = set([1,2,3,4])
print(SetA)
## {1, 2, 3, 4}
SetA.remove(3)
print(SetA)
## {1, 2, 4}

👉 discard() and remove() takes single element and remvoes from set howver if no value is present then discard() does not do anything howver remove() will raise KeyError exception.

Using copy() method we can create a shallow copy of the set.

SetA = set([1,2,3,4])
print(SetA)
## {1, 2, 3, 4}
SetB = SetA.copy()
print(SetB)
## {1, 2, 3, 4}

If you use assignment operator it will create a pointer to already existing set.

clear() method will remove all the elements from set.

SetA = set([1,2,3,4])
print(SetA)
## {1, 2, 3, 4}
SetA.clear()
print(SetA)
## set()

pop() will remove arbitary set element.

SetA = set([1,2,3,4])
print(SetA)
## {1, 2, 3, 4}
SetA.pop()
## 1
print(SetA)
## {2, 3, 4}

Other useful Set operations

#interaction()

SetA = set([1,2,3,4,5,6,7])
print(SetA)
## {1, 2, 3, 4, 5, 6, 7}
SetB = set([5,6,7,8])
print(SetB)
## {8, 5, 6, 7}
print(SetA & SetB)
## {5, 6, 7}
print(SetA.intersection(SetB))


#difference()
## {5, 6, 7}
print(SetA.difference(SetB))
## {1, 2, 3, 4}
print(SetB.difference(SetA))
## {8}

Expression

  • List Expression
  • Dictionary Expression
  • Generator Expression
  • Conditional Expression

List Expression

[compute(var) for var in iterable]

example

[str(x) for x in range(10)]
## ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

Dictionary Expression

{k,v for k in iterable}

example

{x:x**2 for x in range(5)}
## {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Generator Expression

(compute(var) for var in iterable)

example

(x for x in range(10))
## <generator object <genexpr> at 0x0000000041A4F728>
list(x for x in range(10))
## [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Conditional Expression

true_value if condition else false_value

example

x = "1" if True else "2"
print(x)
## 1