Revision
This revision has a companion notebook on Kaggle. Fork it and start learning hands-on!
In this section you will revise all the concepts learnt so far in snippets of code:
try, except, finally block
try: # try statement encloses statements which could throw an exception
# input function chained with float function
deposit_amount = float(input("Enter deposit amount:\t\t"))
interest_earned = float(input('Enter total interest earned:\t\t'))
interest_rate = (interest_earned/deposit_amount) * 100
# round function rounds the result to 2 decimal places
print("Rate of interest: \t\t"+ str(round(interest_rate, 2)))
except: # catch all exceptions if nothing is specified.
print("You entered an invalid integer. Please type a valid value")
finally:
# typically resources are released in this block
print("This will be executed no matter what")
for loop
for x in range(0, 3):
print("Hip hip hurray! %d" % (x))
output:
Hip hip hurray! 0
Hip hip hurray! 1
Hip hip hurray! 2
while loop
# while loop
x = 1.456
while True:
print("Integer value of x {:1.0f}".format(x))
print("Value of x rounded to 2 decimal points {:.2f}".format(round(x, 2)))
x += 1
if (x > 3):
break;
output:
Integer value of x 1
Value of x rounded to 2 decimal points 1.46
Integer value of x 2
Value of x rounded to 2 decimal points 2.46
def function
name = 'My name'
def myfunc(name):
print("hello there! " + name) # global name variable is replaced with the local name.
myfunc("Python")
output:
hello there! Python
not keyword
game_over = False
i = 1;
while not game_over:
print("playing " + str(i) + " time(s)")
i += 1
if (i > 2):
break
output:
playing 1 time(s)
playing 2 time(s)
Sending list to a function
# sending list to function
topics = ["numpy",'pandas',"seaborn"]
def displayTopics(topics):
for topic in topics:
print(topic)
displayTopics(topics)
output:
numpy
pandas
seaborn
List of lists - 2d
topics = [
['numpy', 1],
['pandas',2],
['seaborn',3]
]
print(topics)
print(topics[1][0])
output:
[['numpy', 1], ['pandas', 2], ['seaborn', 3]]
pandas
Tuples
# Tuples are immutable
t_tuples = ('numpy', "pandas", "seaborn")
print(t_tuples[0])
a,b,c = t_tuples #tuples can be unpacked into multiple assignment statements
print(b)
# tuples are more efficient than lists so for readonly structures use tuples
output:
numpy
pandas
String search
message = "Congratulations! you are all set to move on to numpy and pandas!"
print('you' in message)
print('congratulations' in message) # case sensitive
for char in "study":
print(char)
print(message.startswith("Congratulations"))
output:
True
False
s
t
u
d
y
True
String manipulations
numbers = "12345"
print(numbers.isdigit()) # Other functions; islower(), isupper(), isalpha()
message = "this is really easy!"
print(message.title())
phoneNumber = "123 234 3489 "
print(phoneNumber.strip() + ".")
print(phoneNumber.replace(" ", "-"))
print("(" + phoneNumber[:3] + ")"+ phoneNumber[4:7] + "-"+ phoneNumber[8:13])
print(phoneNumber.split(" "))
# Justifies to the given length by adding spaces to fill the gap
print("book".ljust(14), "$9.99".rjust(10))
print(message.upper())
output:
True
This Is Really Easy!
123 234 3489.
123-234-3489----
(123)234-3489
['123', '234', '3489', '', '', '', '']
book $9.99
THIS IS REALLY EASY!
datetime module
from datetime import date
from datetime import datetime
print(date.today())
print(datetime.now())
peace_day = datetime(1981, 9, 21, 17, 30)
print(peace_day)
print(peace_day.strftime("%Y/%m/%d"))
output:
[the date this program is run]
[the date and time this program is run]
1981-09-21 17:30:00
1981/09/21>
Dictionaries
are unordered collection. Keys are indexed, Key can be any immutable type and value can be any type including mutable types
countries = {'CA': "Canada",
"US":"United States",
"MX": "Mexico",
3:10
}
print (countries)
print(countries['CA'])
code = 'US'
if code in countries:
print(countries[code])
print(countries.get("mx")) # Case sensitive
print(countries.get("MX"))
countries['IN'] = "India"
print(countries['IN'])
countries['IN'] = 'Bharath'
print(countries['IN'])
del countries['MX']
print(countries)
countries.pop("IN") # You can use del, pop methods to remove an item from dictionary. clear() removes all items
print(countries)
print(countries.keys())
print(countries.values())
for name in countries.values():
print (name)
for code,name in countries.items(): # Unpack tuples
print(code , name)
output:
{'CA': 'Canada', 'US': 'United States', 'MX': 'Mexico', 3: 10}
Canada
United States
None
Mexico
India
Bharath
{'CA': 'Canada', 'US': 'United States', 3: 10, 'IN': 'Bharath'}
{'CA': 'Canada', 'US': 'United States', 3: 10}
dict_keys(['CA', 'US', 3])
dict_values(['Canada', 'United States', 10])
Canada
United States
10
CA Canada
US United States
3 10
More dictionary manipulations
# Convert dictionary to list
codes = list(countries.keys())
print(type(codes))
del codes[2] # remove the integer so sort can work
codes.sort()
print(codes)
output:
<class 'list'>
['CA', 'US']