L O A D I N G
blog banner

JULY Weekend Data Science

print(); print(3+5*25+ 100); print(‘3+5*2-5+100 ‘)
print(‘3+5*2-5+100=’, 3 + 5*25+100) #parameters = 2
print(‘3+5*2-5+100=’,3+5*25+100, “Hello”,5*2)
# Comments – this for humans not for computer
# indentation is mandatory in Python

#Process finished with exit code 0 = Exit code 0 means no error as expected

#variable
value1 = 50 #defining a varaible called value1
# lets tale value1 and assume its value is 50
print(value1)
print(“Value1 =”,value1)
value1 = 100
print(“Value1 =”,value1)

value1 = “HELLO”
print(“Value1 =”,value1)

#Basic types of data in Python
# type()
value1 = 50
print(type(value1)) # <class ‘int’>

# int -> integer: -9999999, -87866,0,1,1000,4534563463
#
value1 = 50.0
print(type(value1)) #<class ‘float’>
# e.g. of float: 0.0, -9,0, 89.8777777777777777
print(5+3)
print(5+3.0)
## indentation, ; variables, int, float, type()

# 3. complex
# square root of -1 called complex numbers, example:
num1 = 5j
print(type(num1) ) # <class ‘complex’>
print(num1)
print(num1 * num1)
print(“===========”)
#4. str – string (text)
num1 = “hell” \
“o”
print(num1)
print(type(num1) ) #<class ‘str’>

num1 = ‘5.6’
print(type(num1) )
num1 = “””hello”””
print(type(num1) )
num1 = ”’How
are
you?”’
print(type(num1) )
print(num1)

# 5. bool (boolean): True or False
val1 = True
print(type(val1))

# # # #
# variable names in Python – should always begin with alphabet
# it accepts, alphabets, digits and _
a=5
b=10
c=a+b
print(c)

awetrwetwetwe=5
bveryaDAGDBBB=10
cYTIUYOYUOJJDHJGN= awetrwetwetwe + bveryaDAGDBBB
print(cYTIUYOYUOJJDHJGN)

num1 = 10
num2 = 5
total = num1 + num2
print(total)

# # # # #
cost_of_each_pen = 59
total_pens = 16
total_cost = cost_of_each_pen * total_pens
print(“Total cost = “,total_cost)
print(“Cost of each pen is”,cost_of_each_pen,“so the cost of”,total_pens,“pens will be”,total_cost)
#above output using format string (f-string)
print(f”Cost of each pen is {cost_of_each_pen} so the cost of {total_pens} pens will be {total_cost})
print(“Cost of each pen is {cost_of_each_pen} so the cost of {total_pens} pens will be {total_cost}”)

total_pens = 3
total_cost = 100
cost_of_each_pen = total_cost / total_pens
print(“Total cost = “,total_cost)
print(“Cost of each pen is”,cost_of_each_pen,“so the cost of”,total_pens,“pens will be”,total_cost)
#above output using format string (f-string)
print(f”Cost of each pen is {cost_of_each_pen:.2f} so the cost of {total_pens} pens will be {total_cost})
print(“Cost of each pen is {cost_of_each_pen} so the cost of {total_pens} pens will be {total_cost}”)

name,country,position = “Virat”,“India”,“Opener”
print(f”Player {name:>15}, plays for the country {country:^20} at {position:<20})
name,country,position = “Manbagwama”,“New Zealand”,“Wicket-Keeper”
print(f”Player {name:>15}, plays for the country {country:^20} at {position:<20})

# operators: Arithematic operations
## + – * / // (integer division) ** (power) %(modulus – remainder)
num1 = 56
num2 = 3
print(num1 + num2)
print(num1 – num2)
print(num1 * num2)
print(num1 / num2)

print(num1 // num2)
print(num1 % num2)
print(num1 ** num2)

print(100 ** (1/2))

# Relational, Logical, Membership

## Assignments ##
# WAP to calculate area and perimeter of a rectangular field when length and breadth are given
# WAP to calculate area and circumference of a circular field when radius is given

DAY 2 : Recording Basic Python


# Comparison / Relational Operators
# check relationship: > < >= <= == !=
# output is bool (True / False)
var1, var2, var3 = 10,20,10 #lets assign value 10 to var1
print(var1 > var2) # False
print(var1 > var3) # False
print(var1 < var2) # True
print(var1 < var3) #False
print(var1 >= var2) #False
print(var1 >= var3) #True
print(“===============”)
print(var1 <= var2) # True
print(var1 <= var3) # True
print(var1 == var2) #False – is var1 equal to var2 ?
print(var1 == var3) #True
print(var1 != var2) # True
print(var1 != var3) # False

# Logical operator: and or not
# input and output are bool
# prediction: Rohit and Surya will open the batting – False
# actual: Ishan and Surya opened the batting
# in AND, even if one is False entire thing becomes False
# prediction: Rohit or Surya will open the batting – True
# actual: Ishan and Surya opened the batting
# in OR, even if one is True entire thing becomes True
print(True and True) #True
print(False and False) #False
print(False and True) #False
print(True and False) #False

print(True or True) #True
print(False or False) #False
print(False or True) #True
print(True or False) #True

##
print(“check”)
var1, var2, var3 = 10,20,10
print(var1 > var2 and var1 > var3 or var1 < var2 and var1 == var3 or var1 != var2 and var1 <= var3)
#(T or T)
print(not True)
print(not False)

# Membership operator: in , not in
print(“i” in “india”)

# looping – when you run a block of code multiple times
## keep looping till yot get the stopping condition – WHILE loop
## exatly how many times to run a code: FOR loop

# if is to check the conditoon
num=8
# condition – usng if
if num ==8:
print(“Value is “,num)
print(“if is executed now”)

# you can have only IF
# or when you have something to talk about when IF is false – ELSE
if num ==18:
print(“Value is “,num)
print(“if is executed now”)
else:
print(“I am in ELSE”)


#WAP to check if a number is positive or not
num = 5
if num >0:
print(“Number is positive”)
else:
print(“Number is not positive”)

# WAP to check if a number is odd or even
num = 11
if num%2!=0:
print(“Its odd number”)
else:
print(“Its even number”)

## input() – take input from the user
val1 = input(“Enter your marks: “)
print(“1. Data type of val1 is: “,type(val1))
val1 = int(val1) # int() float() bool() str() complex() – explicit conversion
print(“2. Data type of val1 is: “,type(val1))
print(“Value you entered is “,val1)



## WAP a program to input value from the user and check if it has 0 at the end
## Value = 57 – it doesnt have zero at the end
## value = 60 – it should say it has zero at the end.

value = int(input(“Enter the number:”))
if value %10==0:
print(“This has zero at the end”)
else:
print(“It doesnt have zero at the end”)

# if a number is positive or negative or zero
num = int(input(“Enter a number: “))
if num == 0:
print(“Number is zero”)
elif num < 0:
print(“Number is negative”)
else:
print(“Number is Positive”)

sum = 360
avg = sum/5

if avg >= 75:
print(“Grade is A”)
elif avg >=60:
print(“Grade is B”)
elif avg>=50:
print(“Grade is C”)
elif avg >=35:
print(“Grade is D”)
else:
print(“Grade is E”)



# if the score is more than 90, invite them for tea with director
avg = 98 #98: 2 88: 2 68: 3 & #98: 2 88: 1 68: 3

if avg >=80:
if avg >= 90:
print(“You are invited for tea @5pm auditorium”)
if avg >=95:
print(“You win President Award!”)
print(“A+ Grade”)
print(“Excellent result”)
print(“Great going!”)
elif avg >=60:
print(“A grade”)
elif avg >=40:
print(“B Grade”)
elif avg >=30:
print(“D Grade”)
else:
print(“Sorry you have failed”)
print(“Try again next time”)


# find the highest number of the given 3 numbers
Num1 = 99
Num2 = 78
Num3 = 123
if Num1 > Num2:
if Num1 > Num3:
print(f”For the assignment given by Swapnil Num1={Num1} value is highest”)
if Num2 > Num1:
if Num2 > Num3:
print(f”For the assignment given by Swapnil Num2={Num2} value is highest”)
if Num3 > Num1:
if Num3 > Num3:
print(f”For the assignment given by SwapnilNum3={Num3} value is highest”)
## ##
num1 = 198
num2 = 198
num3 = 168

if num1 > num2:
if num1 > num3:
print(“{num1} is greater”)
else:
print(“{num3} is greater”)
else:
if num2 >num3:
print(“{num2} is greater”)
else:
print(“{num3} is greater”)

###
num1 = 98
num2 = 128
num3 = 168
high = num1
if high < num2:
high = num2
if high <num3:
high = num3
print(f”{high} is the highest”)


# WAP to input 3 sides of a triangle and find if its a equilateral, isoceles or scalene
num1 = 128
num2 = 128
num3 = 128
s1=num1; s2=num2; s3=num3
if s1==s2:
if s2==s3:
print(“As all 3 sides of triangle is equal hence it is an equilateral triangle”)
else:
print(“As 2 sides of an triangle are equal hence it is an isosceles triangle”)
else:
if s2==s3 or s3==s1:
print(“As 2 sides of an triangle are equal hence it is an isosceles triangle”)
else:
print(“As no sides are equal it is an scalene triangle”)


num1 = 128
num2 = 108
num3 = 128

if num1 == num2:
if num1 == num3:
print (“equilateral triangle”)
else:
print(“isoscales triangle”)
else:
if num2 == num3 or num1==num3:
print (“isoscales triangle”)
else:
print(“scalene triangle”)

## below: bad example of the code
num1 = 128
num2 = 108
num3 = 128

if num1 == num2 and num1==num3:
print (“equilateral triangle”)
if (num1 == num2 and num2!=num3) or (num1==num3 and num3!=num2) or (num2==num3 and num3!=num1):
print (“isoscales triangle”)
if (num1 !=num3 and num1!=num2) or (num2 !=num1 and num2!=num3) or (num3 !=num1 and num2!=num3):
print(“scalene triangle”)

# for loop
# range(a,b,c): a=start, b< end (upto, not equal to), c = increment
#range(2,12,3)# generates range of values- 2,5,8
# range(a,b) default c value is ONE
#range(5) #default start = 0, increment =1: 0,1,2,3,4

for counter in range(10):
print(counter)

# while: loops until the given condition
z=0
while z<=10:
print(z)
z=z+ 1
# divisible by 100 & 400 – leap year, divisible by 100 but not 400 – not a leap year
# divisible by 100 but divisible by 4 – leapyear

year = 400
if year %100==0:
if year %400==0:
print(“Leap Year”)
else:
print(“Not a leap year”)
else:
if year %4==0:
print(“Leap Year”)
else:
print(“Not a leap Year”)

####
a,b,c,d = 40,10,20,5
small = a
if b <small:
small=b
if c <small:
small=c
if d <small:
small=d

num=str(1234567)
print(“Number of characters = “,len(num))
num = 158
length = 1
a = num//10
if a!=0:
length+=1 # length = length + 1
num = num//10

a = num//10
if a!=0:
length+=1 # length = length + 1
num = num//10

a,b,c=20,10,30

if a < b:
a,b=b,a
if b < c:
if a>c:
print(c, “is second highest”)
else:
print(a,“is second highest”)
else:
print(b,“is second highest”)

eng = 85
maths,science,ss = 90,90,80
if eng >=80:
if ss>=80:
if maths>=80 and science >= 80:
print(“Science Strean”)
else:
print(“Humanities Stream”)
elif maths >= 50 and science >= 50:
print(“Commerce”)

else:
print(“Admission not possible”)
# loops – repeat multiple times
# for: used when you know how many times to repeat
# while: in which conditions to repeat

#range(): which generates range of values
# range(=start, <end, increment)
# range(3,11,2): 3,5,7,9
# range(=start, <end) : increment is default 1
# range(5,9): 5,6,7,8
# range(<end): default start = 0 & increment is 1
# range(4): 0,1,2,3

for counter in range(3,11,2):
print(“Counter = “,counter)
print(“Hello”)

#print even numbers from 6 to 20
for i in range(6,21,2):
print(i,end=“, “)
print()

# find sum of numbers between 5 and 9 both including
sum=0
for i in range(5,10):
sum+=i
print(“Sum = “,sum)

# generate first 4 multiples of 5: 5 10 15 20
num = 15
for j in range(4):
print(f”{num} * {j+1} = {num*(j+1)})

print(“WHILE : condition based repeation”)
count = 1
while count <=8:
count += 2
print(count)

# print hello till user says yes

while True:
print(“HELLO”)
ch = input(“Enter y to print again or anyother key stop: “)
if ch!=‘y’:
break

”’
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
”’
print(“Pattern 1”)
for j in range(5):
for i in range(5):
print(“*”, end=” “)
print()

”’
*
* *
* * *
* * * *
* * * * *
”’
print(“Pattern 2”)
for j in range(5):
for i in range(j + 1):
print(“*”, end=” “)
print()

”’
* * * * *
* * * *
* * *
* *
*
”’
print(“Pattern 3”)
for j in range(5):
for i in range(5 – j):
print(“*”, end=” “)
print()

”’
Assignment 1:
* * * * *
* * * *
* * *
* *
*

Assignment 2:
*
* *
* * *
* * * *
* * * * *

Assignment 3: Multiplication Table:

1 * 1 = 1 2 * 1 = 2 … 10 * 1 = 10
1 * 2 = 2 2 * 2 = 4 10 * 2 = 20

1 * 10 = 10 2 * 10 = 20 10 * 10 = 100
”’

## Check if Prime or not
num = 53
isPrime = True
for i in range(2, num // 2 + 1):
if num % i == 0:
isPrime = False
break

if isPrime:
print(f”{num} is Prime”)
else:
print(f”{num} is not Prime”)

import time
curr = time.time()
line = 0
## Generate Prime numbers between 20000 and 30000
for num in range(20000,30001):
isPrime = True
for i in range(2,num//2+1):
if num % i==0:
isPrime = False
break

if isPrime:
if line >= 20:
print()
line = 0
print(num, end=“,”)
line+=1
end = time.time()
print(\n\nTotal time taken to generate prime numbers is “,end-curr,“seconds”)
print(“Time is: “,time.time())
”’
1*1 = 1 2 * 1 = 2 …
1 * 2..

1 * 10

”’
s=0
for i in range(1,11,1):
s += 1 # s=s+1
for j in range(1,11):
print(f”{j:<2}*{i:>2}={j*i: <3}, end=” “)

print()

print(“S = “, s)
## WHILE LOOP
num = 1
ch = “y”
while ch==“y”:
num+=1
ch=input(“Enter y to continue or anyother key to stop: “)

print(“num = “,num)
##
# Menu option
while True:
print(“Now, pick up the option:”)
print(“1. Addition”)
print(“2. Subtraction”)
print(“3. Multiplication”)
print(“4. Division”)
print(“5. Quit”)
choice = int(input(“Enter your option from the above menu:”))

if choice>=1 and choice <=4:
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))

if choice==1:
print(“Addition of given numbers: “,num1+num2)
elif choice==2:
print(“Subtraction of given numbers: “,num1-num2)
elif choice==3:
print(“Multiplication of given numbers: “,num1*num2)
else:
print(“Division of given numbers: “,num1/num2)
elif choice==5:
break
else:
print(“Invalid option, try again!”)

##
”’
Guess the number game!
Computer v Human

Module: has collection of related functions
randint(1,100) – will return random integer number between 1 and 100 (both including)
”’
import random

num = random.randint(1, 100)
attempt = 0
while True:
guess = int(input(“Guess the number: “))
if guess < 1 or guess > 100:
print(“Invalid guess, try again”)
continue

attempt += 1
if num == guess:
print(f”Congratulations! You guessed it right in {attempt} attempts.”)
break
elif num < guess:
print(f”Your {guess} is higher.. try with a lower guess!”)
else:
print(f”Your {guess} is lower.. try with a higher guess!”)
”’
Guess the number game!
Computer v Computer

Module: has collection of related functions
randint(1,100) – will return random integer number between 1 and 100 (both including)
”’
import random
import time

start = time.time()
num = random.randint(1,100)
low,high =1,100
attempt = 0
while True:
guess = random.randint(low,high)
attempt+=1
if num==guess:
end = time.time()
print(f”Congratulations! You guessed it right in {attempt} attempts and in {end-start} seconds.”)
break
elif num < guess:
print(f”Your {guess} is higher.. try with a lower guess!”)
high = guess-1
else:
print(f”Your {guess} is lower.. try with a higher guess!”)
low = guess + 1

## ### ### ##
”’
WAP a Program to generate prime numbers from 1 till user continue to ask
2
you want more? y
3
you want more? y
5
you want more? y
7
you want more? y
11
you want more? n
Thank you

”’
num = 1
while True:
num+=1
isPrime = True
for i in range(2,num//2+1):
if num%i==0:
isPrime=False
break
if not isPrime:
continue
print(num)
ch=input(“you want more (y for yes)?”)
if ch!=“y”:
break
## ##
## STRINGS
str1 = ‘Hello’ # one line text
str2 = “Hi there” # one line text
str3 = ”’How are you?
Where are you?
How you doing?”’ # multiline text
str4 = “””I am fine
I am here
i am great””” # multiline text
print(type(str1),type(str2),type(str3),type(str4))
print(str1,\n,str2,\n,str3,\n,str4)

# \n is used for newline
# \ – escape character { this will add power / remove power if you have power}
# \\ – will make one \
print(\\n is used for newline \\t is used for Tab spaces \\c has not meaning”)

# \\n \\t \\c
print(\\\\n \\\\t \\\\c”)
## STRING
str1 = “hello 5”
str2 = “how are you”
# he asked,”how are you?”
print(‘he asked,”how are you?”‘)
print(“he asked,\”how are you?\”)
# he asked,”what’s your name?”
print(‘he asked,”what\’s your name?”‘)
print(str1 + ” “+ str2)
print((str1+” “)*5)

for i in str1:
print(i)

# len() – will tell you the length of the variable
print(f”Number of elements in {str1} is”,len(str1))

for i in range(len(str1)):
print(i, ” – “,str1[i])

# indexing: accessing the member from a string /data collection
str1 = “helloshnrtmd”
print(str1[0])
last_idx = len(str1) – 1
print(str1[-1])
# str1[0] = “H” – error

# string is immutable – you cant edit
a=5
a=6
str1 = “hello”
str1 = “Hello”
print(“ell”, str1[1:4], str1[-4:-1])
print(“Hell”,str1[0:4],str1[:4], str1[:-1])
print(“ello”,str1[1:5],str1[1:], str1[-4:])

# Functions (global) and Methods (specific to the class)
str1 = “HelLo how are you”
str2 = “hello”
anything =
print(“Lower: “,str1.lower())
print(“Uppercase: “,str1.upper())
print(“STR1 = “,str1)
print(“Title Case: “, str1.title())
print(str2.islower())
print(str2.upper().isupper())
print(str2.isalnum())
print(str2.isdigit())

num1 = input(“Enter length of the rectangle: “)
if num1.isdigit():
num1 = int(num1)
else:
print(“Invalid number”)

# modify below program to accept space also
name = input(“Enter your name: “)
if name.isalpha():
print(“Name accepted”)
else:
print(“Invalid name”)
# modify below program to accept space also
name = “Sachin Tendulkar”
if name.isalpha():
print(“Name accepted”)
else:
print(“Invalid name”)

output = name.split() #split by default will split on ‘ ‘
output_str = “”.join(output)
print(output_str)
if output_str.isalpha():
print(name,“Name accepted”)
else:
print(“Invalid name”)

print(“Strip —“)
txt = ” 2 4 6 8 “
print(txt.strip(), “length is”,len(txt.strip()))

# replace find count
print(“blank spaces are:”,txt.count(” “))
txt2 = “Twinkle Twinkle Twinkly Star”
print(“Count Twin: “,txt2.count(“Twin”))
print(“Find Twin: “,txt2.find(“Twin”))

# Print the position of all the occurrences
st=0
for i in range(txt2.count(“Twin”)):
cnt = txt2.find(“Twin”,st)
print(“Find Twin: “, cnt)
st = cnt+1

txt2 = “Twinkle Twinkle Twinkly Star”
txt3 = txt2.replace(“Twin”,“Quin”)
print(txt3)
txt3 = txt2.replace(“Twin”,“Quin”,2)
print(txt3)
print(“Check if txt2 starts with t: “,txt2.startswith(“t”))
print(“Check if txt2 starts with t: “,txt2.startswith(“T”))
print(“Check if txt2 starts with t: “,txt2.endswith(“r”))
print(“Check if txt2 starts with t: “,txt2.endswith(“R”))


# LIST: linear mutable ordered collection
l1 = []
print(type(l1))
l1 = [3,4,6,8,9]
print(“Getting last 3 values:”)
print(l1[2:])
l1[0]=0
print(l1)

l2 = [“Hello”, 45, 66.6, 5j , True, [5,10,15,20]]
print(l2)
print(type(l2))
print(type(l2[3]))

print([2,4,6]+[4,8,12])
print([2,4,6] * 5)

###
for i in l2:
print(i)

fare=[]
fare.append(50) # append is used to add members to a list at the end
fare.append(60)
fare.append(45)
fare.insert(1,77)
fare.insert(1,44)
print(“Fare = “,fare)

fare.pop(2)
print(“Fare = “,fare)
fare.remove(60)
print(“Fare = “,fare)
fare.clear()
print(“Fare = “,fare)

marks = []
tot = 0
for i in range(5):
m = int(input(“Enter marks = “))
marks.append(m)
tot+=m

print(“Marks = “,marks)
print(“Total marks is”,sum(marks))
print(“Total = “,sum(marks)/len(marks))

#LIST

”’
## Assignment: Implement Stack and Queue operations using List
Stack is called as – Last in First out structure (LIFO)

Queue: First In First Out (FIFO)

”’
l1 = [2,4,8,14,16]
num= 140
if l1.count(num) >0:
print(“Index: “,l1.index(num))
else:
print(f”{num} is not in the list”)

print(l1.index(14,2,6))
print(“0. L1 = “,l1)
l2 = l1.copy() # shallow copy – creates another copy
l3 = l1 # deep copy – another name for same data
print(“1. L1 = “,l1)
print(“1. L2 = “,l2)
print(“1. L3 = “,l3)
l1.append([18,20])
l1.append(20)
print(“2. L1 = “,l1)
print(“2. L2 = “,l2)
print(“2. L3 = “,l3)

l1.extend(l3) # l1 = l1 + l3
print(l1)

l4 = [5,9,1,4,2,3,6]
l4.reverse()
print(l4)
l4.sort()
print(l4)
l4.sort(reverse=True)
print(l4)

# [[4,6,8],[9,5,2],[5,9,1]] – find highest value at each position.
l1 = [[5, 6, 8], [5, 0, 0], [5, 9, 1]]
print(“the largest element is”, max(l1))

data = []
for i in range(3):
temp = []
for j in range(3):
val = int(input(“Enter value: “))
temp.append(val)
data.append(temp)

print(“Data = “,data)
# data = [[5, 4, 3], [6, 7, 5], [9, 8, 7]]
max_list = [-999,-999,-999]
for i in range(3):
for j in range(3):
if max_list[i] < data[j][i]:
max_list[i] = data[j][i]

print(max_list)

# Assignment 2: Find the highest element for each of the sub-list

# TUPLE: Linear immutable Ordered collection
t1 = (1,2,3)
print(type(t1))
print(t1.count(3))
print(t1.index(3))
# indexing is exactly same as Str/List
for i in t1:
print(i)
a,b,c = t1
print(a,b,c)
d = [(1,2,3,4,5,6),(1,2,3,4,5,6),(1,2,3,4,5,6),(1,2,3,4,5,6)]
t1 = list(t1)
t1 = tuple(t1)

## ##
# Dictionary: Linear mutable unordered collection
# dictionary is your key:value (key value pairs)
d1 = {“Name”:“Sachin”,“Runs”:21000,3:“Mumbai”, True:“Mumbai Indians”}
print(d1)
print(d1[“Name”])
d1[“Name”] = “Sachin Tendulkar”
print(d1)

d2 = d1 #deep copy
d3 = d1.copy() #shallow copy
print(“1. D1 = “,d1)
print(“1. D2 = “,d2)
print(“1. D3 = “,d3)
t = {“Country”:“India”}
d1.update(t)
print(“2. D1 = “,d1)
print(“2. D2 = “,d2)
print(“2. D3 = “,d3)

print(d1.keys())
print(d1.values())
print(d1.items())

for i in d1.keys():
print(i)
print(“================”)
for i in d1.values():
print(i)
print(“================”)
for i in d1.items():
print(i)
print(“================”)

for i,j in d1.items():
print(i,“:”,j)
print(“================”)

d1.pop(“Name”)
print(d1)
d1.popitem()
print(d1)

Leave a Reply

Your email address will not be published. Required fields are marked *