0% found this document useful (0 votes)
3 views

Python Basics

The document provides an overview of various Python data types including numeric types, strings, lists, tuples, and dictionaries, along with examples of their usage. It also covers control flow statements, boolean operators, and functions, illustrating how to manipulate and process data in Python. Additionally, it touches on advanced topics like list comprehension, importing modules, and using *args and **kwargs in functions.

Uploaded by

puneethapatkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Basics

The document provides an overview of various Python data types including numeric types, strings, lists, tuples, and dictionaries, along with examples of their usage. It also covers control flow statements, boolean operators, and functions, illustrating how to manipulate and process data in Python. Additionally, it touches on advanced topics like list comprehension, importing modules, and using *args and **kwargs in functions.

Uploaded by

puneethapatkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Numeric data type

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

>>> my_string = "I'm a Python programmer!"


>>> otherString = 'The word "python" usually refers to a snake'
>>> tripleString = """Here's another way to embed "quotes" in a string"""
>>> my_number = 123
>>> my_string = str(my_number)

>>> x = int("123")

>>> string_one = "My dog ate "


>>> string_two = "my homework!"
>>> string_three = string_one + string_two # concatenation
• >>> my_String = “ This is my book!”
• >>> my_String.upper()
• >>> dir(my_String)
• >>> help (my_Stirng.captalize)
• >>> type(my_String)
• >>> my_String = “I like Apple”
• >>> My_String[0:2]
>>> my_String[0:-5]
>>> print(my_String[0])
>>> my_String[:]
>>> my_String[:1]
• String methods
>>> S.captalize()
>>> S.count(x) # returns the number of times x appears
>>> S.index(x) # returns the index of first substring identical
>>> S.find(t)
>>> S.join(Seq) # combine the strings into single string using s
as the glue.
More on Python types
More Python type
• Lists are sequences of things
• list can contain a number, a string, and another list
• >>> x= [24, “A”, [1,2]]
>>> x =[] # empty list
>>> x [23]
Creating a list
L = list (‘’hil’’)
M = list()
Operations on lists
• Indexing
>>> x =[12,-2,9,’a’,[1,2]]
X[1]
X[-1]
X[0;3]
X[:-1]
Y = [2]
x+y
x.append(50)
x.extend([2,3])
24 in x
• Lists containing list
Table = [[1,2,3],[2,3,4],[4,5,6]]
S = ‘abc’*4
S+S
one =str(1)
type(one)
I =int(str(1))
Type(I)
Empty= str()
>>> my_list = [1, 2, 3]
>>> my_list2 = ["a", "b", "c"]
>>> combo_list = my_list + my_list2
>>> combo_list
>>> alpha_list = [34, 23, 67, 100, 88, 2]
>>> alpha_list.sort()
>>> alpha_list
>>> alpha_list = [34, 23, 67, 100, 88, 2]
>>> sorted_list = alpha_list.sort()
>>> sorted_list
>>> print(sorted_list)
# none is important, you cannot assign it to a different variable
Tuples
• Using commas, we could create a sequence is called tuples
>>> x = (24, 27, 2.17, “w”, 7)
>>> y =(100,) # tuple with one element
>>> z=() # empty tuple
Not tuple
>>> y = (67)
>>> y == 67
# The parenthesis makes no difference
>>> s == 8
>>> t =5,
Making tuples
>>> L = tuple(‘hil’)
>>> L
>>> M = tuple()
>>> M
>>> K = (24, 2.15, “W”,9)
>>> K[-1]
>>> K[2]
>>>K[-1:-3]
Concatenation

>>> 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 value < 10:


• print("That's a great deal!")
• elif 10 <= value <= 20:
• print("I'd still pay that...")
• else:
• print("Wow! That's too much!")
Boolean operators
• x = 10
• y = 20

• if x < 10 or y > 15:


• print("This statement was True!")
• x = 10
• y = 10
• if x == 10 and y == 15:
• print("This statement was True")
• else:
• print("The statement was False!")
• my_list = [1, 2, 3, 4]
• x = 10
• if x not in my_list:
• print("'x' is not in the list, so this is True!")
• x = 10
• if x != 11:
• print("x is not equal to 11!")
• my_list = [1, 2, 3, 4]
• x = 10
• z = 11
• if x not in my_list and z != 10:
• print("This is True!")
Checking for Nothing & special characters

• if empty_string == "":
• print("This is an empty string!")
• >>> print("I have a \n new line in the middle")
• >>> print("This sentence is \ttabbed!")

• >>> print("This is a backslash \")


• >>> print("This is a backslash \\")
my_list = [1, 2, 3, 4, 5, 6, 7,200, 120, 11, 13, 12, 2, 8, 102]
even = []
not_even = []
outlier = []
for i in my_list:
if i > 90:
outlier.append(i)
elif i%2 == 0:
even.append(i)
else:
not_even.append(i)
print('Even numbers', even)
print('Odd numbers', not_even)
print('outliers', outlier)
• Find the sum of all numbers in the given list
sum = 0
for i in my_list:
sum = sum + i
print('Sum of the elements in the list', sum)
Find the sum of even numbers in the list
even = []
for i in my_list:
if i%2 == 0:
even.append(i)
# step 2: add all items in even list
num = 0
for i in even:
sum= sum + i
print('The sum of even numbers', sum)
• Find the number of even numbers in the given list.
count = 0
for i in range(len(my_list)):
if my_list[i]%2==0:
count = count +1
print('The count of even numbers in the list', count)
• Use zip function to aggregate two given lists
state_id = [1,2,3,4]
state = [‘Karnataka', ‘Goa', ‘AP’, ‘TN’]
for i, j in zip(state_id, state):
print(f'{i} {j}’) #f’ formatted strings
• Extract a particular type form the given tuple that has
mixed data type.
• Ex: g_tu = (1,”AB”, 3, 4,”CD”,5), extract only integers
g_tu = (1,”AB”, 3, 4,”CD”,5)
for i in g_tup:
if type(i) == int:
print(i)
• Suppose you’ve created list that contains tuples as
list_tup = [(1,2), (4,5), (7,9)] How to unpack the tuples and
create two lists from the list.
list_tup = [(1,2), (4,5), (7,9)]
list1 = []
list2 = []
for i,j in list_tup:
list1.append(i)
list2.append(j)

print('List of first tuple items', list1)


print('List of second tuple items', list2)
• Use enumerate(), to extract elements in a tuple
my_tup = ('Apple', 'Orange', 'Banana')
for i,j in enumerate(my_tup, start=1):
print(i,j)
• Looping through Dictionaries
my_dict = {"apple": 2.50, "orange": 1.99, "banana": 0.59}
• How to extract all the keys in the dictionary?
for i in my_dict.keys():
print(i)
• How to access all the values in a dictionary?
for i in my_dict.values():
print(i)
• How to access both the keys and the values together from a
dictionary?
for i,j in my_dict.items():
print('Key: ', i)
print(f'Value: {j}’)
• Find an average of all values in a dictionary?
for i in my_dict.values():
values.append(i)

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

while i < 10:


if i == 3:
i += 1
continue

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/.

You might also like