Python Basics
Python Basics
X = 3j+2
type(X)
<type 'complex'>
Strings
• >>> x =‘duck’
>>> type(x)
>>> x =“ \n
Better is better than average.\n Good is better than
Better.\n Best is better than best.
>>> print(x)
>>> my_string = "Welcome to Python!"
>>> another_string = 'The bright red fox jumped the fence.’
>>> a_long_string = '''This is a
>>> x = int("123")
>>> k+t
Identify at least difference between list and tuples.
Tuples once created, it cannot be modified
• >>> my_tuple = (1, 2, 3, 4, 5)
• >>> my_tuple[0:3]
• >>> another_tuple = tuple()
• >>> abc = tuple([1, 2, 3])
• >>> abc_list = list(abc) # casting (type)
Dictionaries
• Dictionaries stores mappings between many kinds of data
types.
• Example: How to store the students name and their choice
of electives?
• we want something like this
>>> MSc_DS
{ ‘Patel Raj’ : [‘Advanced Regression’, ‘ MLII’],
‘Harschit’ : [‘No SQL’, Advanced R Prog’], …..}
Dictionaries
• Most often we use string as the keys of a dictionary and use all
kind of items as values.
>>> d = {‘x’:43, ‘y’:56, ‘z’ :7}
>>> y ={1:2, 3:6}
>>> z ={}
>>> L= dict(x=43, y=56, z =7}
Also, M = dict([[1,2],[3,6]])
>>> d[‘x’]
>>> M[1]
>> d[‘w’]
• Dictionaries and lists can be mixed.
• Dictionaries can be used to build information
• Used to collect various attributes of an object
• >>> my_dict = {}
• >>> another_dict = dict()
• >>> my_other_dict = {"one":1, "two":2, "three":3}
• >>> my_other_dict
• >>> my_other_dict["one"] # to access the value
• >>> my_dict = {"name":"Mike", "address":"123 Happy Way"}
• >>> my_dict["name"]
• >>> "name" in my_dict
>>>"state" in my_dict
• How get the key values in Dictionaries?
>>> my_dict.keys()
Find the even, odd numbers and outliers in the given list,
separate them
IF …
• >>> if 2 > 1:
• print("This is a True statement!")
• >>> var1 = 1
• >>> var2 = 3
• >>> if var1 > var2:
• print("This is also True") if var1 > var2:
• print("This is also True")
• else:
• print("That was False!")
• # Python 2.x code
• value = raw_input("How much is that doggy in the window? ")
• value = int(value)
• if empty_string == "":
• print("This is an empty string!")
• >>> print("I have a \n new line in the middle")
• >>> print("This sentence is \ttabbed!")
average = sum(values)/len(values)
print(f'Average of values: {average}')
• How to update all values in the dictionary?
• Suppose you are offering a discount of 25% on all fruits.
for i, j in my_dict.items():
my_dict.update({i: j*.75})
print(my_dict)
• Print each word in the given sentence.
sent = ‘Today is a great day'
# splitting the sentence into words
sent_split = sent.split()
# extract each word with a loop
for i in sent_split:
print(i, end = ' / ')
• While loop
i=0
while i < 10:
print(i)
i=i+1
----
while i < 10:
print(i)
if i == 5:
break
i += 1
i=0
print(i)
if i == 5:
break
i += 1
my_list = [1, 2, 3, 4, 5]
for i in my_list:
if i == 3:
print("Item found!")
break
print(i)
else:
print("Item not found!")
• Write a function to sum of digits in the given integer
>>> def SoD(n):
num= abs(n)
total = 0
while num >= 1:
total = total + (num % 10)
num = num //10
return total
Create a triangle with ***’s
def triangle():
print('*’)
print('* *’)
print('* * *’)
print('* * * *’)
Write a function to find area of a rectangle
def arear(l, b):
area= l*b
return area
• Write a function to assign grades for the given mark
def assignGrade(marks):
if marks >= 90:
grade = 'A’
elif marks >= 70:
grade = 'B’
elif marks >= 50:
grade = 'C’
elif marks >= 40:
grade = ‘D’
else:
grade = 'F’
return grade
>>> range(start, end, increment)
Using range (), write a function to find factorial of an integer
>>> def factorial(n):
if n < 0:
return ‘Factorial is undefine’
fact =1
for i in range(1, n+1):
fact =fact*i
return factorial
Pop()
A = [10,20,10,30,10,50]
A.pop(4)
Print(A)
---
A= [10,20, 30,40,10,10]
A.remove(10)
Print(A)
• List Comprehension
• these are very handy
>>> x = [i for i in range(5)]
>>> x = ['1', '2', '3', '4', '5']
>>> y = [int(i) for i in x]
>>> y
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
>>> print( {i: str(i) for i in range(5)} )
>>> my_dict = {1:"dog", 2:"cat", 3:"hamster"}
>>> print( {value:key for key, value in my_dict.items()} )
import
>>> import this
>>> from math import sqrt
>>> sqrt(12)
>>> from math import pi, sqrt
>>> from math import * # * is wild card character
>>> sqrt(7)
>>> pi*5*5
*args and **kwargs
• Setting up many argument or keyword arguments in a
function
>>> def many(*args, **kwargs):
print(args)
print(kwargs)
>>> many(1,2,3, name =“Ram”, Class=“MSc”)
Scope and Global
def function_a(): def function_a():
a=1 global a
b=2 a=1
return a+b b=2
return a+b
def function_b():
c=3 def function_b():
return a+c c=3
return a+c
print( function_a() )
print( function_b() ) print(function_a())
print(function_b())
Learning from the Library
• Introspection
• csv
• ConfigParser
• logging
• os
• smtplib / email
• subprocess
• sys
• thread / queues
• time / datetime
• Introspection
• type
• dir
• Help
• X = “abc”
• Y =7
• Z= None
>>> type(X)
Dir
dir(“abc”)
>>> import sys
dir(sys)
help()
CSV module
• Reading a CSV file
• Download the file
http://www.who.int/tb/country/data/download/en/.