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

Notebook Python Crash Course

The document provides an introduction to Python basics including variables, data types, operators, conditional statements, loops, functions, modules and exceptions. It covers key concepts like strings, lists, tuples, dictionaries, sets and files. Examples are provided throughout to demonstrate the concepts.

Uploaded by

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

Notebook Python Crash Course

The document provides an introduction to Python basics including variables, data types, operators, conditional statements, loops, functions, modules and exceptions. It covers key concepts like strings, lists, tuples, dictionaries, sets and files. Examples are provided throughout to demonstrate the concepts.

Uploaded by

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

Python_Crash_Course

May 20, 2021

1 Python Crash Course

2 Basics
• First Program
• Arithmetic Operation
• Variables
• Strings
• Comments
• List
• Tuple
• Dictionary
• Set

2.1 The Very First Program


[ ]: print("Hello World! we are going to dive in Python")

Hello World! we are going to dive in Python

[ ]: print('HI this is Vishwas \n book')

HI this is Vishwas
book
You can use it as Calculator

2.2 Arithmatic Operation


5+5 = 10
[ ]: 5+17834

[ ]: 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)

Data Science for Beginners

[ ]: message = "Python is Great!"


print(message)

Python is Great!

[ ]: message = "Hello Python Crash Course reader!"


print(message)

Hello Python Crash Course reader!

[ ]: a = 2
b = 3
sum = a+b
print(sum)

[ ]: a = '34.5'
print(type(a))

<class 'str'>

2.3.1 Taking input from users


The input() function pauses your program and waits for the user to enter some text.

[ ]: message = input("Enter any message: ")


print(message)
print(type(message))

2
Enter any message: hi
hi
<class 'str'>

[ ]: age = input("How old are you? ")


print("My age is: ", age)

How old are you? 23


My age is: 23

[ ]: age = input("How old are you? ")


age > 18

[ ]: age = int(input("How old are you? "))


age >= 18

How old are you? 24

[ ]: True

[ ]: x = input("Enter a number: ")


y = x + 5
print(y)

[ ]: print(type(x))

<class 'str'>

[ ]: x = input("Enter a number: ")


y = x + "5"
print(y)

Enter a number: 8
85

[ ]: x = int(input("Enter a number: "))


y = x + 5
print(y)

Enter a number: 3
8

[ ]: message = "Hello Python Crash Course reader!"


print(mesage)

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

[ ]: name = "data science"


print(name)
type(name)

data science

[ ]: str

[ ]: name = "data science"


print(name.title())

Data Science

[ ]: name = "Data Science"


print(name.upper())
print(name.lower())

2.4.1 Combining or Concatenating Strings

[ ]: fname = input("Enter your first name: ")


lname = input("Enter your last name: ")
name = fname+" "+lname
print("Hello! "+name.title())

Enter your first name: vishwas


Enter your last name: srivastava
Hello! Vishwas Srivastava

[ ]: print("Languages:\n\tPython\n\tC\n\tJavaScript")

[ ]: favorite_language = ' python '


#favorite_language
#favorite_language.rstrip()
#favorite_language
#favorite_language.lstrip()
favorite_language.strip()

[ ]: 'python'

Concatination of String and Integer:

4
[ ]: age = 23
message = "Happy " + str(age) + "rd Birthday!"
print(message)

Happy 23rd Birthday!

[ ]: print(len(message))

20

2.5 Comments
[ ]: # Say hello to everyone.
print("Hello Python people!")

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)

# len function to count the number of elements


n = len(bikes)
print("No. of bikes available: ",n)

['Honda', 'Hero', 'TVS', 'Bajaj', 'Suzuki']


No. of bikes available: 5

[ ]: print(bikes[0])

Honda

[ ]: print(bikes[-1])

[ ]: print(bikes[-2])

Bajaj

[ ]: # changing the value


bikes = ['Honda', 'Hero', 'TVS', 'Bajaj', 'Suzuki']
print(bikes)

bikes[0] = 'Yamaha'
print(bikes)

5
['Honda', 'Hero', 'TVS', 'Bajaj', 'Suzuki']
['Yamaha', 'Hero', 'TVS', 'Bajaj', 'Suzuki']

[ ]: # append the element


bikes.append('Ducati')
print(bikes)

['Yamaha', 'Hero', 'TVS', 'Bajaj', 'Suzuki', 'Ducati']

[ ]: # inserting at perticular position


bikes = ['Honda', 'Hero', 'TVS', 'Bajaj', 'Suzuki']
bikes.insert(1, 'Ducati')
print(bikes)
temp = bikes[0]
bikes[0] = bikes[1]
bikes[1] = temp
print(bikes)

['Honda', 'Ducati', 'Hero', 'TVS', 'Bajaj', 'Suzuki']


['Ducati', 'Honda', 'Hero', 'TVS', 'Bajaj', 'Suzuki']

[ ]: # removing element from list


del bikes[2]
print(bikes)

['Ducati', 'Honda', 'TVS', 'Bajaj', 'Suzuki']

[ ]: # removing element by value


bikes.remove('TVS')
print(bikes)

['Ducati', 'Bajaj', 'Suzuki']

[ ]: # slicing of list
bikes = ['Honda', 'Hero', 'TVS', 'Bajaj', 'Suzuki']
print(bikes[1:3])

['Hero', 'TVS']

[ ]: print(bikes[2:])

['TVS', 'Bajaj', 'Suzuki']

[ ]: 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

[ ]: # can you change the element


dimensions[0] = 250

[ ]: # wait! we can reinitialize the tuple variable


dimensions = (300, 40)
print(dimensions)
dimensions[1] = 100

[ ]: # you can perform all operation just like a list


# except assignment
bikes = ('Honda', 'Hero', 'TVS', 'Bajaj', 'Suzuki')
# print(bikes[:3])
print(len(bikes))
type(bikes)

[ ]: 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)

{'Raju': 90, 'Rani': 95}

[ ]: grades = {"Suresh":85, "Seema": 95}


print(grades)

{'Suresh': 85, 'Seema': 95}

7
[ ]: print(grades["Suresh"])

85

[ ]: # adding new item to dictionary


grades["Mohan"] = 76
print(grades)

{'Suresh': 85, 'Seema': 95, 'Mohan': 76}

[ ]: print(len(grades))

[ ]: # modifying grades
grades["Suresh"] = 98
print(grades)

{'Suresh': 98, 'Seema': 95, 'Mohan': 76}

[ ]: # removing item
del grades["Seema"]
print(grades)

{'Suresh': 98, 'Mohan': 76}

[ ]: favorite_languages = {
'Raju': 'python',
'Rani': 'c',
'Suresh': 'ruby',
'Seema': 'python',
}

print("Raju's favorite language is " +


favorite_languages['Raju'].title() +
".")

Raju's favorite language is 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)

2.10 Control Flow


It is the order in which individual statements, instructions or function calls

2.10.1 The if statement


if condition:
Statement 1
Statement 2
[ ]: # if statement
age = int(input("Enter your age: "))
if age >= 18:
print("You are old enough to vote!")

12
Enter your age: 12

[ ]: age = int(input("Enter your age: "))


if age >= 18:
print("You are old enough to vote!")

Enter your age: 18


You are old enough to vote!

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!")

Enter your age: 24


You are old enough to vote!
Have you registered to vote yet?

2.10.3 The if-elif-else Chain


if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Many real-world situations involve more than two possible conditions. For example, consider an
amusement park that charges different rates for different age groups:
• Admission for anyone under age 4 is free.
• Admission for anyone between the ages of 4 and 18 is $5.
• Admission for anyone age 18 or older is $10.

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.")

Enter your age: 23


Your admission cost is $10.

[ ]: age = int(input("Enter your age: "))


if age < 4:
price = 0
elif age < 18:
price = 5
else:
price = 10
print("Your admission cost is $" + str(price) + ".")

Enter your age: 12


Your admission cost is $5.

2.10.4 While Loop


With the while loop we can execute a set of statements as long as a condition is true.
while condition:
statements
[ ]: # while loop
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1 # a += 1 ---> a = a+1

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

[ ]: prompt = "\nTell me something, and I will repeat it back to you:"


prompt += "\nPress n to quit. "
message = ""
while message != 'n':
message = input(prompt)
print(message)

[ ]: # break
number = int(input("Enter any number: "))
loop_number = 1
while loop_number <= 10:
product = number * loop_number

if product > 20:


break

print(str(number) + " X " + str(loop_number) + " = " + str(product))


loop_number += 1

[ ]: # 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

[ ]: # loop through the letters in the word "banana":


for x in "banana":
print(x, end=" ")

b a n a n a

[ ]: cars = ['audi', 'bmw', 'subaru', 'toyota']

for car in cars:


if car == 'bmw':
print(car.upper())
else:
print(car.title())

Audi
BMW
Subaru
Toyota

[ ]: # using the range() function:


for x in range(10):
print(x, end=',')

0,1,2,3,4,5,6,7,8,9,

[ ]: # using the start parameter:


for x in range(2, 6):

16
print(x)

2
3
4
5

[ ]: # Increment the sequence with 3 (default is 1):


# range(start, end-1, steps)
for x in range(0, 101, 10):
print(x, end=" ")

0 10 20 30 40 50 60 70 80 90 100

[ ]: l1 = ['black', 'white', 'yellow']


l2 = ['laptop', 'table', 'book']

# 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()

[ ]: # Passing Information to a Function


def greet_user(username):
print("Hello, " + username.title() + "!")

# calling with parameters


greet_user("vishwas")

Try it yourself

17
[ ]: # Passing Information to a Function
def greet_user(fname, lname):
print("Hello, " + fname.title() + " " + lname.title() + "!")

# calling with parameters


greet_user("vishwas","srivastava")

Passing an Arbitrary Number of Arguments


Sometimes you won’t know ahead of time how many arguments a function needs to accept. For-
tunately, Python allows a function to collect an arbitrary number of arguments from the calling
statement.
[ ]: def make_pizza(*toppings):
# doc string
"""Print the list of toppings
that have been requested."""
print(toppings)

# 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

[45]: def add(x, y):


return x+y

add(9, 19)

[45]: 28

[46]: def square(x):


return x ** 2

num = int(input("Enter a number to finds its square: "))


sqr = square(num)
print("Square of "+str(num)+" is: "+str(sqr))

Enter a number to finds its square: 9


Square of 9 is: 81
TRY IT YOURSELF
Write a function that accepts length and breadth of rectangle as arguments, and calculate Area
and Perimeter of that rectangle.

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

[ ]: cars = ['bmw', 'audi', 'toyota', 'subaru','suzuki']


cars.sort()
print(cars)

[ ]: numbers = [3, 4, 1, 6, 5, 9, 2, 0]
numbers.sort()
print(numbers)

[50]: # using reverse


cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)

19
print(cars)

['toyota', 'subaru', 'bmw', 'audi']


TRY IT YOURSELF
Reverse the order of list of your choice
You can reverse the order by just:
variable_name.reverse()
Sorting a List Temporarily with the sorted() Function

[52]: # use of sorted method


cars = ['bmw', 'audi', 'toyota', 'subaru']

print("Here is the original list:")


print(cars)

print("\nHere is the sorted list:")


print(sorted(cars))

print("\nHere is the original list again:")


print(cars)

Here is the original list:


['bmw', 'audi', 'toyota', 'subaru']

Here is the sorted list:


['audi', 'bmw', 'subaru', 'toyota']

Here is the original list again:


['bmw', 'audi', 'toyota', 'subaru']

3.2 List Comprehensions


Frequently, you’ll want to transform a list into another list, by choosing only certain elements,or
by transforming elements, or both.
[56]: # even number list
even_numbers = [x for x in range(21) if x % 2 == 1]
print(even_numbers)

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

[59]: # square list


squares = [x * x for x in range(10,21)]
print(squares)

[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)

[ ]: square_set = { x * x for x in range(-5, 6) }


print(square_set)
print(len(square_set))

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]: """The random.random() method returns a random


float number between 0.0 to 1.0.
The function doesn't need any arguments."""
rm.random()

[72]: 0.5043620912134686

[77]: # Generate Random Integers


rm.randint(1, 100)

[77]: 35

[79]: rm.randrange(1, 100)

[79]: 31

[86]: # randrange(start, stop, step)


rm.randrange(0, 51, 10)

[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

[95]: [45, 65, 12, 43, 23, 67]

TRY IT YOURSELF
Generate random even numbers between 0-50 (both 0 and 50 are inclusive)and print then sort and
print

3.4 Object-Oriented Programming


In object-oriented programming you write classes that represent real-world things and situations,
and you create objects based on these classes.
class ClassName:
<statement-1>
.
.
<statement-N>
[ ]: # By convention, capitalized names refer to classes in Python.
class MyClass:
x = 5

[101]: obj1 = MyClass()


print(obj1.x)

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 Properties


#del p1.age

# 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))

p1 = Person("Vishwas", 30, 12345)


p1.myfunc()

Hello my name is Vishwas


My age is: 30
Contact me on: 12345

[121]: # Creating Multiple Instances


class Person:
def __init__(self, name, age):
self.name = name
self.age = age

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)

#Use the Person class to create an object,


#and then execute the print_name method:

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!")

You can't divide by zero!

[ ]: print("Give me two numbers, and I'll divide them.")


print("Enter 'q' to quit.")

while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break

second_number = input("Second number: ")


if second_number == 'q':
break

answer = int(first_number) / int(second_number)


print(answer)

[ ]: print("Give me two numbers, and I'll divide them.")


print("Enter 'q' to quit.")

while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break

second_number = input("Second number: ")


if second_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

You might also like