Notebook Python Crash Course
Notebook Python Crash Course
2 Basics
• First Program
• Arithmetic Operation
• Variables
• Strings
• Comments
• List
• Tuple
• Dictionary
• Set
HI this is Vishwas
book
You can use it as Calculator
[ ]: 17839
[ ]: 5/2
1
[ ]: 2.5
[ ]: 1435//4
[ ]: 358
[ ]: 2**4
[ ]: 16
2.3 Variables
Variables are the names you give to computer memory locations which are used to store values in
a computer program.
[ ]: message = "Data Science for Beginners"
print(message)
Python is Great!
[ ]: a = 2
b = 3
sum = a+b
print(sum)
[ ]: a = '34.5'
print(type(a))
<class 'str'>
2
Enter any message: hi
hi
<class 'str'>
[ ]: True
[ ]: print(type(x))
<class 'str'>
Enter a number: 8
85
Enter a number: 3
8
3
2.4 String
A string is simply a series of characters.Anything inside quotes is considered a string in Python,
and you can use single or double quotes around your strings like this:
"This is a string."
'This is also a string.'
data science
[ ]: str
Data Science
[ ]: print("Languages:\n\tPython\n\tC\n\tJavaScript")
[ ]: 'python'
4
[ ]: age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)
[ ]: print(len(message))
20
2.5 Comments
[ ]: # Say hello to everyone.
print("Hello Python people!")
2.6 List
A list is a collection of items in a particular order.
[ ]: bikes = ['Honda','Hero','TVS','Bajaj','Suzuki']
print(bikes)
[ ]: print(bikes[0])
Honda
[ ]: print(bikes[-1])
[ ]: print(bikes[-2])
Bajaj
bikes[0] = 'Yamaha'
print(bikes)
5
['Honda', 'Hero', 'TVS', 'Bajaj', 'Suzuki']
['Yamaha', 'Hero', 'TVS', 'Bajaj', 'Suzuki']
[ ]: # slicing of list
bikes = ['Honda', 'Hero', 'TVS', 'Bajaj', 'Suzuki']
print(bikes[1:3])
['Hero', 'TVS']
[ ]: print(bikes[2:])
[ ]: print(bikes[:-3])
['Honda', 'Hero']
6
2.7 Tuples
Tuples are lists’ immutable cousins. You specify a tuple by using parentheses (or nothing) instead
of square brackets:
[ ]: dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
200
50
[ ]: tuple
2.8 Dictionaries
Another fundamental data structure is a dictionary, it allow you to connect pieces of related infor-
mation.It associates values with keys and allows you to quickly retrieve the value corresponding
to a given key:
[ ]: grades = {}
grades["Raju"] = 90
grades["Rani"] = 95
print(grades)
7
[ ]: print(grades["Suresh"])
85
[ ]: print(len(grades))
[ ]: # modifying grades
grades["Suresh"] = 98
print(grades)
[ ]: # removing item
del grades["Seema"]
print(grades)
[ ]: favorite_languages = {
'Raju': 'python',
'Rani': 'c',
'Suresh': 'ruby',
'Seema': 'python',
}
[ ]: "c" in favorite_languages
[ ]: False
2.9 Sets
Another data structure is set , which represents a collection of distinct elements:
SET
8
unindexed, unordered, mutable
Creating, Accessing, Updating and Deleting
CREATING A SET
[ ]: s = {1,3,5}
ACCESSING SET
[ ]: print(s)
{1, 3, 5}
[ ]: s1 = set()
[ ]: print(s1)
set()
[ ]: s2 = set([1,2,3])
[ ]: print(s2)
{1, 2, 3}
ADD ELEMENT IN SET
[ ]: s.add(6)
[ ]: print(s)
{1, 3, 5, 6}
TYPE
[ ]: s={1,3,5}
[ ]: print(type(s))
<class 'set'>
Duplicate Value
[ ]: s={1,2,3,4,4}
[ ]: print(s)
{1, 2, 3, 4}
UPDATEING
[ ]: s.update([8,9,10])
9
[ ]: print(s)
{1, 3, 5, 8, 9, 10}
DELETING ELEMENT
[ ]: s.discard(3)
[ ]: print(s)
{1, 5, 8, 9, 10}
[ ]: s.remove(5)
[ ]: print(s)
{1, 8, 9, 10}
[ ]: s.clear()
[ ]: print(s)
set()
[ ]: s={1,3,5}
[ ]: print(s)
{1, 3, 5}
MEMBERSHIP TEST
[ ]: print(3 in s)
True
[ ]: print(6 not in s)
False
COPYING SET
[ ]: s_copy=s.copy()
[ ]: print(s_copy)
{1, 3, 5}
FUNCTIONS
[ ]: s={1,3,5}
10
[ ]: s2={1,3,6}
[ ]: print(s&s2)
{1, 3}
[ ]: print (s.intersection(s2))
{1, 3}
[ ]: print(s|s2)
{1, 3, 5, 6}
[ ]: print (s.union(s2))
{1, 3, 5, 6}
[ ]: print(len(s))
[ ]: print(max(s))
[ ]: print(min(s))
[ ]: print(sum(s))
[ ]: s={1,2,0}
[ ]: print(s)
[ ]: print(all(s))
False
[ ]: s11={0,0,0,0,0,0}
[ ]: print(any(s11))
False
11
[ ]: s={2,3,'ABHISHEK'}
[ ]: print(s)
{'ABHISHEK', 2, 3}
[ ]: se={'abhishek', 'ABHISHEK'}
[ ]: print(max(se))
abhishek
Reason to use sets: The first is that in is a very fast operation on sets. If we have a large
collection of items that we want to use for a membership test, a set is more appropriate than a list:
stopwords_list = ["a","an","at"] + hundreds_of_other_words + ["yet", "you"]
"zip" in stopwords_list # False, but have to check every element
stopwords_set = set(stopwords_list)
"zip" in stopwords_set # very fast to check
The second reason is to find the distinct items in a collection:
[ ]: item_list = [1, 2, 3, 1, 2, 3]
num_items = len(item_list)
item_set = set(item_list)
num_distinct_items = len(item_set)
distinct_item_list = list(item_set)
print(item_list)
print(num_items)
print(item_set)
print(num_distinct_items)
print(distinct_item_list)
12
Enter your age: 12
2.10.2 if-else
if (condition):
Statement 1
Statement 2
else:
Statement 3
Statement 4
[ ]: # if-else
age = int(input("Enter your age: "))
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
13
[ ]: # The if-elif-else Chain
age = int(input("Enter your age: "))
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $5.")
else:
print("Your admission cost is $10.")
print()
print(current_number)
1
2
3
4
5
6
TRY IT YOURSELF
14
using while loop print the table like:
5 x 1 = 5
5 x 2 = 10
.
.
.
5 x 10 = 50
[ ]: # while loop
number = int(input("Enter any number: "))
loop_number = 1
while loop_number <= 10:
mul = number * loop_number
print(str(number) + " X " + str(loop_number) + " = " + str(mul))
loop_number += 1
[ ]: # break
number = int(input("Enter any number: "))
loop_number = 1
while loop_number <= 10:
product = number * loop_number
[ ]: # continue
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
[ ]: 8 % 5
[ ]: 3
15
2.10.5 For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or
a string).
This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
for iterator_var in sequence:
statements(s)
[ ]: # for loop
fruits = ["apple", "banana", "cherry", "mango"]
for x in fruits:
print(x.title())
Apple
Banana
Cherry
Mango
b a n a n a
Audi
BMW
Subaru
Toyota
0,1,2,3,4,5,6,7,8,9,
16
print(x)
2
3
4
5
0 10 20 30 40 50 60 70 80 90 100
# black laptop
# black table
# black book
# white laptop
# white table
# white book
2.11 Functions
These are named blocks of code that are designed to do one specific job. When you want to perform
a particular task that you’ve defined in a function, you call the name of the function responsible
for it. In Python a function is defined using the def keyword:
def function_name():
statements
[ ]: # Display a simple greeting.
def greet_user():
print("Hello!")
# function calling
greet_user()
Try it yourself
17
[ ]: # Passing Information to a Function
def greet_user(fname, lname):
print("Hello, " + fname.title() + " " + lname.title() + "!")
# function calling
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
()
('mushrooms', 'green peppers', 'extra cheese')
[ ]: def make_pizza(*toppings):
print("\nMaking a pizza with the following toppings:")
for x in toppings:
print("- " + x)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
TRY IT YOURSELF
Write a function that accepts a list of items a person wants on a sandwich. The function should
have one parameter that collects as many items as the function call provides,and it should print a
summary of the sand- wich that is being ordered. Call the function three times, using a different
num- ber of arguments each time.
[44]: def double(x):
"""this is where you put an optional docstring
that explains what the function does.
for example, this function multiplies its input by 2"""
return x * 2
double(13)
18
[44]: 26
add(9, 19)
[45]: 28
3 The Not-So-Basics
• Sorting
• List Comprehensions
• Randomness
• Object-Oriented Programming
• Exceptions
3.1 Sorting
Python’s sort() method makes it relatively easy to sort a list. Sorting a List Permanently with
the sort() Method
[ ]: numbers = [3, 4, 1, 6, 5, 9, 2, 0]
numbers.sort()
print(numbers)
19
print(cars)
[100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
20
TRY IT YOURSELF
Make a list of cubes between numbers 1-30
You can similarly turn lists into dictionaries or sets:
[ ]: square_dict = { x : x * x for x in range(10) }
print(square_dict)
3.3 Randomness
As we learn data science, we will frequently need to generate random numbers, whichwe can do
with the random module:
[71]: import random as rm
[72]: 0.5043620912134686
[77]: 35
[79]: 31
[86]: 0
[89]: random.choice('computer')
[89]: 'u'
[92]: random.choice([12,23,45,67,65,43])
[92]: 12
21
[95]: # The random.shuffle() method randomly
# reorders the elements in a list.
numbers=[12,23,45,67,65,43]
random.shuffle(numbers)
numbers
TRY IT YOURSELF
Generate random even numbers between 0-50 (both 0 and 50 are inclusive)and print then sort and
print
5
**The __ init __() Method**
A function that’s part of a class is a method. Everything you learned about functions applies to
methods as well; the only practical difference for now is the way we’ll call methods. The init()
method is a special method Python runs automatically whenever we create a new instance based
on the class. We define the init() method to have three parameters: self , name , and age . The self
parameter is required in the method definition, and it must come first before the other parameters.
[114]: class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Vishwas", 30)
print(p1.name, p1.age)
Vishwas 30
22
[107]: # Modify Object Properties
p1.age = 40
print(p1.age)
40
# Delete Object
del p1
print(p1.name)
print(p1.age)
[120]: # Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age, ph_no):
self.name = name
self.age = age
self.ph_no = ph_no
def myfunc(self):
print("Hello my name is " + self.name)
print("My age is: " + str(self.age))
print("Contact me on: " + str(self.ph_no))
def myfunc(self):
print("Persons: " + self.name)
p1 = Person("Vishwas", 30)
p2 = Person("Abhishek", 30)
p1.myfunc()
p2.myfunc()
23
Persons: Vishwas
Persons: Abhishek
The pass Statement
class definitions cannot be empty, but if you for some reason have a class definition with no content,
put in the pass statement to avoid getting an error.
[123]: class Person:
pass
Inheritance
When one class inherits from another, it automatically takes on all the attributes and methods of
the first class. The original class is called the parent class, and the new class is the child class. The
child class inherits every attribute and method from its parent class but is also free to define new
attributes and methods of its own.
[ ]: # parent class
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def print_name(self):
print(self.firstname, self.lastname)
p = Person("Vishwas", "Srivastava")
print("Faculty Name:")
p.print_name()
print("_"*20)
# child class
class Student(Person):
pass
s = Student("Raju", "Verma")
print("Student Name:")
s.print_name()
TRY IT YOURSELF
Create a program of inheritance of your choice
3.5 Exceptions
Python uses special objects called exceptions to manage errors that arise dur- ing a program’s
execution.
24
[ ]: print(5/0)
[128]: try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
TRY IT YOURSELF
what if a user press an alphabet other than ‘q’ how you can handle this sitiuation?
25