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

Python Fundamentals

The document provides an overview of Python fundamentals including: - Printing, variables, escape characters, keywords, operators, strings, formatting, loops, conditionals, functions, modules and more. It demonstrates basic syntax and features through examples like printing math operations, assigning variables, string slicing, conditional logic, and iterating with for loops. The document serves as a tutorial for learning core Python concepts.

Uploaded by

swapz99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Python Fundamentals

The document provides an overview of Python fundamentals including: - Printing, variables, escape characters, keywords, operators, strings, formatting, loops, conditionals, functions, modules and more. It demonstrates basic syntax and features through examples like printing math operations, assigning variables, string slicing, conditional logic, and iterating with for loops. The document serves as a tutorial for learning core Python concepts.

Uploaded by

swapz99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

9/21/2019 Python_Fundamentals

Python Fundamentals

Printing
In [ ]: #Basic Printing
#Print String
print("Hello")
print('Hello')

#Print math operations


#Math rule: PE(M&D)(A&S)
print(2 + 2)
print(2 * 2)
print(4 / 2)
print(4 // 2)
#Print using Triple quotes
print('''
Jupyter Notebook
Python 3
Conda
Atom''')
print("""
Jupyter Notebook
Python 3
Conda
Atom""")

Variable Assignment
In [ ]: var1 = 10
#Multiple variable assignment
a = b = c = d = 10
var2 ,var3 = 20, 30

print(var1 , var2, var3, a, b, c, d)

Escape Char.
In [ ]: #Escape Character
text1 = "Jupyter\tNotebook\nPython\t3\nConda\nAtom"
print(text1)
text2 = "Jupyter\aNotebook\tPython\\3\'Conda\"Atom"
print(text2)

Reserved Keyword
Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 1/43
9/21/2019 Python_Fundamentals

In [ ]: #Keywords in Python.Reserved


print('''
False\tclass\tfinally\tis\treturn
None\tfor\tlambda\ttry\tcontinue
except\tTrue\tdef\tglobal\tnot
with\tas\telif\tif\tor
yield\tassert\telse\timport\tpass
break\texcept\tin\traise
''')

Cont. char.
In [ ]: #Continutation Char : continuation character (\)
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
print(a)

b = "Hello" \
" "\
"World"
print(b)

Operators

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 2/43
9/21/2019 Python_Fundamentals

In [ ]: a = 10
b = 5
#Arithmetic Operators
print("="*50)
print("Arithmetic Operator")
print("Sum:",(a + b))
print("Difference:",(a - b))
print("Product:",(a * b))
print("Division:",(a / b))
print("Exponent:",(a ** b))
print("Floor Division:",(a // b))
print("Modulo: ", (a % 3))

#Comparision Operator. Return Bool


print("="*50)
print("Comparision Operator")
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
print(a != b)
print(a == b)

#Logical Operators
a = 5
b = 10
c = 5
print("="*50)
print("Logical Operator")
print("AND Operator:")
#And Operator: both need to be true
print(a == c and a != b )
print(b > a and c > b)
print(b ==c and b > a)
print(a == b and c >b)

#OR Operator: Either or both true case


print("OR Operator:")
print(a == c or a != b )
print(b > a or c > b)
print(b ==c or b > a)
print(a == b or c == b)

print("Not Operator:")
print(not(a == c or a != b ) )
print(not(not(a == c or a != b ) ))

Strings
Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 3/43
9/21/2019 Python_Fundamentals

In [ ]: #Strings
greet = "Hello"
name = "Jupyter"
print(greet)
print(name)
print(greet + name)
print(greet +' '+ name)

String index,len,in,for,f-string
In [ ]: #String index,len,in,for,f-string
parrot = "Green Bird"

print("Type:",type(parrot))
print("Print Entire String:",parrot)
print("Print first element:",parrot[0])
print("String Slicing")
print(parrot[0:])
print(parrot[:-1])
print(parrot[0:-2])
print(parrot[0::2])
print(parrot[0::3])
print(f"Length of string parrot: {len(parrot)}")
for i in parrot:
print(i)

#String are immutable


#parrot[3] = 'd'
#But the string can be re-asigned
parrot = "Blue Bird"

vow = ''
for i in parrot:
if i in "aeiou":
vow +=i

print(f"Vowels in \'{parrot}\':{vow}")

if "Bird" in parrot:
print(True)
elif "Green" in parrot:
print(True)

if "Blue" in parrot:
print(True)
else:
print(False)

Format string and f-string


Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 4/43
9/21/2019 Python_Fundamentals

In [ ]: #Format string and f-string


text1 = "Jupyter Notebook"
#f-string
print(f"Python using {text1}")
text2 = "Python using {}"
print("Python using {}".format(text1))
print(text2.format(text1))

For Loop
In [ ]: #For Loop
for i in range(11):
print(i)

string_txt = "1234567890"
print('*'*10)
for i in string_txt:
print(i)

string_txt2 = "Parrot"
print('*'*10)
for i in string_txt2:
print(i)

User Input
In [ ]: #User Input
print("Enter a number:",end ='')
x = input()
print("You typed:",x)

y = input("Enter another number:")


print("You entered:",y)

#Multiple input
num1, num2, num3 = input("Enter three numbers: ").split()

if...elif....else

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 5/43
9/21/2019 Python_Fundamentals

In [ ]: #if...elif....else
age = 30
if age >= 25:
print("Age greater than equal to 25 but less than 35.")
elif age >= 35:
print("Age greater than or equal.")
else:
print("Age less than 25")

print("*"*10)
#Nested if
number = 25
if number >= 10:
print("Number greater than 10.")
if number > 15:
print("Number greater than 15.")
if number > 20:
print("Number greater than 20.")
if number == 25:
print(f"Number is {number}.")
else:
print("Number less than 10.")

Strange case
In [ ]: #Strange case:
xt = "False"
if xt:
print("Hello")

Negation
In [ ]: #Negation
print(not True)
print(not False)

end and Joins


In [ ]: #end and Joins
print("Text1",end='')
print("Text2")
print("Text1",end =' ')
print("Text2")
print('#'.join("Text1"))
print(' '.join("Parrot"))
str1 = "BlueBird"
print(' '.join(str1))

Processing math: 100%


Argument pass and unpack
localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 6/43
9/21/2019 g p p Python_Fundamentals

In [ ]: '''
#Argument pass and unpack
'''
'''
#Using import module argv
from sys import argv

#Unpack and assign


script , number1 ,number2 = argv
print(number1)
print(number2)
'''

Text File read,write,truncate,copy

from sys import argv script, filename1, filename2, filename3, filename4, filename5 = argv

#File Reading and writing

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 7/43
9/21/2019 Python_Fundamentals

In [ ]: #If argv used then replace file1.txt by filename1, file2.txt by filename2 e

#Open file. Read by default


txt1 = open('file1.txt')
#Read and print
print(txt1.read())
txt1.close()

#Open and write


#Auto-truncates txt2
txt2 = open('file2.txt','w')
#w+ , r+, a+ open for read and write
#a+ is for append
#txt2 = open(filename3 ,'w+')
#print(txt2.read()) #This will be empty
#Writes new line and Hello in txt2
txt2.write("\n")
txt2.write("Hello")
#Closing files
txt2.close()

#Truncation
txt3 = open('file3.txt','w')
txt3.truncate()
txt3.close()

#Read from one file and write to other file


txt4 = open('file4.txt')
txt4_dummy = txt4.read()
txt5 = open('file5.txt','w')
txt5.write(txt4_dummy)

txt4.close()
txt5.close()

Run its as below if using argv


python abc.py file1.txt file2.txt file3.txt file4.txt file5.txt

File Read, write,readline,seek

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 8/43
9/21/2019 Python_Fundamentals

In [ ]: #File read, write, realine, seek


#Open file. Read by default
txt1 = open('file1.txt','r')
#Read and print entire file
print(f"Entire file:\n{txt1.read()}")

#Move to start of text


txt1.seek(0)

#Print first and second line


print("="*40)
print("First Line:")
print(txt1.readline())
#Second Line is printed
print("Second Line:")
print(txt1.readline())
print("="*40)

#Move to start of text


txt1.seek(0)
print("Use for loop to read each line of the file:")
for i in txt1:
print(txt1.readline())

#Move to start of file


print("="*40)
print("Using seek to move to start of the text and then first 4 chars: ")
txt1.seek(0)
print(txt1.read(4))

#Read char
print("="*40)
print("Using readline(1) to print one char: ")
print(txt1.readline(1))

txt1.close()

More Seek

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 9/43
9/21/2019 Python_Fundamentals

In [ ]: #f.seek(offset, from_what)

#Read using open function


text1 = open('file1.txt','r')
print(text1.read())
#Move to 5 char from start of text
text1.seek(5)
#Read 1 char after seek
print(text1.read(1))

#Read using open function and with


with open('file5.txt', 'r') as f:
print(f.read())
#Move to 10 char from start of text
f.seek(10)
#Read 15 char after seek
print(f.read(15))

Augmented assigments
In [ ]: var1 = 5
var1 += 5
print(var1)
var1 -= 2
print(var1)
var1 *= 2
print(var1)
var1 /= 2
print(var1)
var1 //= 2
print(var1)
var1 %= 3
print(var1)

str ="Hello"
str +=" "
str +="World"
print(str)

Text Processing

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 10/43
9/21/2019 Python_Fundamentals

In [ ]: #Python treats all uppercase letters to be lower than lowercase letters.
def txt_processor(txt):
#Text Processing
print("="*40)
words = txt.split(' ')
#print(type(words)) #List

words = txt.split(' ')


#print(type(words)) #List

print("Printing split word list:")


for i in words:
print(i)

#Sort and Sorting


print("="*40)
words2 = txt.split(' ')
#print(type(words2)) #List
sorted_words = sorted(words2)
print("Printing sorted list using sorted() function:")
#Sorted return List
for i in sorted_words:
print(i)
print("="*40)
words2.sort()
print("Printing sorted list using sort() function:")
#sort doesnot return anything. It works on the object.
for i in words2:
print(i)

def pop_fn(txt,num):
print(txt.pop(num))

#Function call:
print("Python treats all uppercase letters to be lower than lowercase lette
print("Text with Lower and Upper Case Words:")
Text1 = "Comments are very important while writing a program"
txt_processor(Text1)

print("\n\nText with Lower Case Words:")


Text2 = Text1.lower()
txt_processor(Text2)

print("\n\nText with Upper Case Words:")


print("="*40)
Text3 = Text1.upper()
words3 = Text3.split(' ')
words3 = sorted(words3)
print("Split and Sorted ist:")
print(words3)
print("\nPrint First Word:",end=' ')
pop_fn(words3,0)
print("Print Second Word:",end=' ')
pop_fn(words3,1)
Processing math: 100%
print("Print Second Last Word:",end=' ')

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 11/43
9/21/2019 Python_Fundamentals
pop_fn(words3,-2)
print("Print Last Word",end=' ')
pop_fn(words3,-1)

While Loop
In [ ]: i = 0
while i < 6:
print(i)
i +=1

Break, Continue , Pass


In [ ]: var1 = int(input("Enter a number to demonstrate a break :"))

for i in range(var1):
if i == 3:
break
print(i)

var2 = int(input("Enter a number to demonstrate continue:"))


for i in range(var2):
if i == 3:
continue
print(i)

sequence = {'a', 'b', 'c', 'd'}


for val in sequence:
pass

Else usage in for and while loops.

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 12/43
9/21/2019 Python_Fundamentals

In [ ]: sequence = [10,20,30,40]


for i in sequence:
print(f"{i} exists in sequence.")
else:
i += 10
print(f"{i} doesnot exists in sequence.")

print("\n")
print("=" * 40)
print("\n")
num1 = int(input("Enter a number between 10 and 15>>"))
while num1 >= 10:
print(f"Number is {num1}")
num1 -= 1
else:
print("Number is less than 10")

Multiplication table generator


In [ ]: #Multiplication table for first five numbers
for i in range(1,6):
print(f"Multiplication table of {i}:")
for j in range(1,11):
print(f"{i} x {j} = {(i * j)}")
print("="*50)

Function

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 13/43
9/21/2019 Python_Fundamentals

In [ ]: def fun1():


print("This is function definition.")

def fun2(a,b):
print("\nFunction with Arguments")
print(f"First argument is {a}")
print(f"Second arument is {b}")

def funrtr(a,b):
print("This function returns value",end =' ')
return a + b

def calculator(a,b):
print("Sum:",(a + b))
print("Difference:",(a - b))
print("Product:",(a * b))
print("Division:",(a / b))
print("Floor Division:",(a // b))
print("Exponent:",(a**b))

#Function call:
fun1()
fun2(10,20)
print("\n")
var1 = funrtr(10,20)
print(var1)

print("\n")
print("*"*40)
calculator(40,20)

Lists

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 14/43
9/21/2019 Python_Fundamentals

In [ ]: #List. Always with [] seperated by commas.


print("Concept of List")
print("=" * 50)
fruits = ['Apple','Pear','Banana']
print(f"List fruits: {fruits}")
print(f"Length:{len(fruits)}")

#First and Last Element


print(f"First Element of List : {fruits[0]}")
print(f"Last Element of List : {fruits[-1]}")

#Slicing within List:


print(f"Slicing List: {fruits[0:2]}")

#Loop to display all elements


print("\nUsing for loop to display all elements of the List.")
for i in range(len(fruits)):
print(fruits[i])

#Append to List
#Append add to end of List
fruits.append('Orange')
print(f"\nUpdate List fruits :{fruits}")

#Check for an element in List


print("Checking for existance of Orange and Kiwi list.")
for i in range(len(fruits)):
if fruits[i] == 'Orange':
print("Orange in List fruits.")
break
else:
print("No Orange in List")

for i in range(len(fruits)):
if fruits[i] == 'Kiwi':
print("Kiwi in List fruits.")
break
else:
print("No Kiwi in List fruits.")

#Empty List
empty_l = []
print(empty_l)

#List comprehension
list_comp = [2 ** x for x in range(10)]
print(list_comp)
#Equivalent to
'''pow2 = []
for x in range(10):
pow2.append(2 ** x)'''

#Insert
#Insert doesnot replace but add at specific index
fruits.insert(3,'Kiwi')
Processing math: 100%
print("\nAdding Kiwi in List")

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 15/43
9/21/2019 Python_Fundamentals
print(f"Update List fruits :{fruits}")

#Change data on some index


fruits[0] ='Guava'
print("\nReplacing First element with Guava")
print(f"Update List fruits :{fruits}")

#Remove/Delete from List


#Remove one element
print("\nRemoving Pear from List.")
fruits.remove('Pear')
print(f"Update List fruits :{fruits}")
#Delete one element
print("\nDelete Orange from List.")
del fruits[3]
print(f"Update List fruits :{fruits}")
#List Clearance
print("\nClearing the List.")
fruits.clear()
print(f"Update List fruits :{fruits}")
#Delete fruit list
print("\nDeleting fruits list.")
del fruits
try:
print(f"Update List fruits :{fruits}")
except:
print("Fruits List deleted")

print("=" * 50)
print("List in List")
even = [0,2,4,6,8]
print(f"List 1 of Even numbers :{even}")

odd = [1,3,5,7,9]
print(f"List 2 of Odd numbers :{odd}")

numbers =[even , odd]


print("Joining the List.")
print(f"Number List: {numbers}")
print("Print Entire List:")
for i in numbers:
for j in i:
print(j)

print("\nRemove element using pop() function")


print(f"Even List:{even}")
print("Remove first element.")
even.pop(0)
print(f"Updated List:{even}")
print("Remove last element.")
even.pop(-1)
print(f"Updated List:{even}")

#Another way to create List


#my_List = list(range(100))
Processing math: 100%
#print(my_List)

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 16/43
9/21/2019 Python_Fundamentals

#List Extension
list_a = list(range(10))
list_b = list(range(10,20))
list_a.extend(list_b)
print(f"Extended List:{list_a}")

#List Copy

list_c = [4,5,6,7]
print(f"\nOrignal List : {list_c}")
list_c_copy = list_c
print(f"Copied list by using assigment operator: {list_c_copy}")

list_c_copy.append(11)
print("="*50)
print(f"Copied List after appending data: {list_c_copy}")
print(f"Orignal List: {list_c}")
print("Both are the same. The orignal lsit has been changed.")

print("\n")
print("="*50)
print("Now using copy() method:")
list_d = [9,10,11,12]
print(f"Orignal List:{list_d}")

list_d_copy = list_d.copy()
print(f"Copied list by using copy function: {list_d_copy}")

list_d_copy.append(23)
print("="*50)
print(f"Copied List after appending data: {list_d_copy}")
print(f"Orignal List: {list_d}")
print("Orignal List Unchnaged.")

#List Reversal
print("="*50)
list_e = [12, 78,0,56,89,98,11,6,4,7]
print(f"New List:{list_e}")
list_e.reverse()
print(f"Reverse List:{list_e}")
list_e.sort()

print(f"Sorted List:{list_e}")

Tuples

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 17/43
9/21/2019 Python_Fundamentals

In [ ]: #Tuples
#Tuples are immutable
tup = ("a","b","c")
print(f"Tuple:{tup}")
print("\nPrint Individual Tuple Element:")
for i in tup:
print(i)

print("="*50)
print("New Tuple:")
welcome = "Welcome to the Train","John","2019"
print(welcome)
print("\nFirst element:")
print(welcome[0])

#Tuples are immutable. The below statement will result in error


#welcome[1] = 'Adam'

#Tuples are immutable, however they can be re-assigned


welcome = "Welcome to the Train","Adam","2019"

print("\nUpdated Tuples:")
print(welcome)
print("="*50)
print('''Advantages of Tuple over List
Since, tuples are quite similiar to lists, both of them are used in similar
However, there are certain advantages of implementing a tuple over a list.
Below listed are some of the main advantages:
\t1)We generally use tuple for heterogeneous (different) datatypes and list
\t2)Since tuple are immutable, iterating through tuple is faster than with
\t boost.
\t3)Tuples that contain immutable elements can be used as key for a diction
\t4)If you have data that doesn't change, implementing it as tuple will gua

print("="*50)
print("Tuple Un-pack")
#Tuple element Un-packing
Song = 'Stairways to Heaven','Led Zepplin',1971
track,artist,year = Song
print(f"Tuple Song:{Song}")
print(f"Track:{track}")
print(f"Artist:{artist}")
print(f"Year:{year}")

print("="*50)
print("Tuple in Tuple")
Sng = ("Rock", "1970s",(("Stairways to Heaven","Led Zepplin"),("Hey Jude","
print(f"Tuple for Rock Song :\n{Sng}")
genre,era,trk_n_artist = Sng
len_t = len("Stairways to Heaven")
print(f"Genre: {genre}")
print(f"Era:{era}")
print(f"Tracks and Artitst:{trk_n_artist}")
cnt = 1
for i in trk_n_artist:
Processing math: 100% print(f"Record {cnt}:")

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 18/43
9/21/2019 Python_Fundamentals
print(f"{i[0]}\n -- {i[1]}")
cnt +=1

print("="*50)
Sng_lst= ("Rock", "1970s",["Stairways to Heaven","Led Zepplin"])
print(f"List in Tuple :\n{Sng_lst}")
genre_2,era_2,trk_n_artist_2 = Sng_lst
print(f"Genre: {genre_2}")
print(f"Era:{era_2}")
print(f"Tracks and Artitst:{trk_n_artist_2}")
trk_n_artist_2.append("Hey Jude")
trk_n_artist_2.append("Beatles")
trk_n_artist_2.append("We Will Rock You")
trk_n_artist_2.append("Queen")
print(f"\nList in Tuple (updated) :\n{Sng_lst}")

print("\nPrinting List which exists in tuples:")


for i in trk_n_artist_2:
print(i)

'''Individal element access via Index:


print(Sng_lst[1])
print(Sng_lst[2][0])'''

'''we cannot change the elements in a tuple. That also means we cannot dele
But deleting a tuple entirely is possible using the keyword del.
del Sng_lst
'''
print("="*50)
print(f"Index of Rock : {Sng_lst.index ('Rock')}")
print(f"Index of 1970s: {Sng_lst.index ('1970s')}")

print(f"No of times Rock appers in tuple:{Sng_lst.count('Rock')}")


print("="*50)
t1 = tuple()
t1 = tuple('Python')
print('t1 = ',t1)
#Single Element tuple
tup_s = ("Hello",)
print(f"Single Element Tuple: {tup_s}")

Ranges

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 19/43
9/21/2019 Python_Fundamentals

In [ ]: print(range(100))

my_List = list(range(100))
print(f"List of range 100 : {my_List}")

even = list(range(0,10,2))
print(f"List of even numbers : {even}")
odd = list(range(1,10,2))
print(f"List of odd numbers : {odd}")

#Index
print("\n")
num = range(0,10)
print(num)
print(num[0])
print(num[2])
print(num.index(9))

print("\n")
string1 = "Hello"
print(string1)
print(string1[0])
print(string1[2])
print(string1.index('l'))

#Negative Slicing
print("\nList details:")
for i in num:
print(i)

print("\nNegative Slicing")
#Negative Slicing when used implicitly reverses the index
for i in num[::-2]:
print(i)

print("\n")
for i in num[10:0:-2]:
print(i)

#Negative Slicing when used implicitly reverses the index


#However when explicitly mentioned it fails
print("\n")
print("No Output")
for i in num[0:10:-2]:
print(i)

#Negative Slicing Palindrome Slicing


print("\nPalindrome Check")
text_1 = "madam"
print(f"Text 1:{text_1}")
text_2 = text_1[::-1]
print(f"Text_2:{text_2}")
if text_1 == text_2:
print("String are equal.")
else:
Processing math: 100% print("String are un-equal.")

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 20/43
9/21/2019 Python_Fundamentals

O_range = range(0,100,4)
P_range = O_range[::5]

print("\n")
print("Number List:")
for i in O_range:
print(i)

print("\n")
print("Sliced List every 5 slice:")
for i in P_range:
print(i)

Iteration and iter()


In [ ]: text = "Hello"
my_iteration = iter(text)
print(my_iteration)
print(type(my_iteration))
print("\nIteration using iter() class.")
print(next(my_iteration))
print(next(my_iteration))
print(next(my_iteration))
print(next(my_iteration))
print(next(my_iteration))
#print(next(my_iteration)) will give an error
try:
print(next(my_iteration))
except:
print("End of Iteration.")

print("\nIteration using for loop")


for i in text:
print(i)

Enumerate
The enumerate() method adds counter to an iterable and returns it (the enumerate object). The
syntax of enumerate() is:

enumerate(iterable, start=0)

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 21/43
9/21/2019 Python_Fundamentals

In [ ]: grocery = ['bread', 'milk', 'butter']


enumerateGrocery = enumerate(grocery)

print(type(enumerateGrocery))

# converting to list
print(list(enumerateGrocery))

# changing the default counter


enumerateGrocery = enumerate(grocery, 10)
print(list(enumerateGrocery))

all() function
The all() method returns True when all elements in the given iterable are true. If not, it returns False.

The all() method returns: True - If all elements in an iterable are true False - If any element in an
iterable is false

In [ ]: # all values true


l = [1, 3, 4, 5]
print(all(l))

# all values false


l = [0, False]
print(all(l))

# one false value


l = [1, 3, 4, 0]
print(all(l))

# one true value


l = [0, False, 5]
print(all(l))

# empty iterable
l = []
print(all(l))

any() function
any() returns:

True if at least one element of an iterable is true.

False if all elements are false or if an iterable is empty

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 22/43
9/21/2019 Python_Fundamentals

In [ ]: l = [1, 3, 4, 0]
print(any(l))

l = [0, False]
print(any(l))

l = [0, False, 5]
print(any(l))

l = []
print(any(l))

Dictonary

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 23/43
9/21/2019 Python_Fundamentals

In [ ]: #Dictionary
# variable = {key:value, key: value,key: value}
#Values mutable but keys are immutable

'''# empty dictionary


my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])'''

fruits = {'OR':'Orange',
'PR':'Pear',
'AP':'Apple'}

print(fruits)
for i in fruits:
print(f"{i}:{fruits[i]}")

key_tup = ('OR','PR','AP')
for i in key_tup:
print(fruits[i])

#Adding Grapes with key GR to dictonary fruits


fruits['GR'] = 'Grapes'
print("Updated Dictonary fruits:")
print(fruits)
fruits['GR'] ='Black Grapes'
print("Overwriting Grapes and so updated Dictonary fruits:")
print(fruits)

del fruits
try:
print(fruits)
except:
print("Dictionary Deleted.")

print("="*50)
#Re-assign tuples
key_tup = ('OR','PR','AP','GR')
print(key_tup)
val_list = ['Orange','Pear','Apple','Grapes']
print(key_tup)
fruits = dict({key_tup:val_list})
print("Bad way of using tuples and list in dictonary")
print(fruits)
Processing math: 100%
del fruits

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 24/43
9/21/2019 Python_Fundamentals
'''Above is bad way of using tuples and list in dictonary'''

print("="*50)
key_tup = ('OR','PR','AP','GR')
print(key_tup)
val_list = ['Orange','Pear','Apple','Grapes']
print(val_list)
print("Good way of using tuples and list in dictonary")
fruits = {key_tup[0]:val_list[0],key_tup[1]:val_list[1],key_tup[2]:val_list
print(fruits)

'''
Individual element key and value deletion in dictionary
del fruits['GR']
print(fruits)
'''
print("="*50)
print(fruits.items())
print("Using loop and multiple variable assignment to print individual item
for i,j in list(fruits.items()):
print(f"Key is {i} and Value is {j}")

print("="*50)
print("Searching the dictionary and retreiving value using get() function."
val1 = fruits.get('GR')
print(val1)

'''
Python 2
print("="*50)
val2 = fruits.has_key('Orange')
print(val2)
'''

print("="*50)
fruits.clear()
print("Clearing dictonary fruits")
print("Empty dictonary fruits:")
print(fruits)

print("="*50)
print("Dictionary Creation using update() function.")
fruits = {'OR':'Orange',
'PR':'Pear',
'AP':'Apple'}
veg = {'TM':'Tomato',
'SP':'Spinach',
'PO':'Potato'}
market ={}
market.update(fruits)
print(market)
market.update(veg)
print(market)

market_2 = market.copy()
print(market_2)
Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 25/43
9/21/2019 Python_Fundamentals

Set

A set is an unordered collection of items. Every element is unique (no duplicates) and must be
immutable (which cannot be changed).

However, the set itself is mutable. We can add or remove items from it.

Sets can be used to perform mathematical set operations like union, intersection, symmetric
difference etc.

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 26/43
9/21/2019 Python_Fundamentals

In [ ]: #Same as Dictionary but no key


fruits ={"Orange","Apple","Pear"}
print(fruits)
for i in fruits:
print(i)

#Doesnot create a set but a dictionary is created


#set_a ={}
set_a =set()
print(type(set_a))

#Another way to create set. From List


veg = set(["Tomato","Potato","Spinach"])
print(veg)

fruits.add("Grape")
veg.add("Celery")

print(fruits)
print(veg)

#Set from range,tuples,list


set_rng = set(range(0,100,2))
set_tup = set(('Tomato','Apple','Spinach'))
set_lst = set([2,5,6,7,8])

'''
print(set_rng)
print(set_tup)
print(set_lst
'''
# set do not have duplicates
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)

# set cannot have mutable items


# here [3, 4] is a mutable list
# If you uncomment line #12,
# this will cause an error.
# TypeError: unhashable type: 'list'
#my_set2 = {1, 2, [3, 4]}
#print(my_set2)

#Add or remove elements from Set


set_new ={2,4,7,9,10}

#set_new[0]
#TypeError: 'set' object does not support indexing

'''
A set is an unordered collection of items. Every element is unique (no dupl
However, the set itself is mutable. We can add or remove items from it.Sets
mathematical set operations like union, intersection, symmetric difference
'''
Processing math: 100%
#Add to set similar to append in list

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 27/43
9/21/2019 Python_Fundamentals
set_new.add(12)
print(set_new)

#Add multiple elements -List


set_new.update([20,21,22])
print(set_new)

#Add multiple elements -Tuples and another List


set_new.update((23,23,25),{26,27,28})
print(set_new)

#Remove using discard() and remove()


set_new.remove(23)
set_new.discard(24)
#set_new.remove(24)
#When remvoe used for non-existing items in the set, it will throw error. H
set_new.discard(26)

print(set_new)
#o/p:{2, 4, 7, 9, 10, 12, 20, 21, 22, 25, 27, 28}

#Pop randomly removes elements


set_new.pop()
print(set_new)
#o/p:{4, 7, 9, 10, 12, 20, 21, 22, 25, 27, 28}
set_new.pop()
print(set_new)
#o/p:{7, 9, 10, 12, 20, 21, 22, 25, 27, 28}

#Clear a set
set_new.clear()
print(set_new)
#o/p: set()

'''
even = set(range(0,40,2))
even_2 = set(range(0,10,2))
odd = set(range(1,40,2))

#UNION
union_set = even.union(odd)
print(union_set)

#union_set2 = even|odd
#print(union_set2)

#INTERSECTION
#inter_set = even.intersection(odd)
inter_set = even.intersection(even_2)
print(inter_set)

#inter_set2 = even & even_2


#print(inter_set_2)

#DIFFERENCE
Difference of A and B (A - B) is a set of elements that are only in A but n
Processing math: 100%
Similarly, B - A is a set of element in B but not in A.

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 28/43
9/21/2019 Python_Fundamentals

diff_set = even.difference(even_2)
#diff_set = even - even_2
print(diff_set)

#SYMMETRIC DIFFERENCE
#Symmetric Difference of A and B is a set of elements in both A and B excep
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
sym_diff = A ^ B
'''
#SET OPERATIONS:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print("=" * 50)
print("Set Operations:")
print(f"Set A : {A}")
print(f"Set B : {B}")
#Union : A | B
#Set of all elements of A and B but will not have duplicates as it is a set
print(f"Union: {A.union(B)}")

#Intersection : A & B
#Set of whats common in both
print(f"Intersection: {A.intersection(B)}")

#Difference : A - B
#Set of whats unique in A
print(f"Difference :{A.difference(B)}")

#Symmetric Difference : A ^ B
#Set of whats not comman in both
print(f"Symmetric Difference : {A.symmetric_difference(B)}")

print("=" * 50)
print("Sets:")
print(f"Set A : {A}")
print(f"Set B : {B}")
print("Performing Difference Update")
A.difference_update(B)
print("Sets after difference update:")
print(f"Set A : {A}")
print(f"Set B : {B}")
print('''Why ?
The difference_update() updates set A with the set difference of A-B.
A will be equal to A-B
B will be unchanged
''')

#Subset and Superset

a = {1,2}
b = {1,2,3,4}

print(a.issubset(b))
print(a.issuperset(b))
Processing math: 100%
print(b.issuperset(a))

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 29/43
9/21/2019 Python_Fundamentals

#Disjoint
#No common element
print("=" * 50)
c = {3,4,5}
print(a.isdisjoint(c))

#Frozen Set
abc =frozenset(range(0,100,2))
#abc.add(3)
#abc.remove(2)
#abc.discard(4)
#abc.difference_update(b)
#add,remove,discard,difference_update will cause errors
#union, intersetion, difference is allowed

Object Orinented Python

One of the popular approach to solve a programming problem is by creating objects. This is known
as Object-Oriented Programming (OOP).

An object has two characteristics:attributes,behavior

Ex. Parrot is an object:


name, age, color are attributes,
singing, dancing are behavior

Important concepts:

Inheritance: A process of using details from a new class without modifying existing class

Encapsulation: Hiding the private details of a class from other objects.

Polymorphism A concept of using common operation in different ways for different data input.

Constructors in Python

Class functions that begins with double underscore (__) are called special functions as they have
special meaning.

Of one particular interest is the init() function. This special function gets called whenever a new
object of that class is instantiated.

This type of function is also called constructors in Object Oriented Programming (OOP). We
normally use it to initialize all the variables.

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 30/43
9/21/2019 Python_Fundamentals

In [ ]: class Kettle(object):


power_source = "Electricity"

def __init__(self,make,price):
self.make = make
self.price = price
self.on = False
def switch_on(self):
self.on = True

#Instantiating class Kettle object Kenwood and Hamilton


Kenwood = Kettle("Kenwood", 16.75)
Hamilton = Kettle("Hamilton",12.50)

print("Kettle Details:")
print("="*50)
print(f"Make: {Kenwood.make}")
print(f"Price: ${Kenwood.price}")
print(f"Switch Status: {Kenwood.on}")
print("\n")
print(f"Make: {Hamilton.make}")
print(f"Price: ${Hamilton.price}")
print(f"Switch Status: {Hamilton.on}")
print("="*50)

#Delete attribute
'''
del Kenwood.make
print(f"Make: {Kenwood.make}")
'''
Bosch = Kettle("Bosch",19.05)
print("New Kettle Details:")
print(f"Make: {Bosch.make}")
print(f"Price: ${Bosch.price}")
print(f"Switch Status: {Bosch.on}")

#Delete Object
'''
del Bosch
print(f"Make: {Bosch.make}")
print(f"Price: ${Bosch.price}")
print(f"Switch Status: {Bosch.on}")

On the command del Bosch, this binding is removed and the name Bosch is del
The object however continues to exist in memory and if no other name is bou
This automatic destruction of unreferenced objects in Python is also called
'''

#Calling Methods:
#USING Objects to call methods
Kenwood.switch_on()
Hamilton.switch_on()

#Using Class to call methods


Kettle.switch_on(Bosch)
Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 31/43
9/21/2019 Python_Fundamentals
print("="*50)
print("Updated Switch Status:")
print(f"Make: {Kenwood.make}")
print(f"Price: ${Kenwood.price}")
print(f"Switch Status: {Kenwood.on}")
print("\n")
print(f"Make: {Hamilton.make}")
print(f"Price: ${Hamilton.price}")
print(f"Switch Status: {Hamilton.on}")
print("\n")
print(f"Make: {Bosch.make}")
print(f"Price: ${Bosch.price}")
print(f"Switch Status: {Bosch.on}")
print("="*50)

#Adding additional attributes to an object:


Kenwood.power = '100W'
print("Updated Attributes on an object:")
print(f"Make: {Kenwood.make}")
print(f"Price: ${Kenwood.price}")
print(f"Switch Status: {Kenwood.on}")
print(f"Power:{Kenwood.power}")

#Attribute Sharing:
print("="*50)
print(Kettle.power_source)
print(Kenwood.power_source)
print(Hamilton.power_source)
print(Bosch.power_source)
print("="*50)
print(Kettle.__dict__)
print(Kenwood.__dict__)
print(Hamilton.__dict__)
print(Bosch.__dict__)
print('''Only Kettle has attribute power_source and none of the objects hav

#re-assign power_source for two of the object


Hamilton.power_source = "Atomic"
Bosch.power_source = "Gas"
print("="*50)
print("Updated Attributes")
print(Kettle.power_source)
print(Kenwood.power_source)
print(Hamilton.power_source)
print(Bosch.power_source)
print("="*50)
print(Kettle.__dict__)
print(Kenwood.__dict__)
print(Hamilton.__dict__)
print(Bosch.__dict__)
print('''Now Hamilton and Bosch has power_source attributes in __dict__.'''

Inheritance
Processing math: 100%

What is Inheritance? Inheritance is a powerful feature in object oriented programming.


localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 32/43
9/21/2019 Python_Fundamentals
What is Inheritance? Inheritance is a powerful feature in object oriented programming.
It refers to defining a new class with little or no modification to an existing class. The new class is
called derived (or child) class and the one from which it inherits is called the base (or parent) class.

In [ ]: #Python Inheritance Syntax


"""
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
"""

In [ ]:

Multiple Inheritance

Type Markdown and LaTeX: α 2

Operator Overloading

In [ ]:

Lambda \ Anonymous Functions

Syntax : lambda arguments: expression

We use lambda functions when we require a nameless function for a short period of time.

In Python, we generally use it as an argument to a higher-order function (a function that takes in


other functions as arguments). Lambda functions are used along with built-in functions like filter(),
map() etc.

In [ ]: double = lambda x: x * 2


'''
Same as:
def double(x):
return x * 2
'''
# Output: 10
print(double(5))

Filter Function

The filter() function in Python takes in a function and a list as arguments.

The function is called with all the items in the list and a new list is returned which contains items for
which the function evaluats to True. Checks condition and return value for true case>

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 33/43
9/21/2019 Python_Fundamentals

In [ ]: my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(filter(lambda x: (x%2 == 0) , my_list))

# Output: [4, 6, 8, 12]


print(new_list)

The map() function in Python takes in a function and a list.

The function is called with all the items in the list and a new list is returned which contains items
returned by that function for each item. Basically Evaluates and return the output.

In [ ]: my_list = [1, 5, 4, 6, 8, 11, 3, 12]

new_list = list(map(lambda x: x * 2 , my_list))

# Output: [2, 10, 8, 12, 16, 22, 6, 24]


print(new_list)

Generators
In [ ]:

Date, Time and TimeZone

Get current date and Time using datetime class

In [ ]: import datetime


datetime_object = datetime.datetime.now()
#OR
#from datetime import datetime
#datetime_object = datetime.now()

print(datetime_object)

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 34/43
9/21/2019 Python_Fundamentals

In [ ]: from datetime import datetime

#datetime(year, month, day)


a = datetime(2018, 11, 28)
print(a)

# datetime(year, month, day, hour, minute, second, microsecond)


b = datetime(2017, 11, 28, 23, 55, 59, 342380)
print(b)

# datetime(year, month, day, hour, minute, second, timestamp)


c = datetime(2017, 11, 28, 23, 55, 59, 342380)
print("year =", c.year)
print("month =", c.month)
print("hour =", c.hour)
print("minute =", c.minute)
print("timestamp =", c.timestamp())

Get current date using date class

In [ ]: import datetime


date_object = datetime.date.today()
#OR
#from datetime import date
#date_object = date.today()

print(date_object)

dir() to check attributes of module datetime

In [ ]: import datetime


print(dir(datetime))

Instantiate date objects from the date class

In [ ]: import datetime


d = datetime.date(2019, 4, 13)
#OR
#from datetime import date
#a = date(2019, 4, 13)
print(d)

Get date from a timestamp

Create date objects from a timestamp. A Unix timestamp is the number of seconds between a
particular date and January 1, 1970 (Unix Epoc) at UTC.

In [ ]: from datetime import date


timestamp = date.fromtimestamp(1326244364)
Processing math: 100%
print("Date =", timestamp)

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 35/43
9/21/2019 Python_Fundamentals

Print today's year, month and day

In [ ]: from datetime import date

# date object of today's date


today = date.today()

print("Current year:", today.year)


print("Current month:", today.month)
print("Current day:", today.day)

Time object to represent time

In [ ]: from datetime import time

# time(hour = 0, minute = 0, second = 0)


a = time()
print("a =", a)

# time(hour, minute and second)


b = time(11, 34, 56)
print("b =", b)

# time(hour, minute and second)


c = time(hour = 11, minute = 34, second = 56)
print("c =", c)

# time(hour, minute, second, microsecond)


d = time(11, 34, 56, 234566)
print("d =", d)
print("hour =", d.hour)
print("minute =", d.minute)
print("second =", d.second)
print("microsecond =", d.microsecond)

datetime.timedelta

A timedelta object represents the difference between two dates or times.

In [ ]: from datetime import datetime, date

t1 = date(year = 2018, month = 7, day = 12)


t2 = date(year = 2017, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)

t4 = datetime(year = 2018, month = 7, day = 12, hour = 7, minute = 9, secon


t5 = datetime(year = 2019, month = 6, day = 10, hour = 5, minute = 55, seco
t6 = t4 - t5
print("t6 =", t6)

print("type of t3 =", type(t3))


print("type
Processing math: 100% of t6 =", type(t6))

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 36/43
9/21/2019 Python_Fundamentals

In [ ]: from datetime import timedelta

t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33)


t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54)
t3 = t1 - t2

print("t3 =", t3)

In [ ]: from datetime import timedelta

t1 = timedelta(seconds = 33)
t2 = timedelta(seconds = 54)
t3 = t1 - t2

print("t3 =", t3)


print("t3 =", abs(t3))

In [ ]: from datetime import timedelta

t = timedelta(days = 5, hours = 1, seconds = 33, microseconds = 233423)


print("total seconds =", t.total_seconds())

Python format datetime

datetime to string

The way date and time is represented may be different in different places, organizations etc.

It's more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common in the UK.

The strftime() method is defined under classes date, datetime and time.

The method creates a formatted string from a given date, datetime or time object.

Here, %Y, %m, %d, %H etc. are format codes.

The strftime() method takes one or more format codes and returns a formatted string based on it.

In the above program, t, s1 and s2 are strings.

%Y - year [0001,..., 2018, 2019,..., 9999]

%m - month [01, 02, ..., 11, 12]

%d - day [01, 02, ..., 30, 31]

%H - hour [00, 01, ..., 22, 23

%M - month [00, 01, ..., 58, 59]

%S - second [00, 01, ..., 58, 59]

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 37/43
9/21/2019 Python_Fundamentals

In [ ]: from datetime import datetime

# current date and time


now = datetime.now()

t = now.strftime("%H:%M:%S")
print("time:", t)

s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)

s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)

Python strptime() - string to datetime

The strptime() method creates a datetime object from a given string (representing date and time)

In [ ]: from datetime import datetime

date_string = "21 June, 2018"


print("date_string =", date_string)

date_object = datetime.strptime(date_string, "%d %B, %Y")


print("date_object =", date_object)

sleep() Function

The sleep() function suspends execution of the current thread for a given number of seconds.

In [ ]: import time

print("Printed immediately.")
time.sleep(2.4)
print("Printed after 2.4 seconds.")

Multithreading and use of sleep() function

A thread is a subset of the process. A process can have one or more threads.

The sleep() function suspends execution of the current thread for a given number of seconds.

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 38/43
9/21/2019 Python_Fundamentals

In [ ]: import threading

def print_hello_three_times():
for i in range(3):
print("Hello")

def print_hi_three_times():
for i in range(3):
print("Hi")

t1 = threading.Thread(target=print_hello_three_times)
t2 = threading.Thread(target=print_hi_three_times)

t1.start()
t2.start()

In [ ]: import threading


import time

def print_hello():
for i in range(4):
#time.sleep(0.5)
print("Hello")

def print_hi():
for i in range(4):
time.sleep(0.7)
print("Hi")

t1 = threading.Thread(target=print_hello)
t2 = threading.Thread(target=print_hi)
t1.start()
t2.start()

Local, Global, Namespace

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 39/43
9/21/2019 Python_Fundamentals

In [ ]: def scope_test():


def do_local():
spam = "local spam"

def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"

def do_global():
global spam
spam = "global spam"

spam = "test spam"


do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)

scope_test()
print("In global scope:", spam)

In [ ]:

Try,Except
In [ ]: try :
print(a)
except:
print("Error.Undefined var")

Import and module


In [ ]: import math
#Importing module math
print("The value of pi is", math.pi)

In [ ]: # import module by renaming it


import math as m
print("The value of pi is", m.pi)

In [ ]: #Import using from


from math import pi
print("The value of pi is", pi)

In [ ]: #Import all


from math import *
Processing math: 100%
print("The value of pi is", pi)

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 40/43
9/21/2019 Python_Fundamentals

In [ ]: #Lists all functions avaialbe from math module


dir(math)

In [ ]: '''
Custom Module
===============
#Example_mod.py
def fun1(a,b):
print("Sum = {a+b}")
================
#Main.py
import example_mod
example_mod.fun1(10,20)
'''

In [ ]: def stuff():


print("Hello")
return
print("World")

stuff()

def addv(a,b):
add1 = a + b
return a

x = addv(2,7)
print(x)

In [ ]: def computepay1(h,r):


if h > 40:
return ((40) + ((h-40)*1.5)) * (r)
else:
return (h * r)

hr = int(input("Enter Hours:"))
rt = float(input("Enter rate per hour:"))

pay = computepay1(hr,rt)

print("Pay:",pay)

In [ ]: n = 0
while n > 0:
print("Test")

Regular Expression

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 41/43
9/21/2019 Python_Fundamentals

In [ ]: #Regular Expression


import re
handle = open('mbox-short.txt','r')
count = 0
for i in handle:
if count > 5:
break
i = i.rstrip()
#Search for any line containing 'From:'
if re.search('From:',i):
print(i)
count +=1
handle.close()
print("="*50)
handle = open('mbox-short.txt','r')
count = 0
for i in handle:
if count > 3:
break
i = i.rstrip()
#Search for any line starting with From
if re.search('^From:',i):
print(i)
count +=1
handle.close()
print("="*50)

In [ ]:

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 42/43
9/21/2019 Python_Fundamentals

Processing math: 100%

localhost:8888/notebooks/Desktop/Files/Python/Python_Fundamentals.ipynb 43/43

You might also like