Python

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 96

S

W
A
M
I
K
E
S
H
V 2nd semester summer Internship report on
A
N
A
“python”
N
D

I
N
S
T
I
T Submitted to: Submitted by:
U Megha Gupta
MS. Harish Minariya
T
E 22ESKCA038

O BRANCH: - CSE(AI)
F

T
Python
Python is a widely used high-level, general-purpose, interpreted, dynamic programming
language. Its design philosophy emphasizes code readability, and its syntax allows
programmers to express concepts in fewer lines of code than would be possible in languages
such as C++ or Java. The language provides constructs intended to enable clear programs on
both a small and large scale. Python supports multiple programming paradigms, including
object-oriented, imperative and functional programming or procedural styles. It features a
dynamic type system and automatic memory management and has a large and comprehensive
standard library. Python interpreters are available for installation on many operating systems,
allowing Python code execution on a wide variety of systems.

History
Python was conceived in the late 1980s, and its implementation was started in December 1989
by Guido van Rossum at CWI in the Netherlands as a successor to the ABC language (itself
inspired by SETL) capable of exception handling and interfacing with the Amoeba operating
system. Van Rossum is Python's principal author, and his continuing central role in deciding
the direction of Python is reflected in the title given to him by the Python community,
benevolent dictator for life (BDFL).

Behind The Scene of Python


About the origin of Python, Van Rossum wrote in 1996:-
Over six years ago, in December 1989, I was looking for a "hobby" programming project that
would keep me occupied during the week around Christmas. My office ... would be closed, but
I had a home Computer, and not much else on my hands. I decided to write an interpreter for
the new scripting language I had been thinking about lately: a descendant of ABC that would
appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly
irreverent mood (and a big fan of Monty Python's Flying Circus)
PYTHON INTERNSHIP DAY 1
Python Fundamentals
Python Character Set
Character set is the set of valid characters that a language can recognize. A character
represents any letter, digit or any other symbol. Python has the following character sets:

· Letters – A to Z, a to z

· Digits – 0 to 9

· Special Symbols - + - * / etc.

· Whitespaces – Blank Space, tab, carriage return, newline, form feed

· Other characters – Python can process all ASCII and Unicode characters as part of data or
literals.

Tokens
In a passage of text, individual words and punctuation marks are called tokens lexical unite or
lexical elements. The smallest individual unit in a program is called token. Python has the
following tokens.

i. Keyword
ii. Identifiers
iii. Operators
iv. Literals
v. Delimiters

Keywords
Used to give special meaning to the interpreter and are used by Python interpreter to
recognize the structure of program. These are reserved for special purpose and must not be
used as normal identifier names. E.g. int, float etc.
Identifiers
Identifiers are the names given to different program elements like variable, objects, classes,
function, list, dictionaries etc. It consists of letters and digits in any order except that the first
character must be a letter, the underscore (_) counts as a character. Identifiers are unlimited
in length. Python is a case sensitive programming language. Thus ‘Value’ and ‘value’ are two
different identifiers in Python. All characters are significant.

Rules for Identifier


 It consist of letters and digits in any order except that the first character must be a
letter.
 The underscore (_) counts as a character.
 Spaces are not allowed.
 Special Characters are not allowed. Such as @,$ etc.
 An identifier must not be a keyword of Python.
 Variable names should be meaningful which easily depicts the logic.

operator
The operator is a symbol that performs a specific operation between two operands, according
to one definition. Operators serve as the foundation upon which logic is constructed in a
program in a particular programming language. In every programming language, some
operators perform several tasks. Same as other languages, Python also has some operators,
and these are given below –

o Arithmetic operators
o Comparison operators
o Logical Operators
o Bitwise Operators
Arithmetic Operators
Arithmetic operators used between two operands for a particular operation. There are many
arithmetic operators. It includes the exponent (**) operator as well as the + (addition), -
(subtraction), * (multiplication), / (divide), % (reminder), and // (floor division) operators.

+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 =>a+b = 20

- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand
is less than the second operand, the value results negative. For example, if a = 20, b
= 5 => a - b = 15

/ (divide) It returns the quotient after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a/b = 2.0

* It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a
(Multiplication) * b = 80

% (reminder) It returns the reminder after dividing the first operand by the second operand. For
example, if a = 20, b = 10 =>a%b = 0

** (Exponent) As it calculates the first operand's power to the second operand, it is an exponent
operator.

// (Floor It provides the quotient's floor value, which is obtained by dividing the two
division) operands

Comparison operator
Comparison operators mainly use for comparison purposes. Comparison operators compare
the values of the two operands and return a true or false Boolean value in accordance. The
example of comparison operators are ==, !=, <=, >=, >, <. In the below table, we explain the
works of the operators

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

<= The condition is met if the first operand is smaller than or equal to the second operand.

>= The condition is met if the first operand is greater than or equal to the second operand.

> If the first operand is greater than the second operand, then the condition becomes true.

< If the first operand is less than the second operand, then the condition becomes true.

Logical Operators
The assessment of expressions to make decisions typically uses logical operators. The
examples of logical operators are and, or, and not. In the case of logical AND, if the first one is
0, it does not depend upon the second one. In the case of logical OR, if the first one is 1, it
does not depend on the second one. Python supports the following logical operators. In the
below table, we explain the works of the logical operators.

and The condition will also be true if the expression is true. If the two expressions a and b are
the same, then a and b must both be true.

or The condition will be true if one of the phrases is true. If a and b are the two expressions,
then an or b must be true if and is true and b is false.

not If an expression a is true, then not (a) will be false and vice versa
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise operators. The examples of
Bitwise operators are bitwise OR (|), bitwise AND (&), bitwise XOR (^), negation (~), Left shift
(<<), and Right shift (>>). Consider the case below.

& (binary A 1 is copied to the result if both bits in two operands at the same location are
and) 1. If not, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit
will be 1.

^ (binary If the two bits are different, the outcome bit will be 1, else it will be 0.
xor)

~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next
bit will be 1, and vice versa.

<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of the
value of the left operand.

>> (right The left operand is moved right by the number of bits present in the right
shift) operand.

Python Data Types


Every value has a data type, and variables can hold values. Python is a powerfully composed
language; consequently, we don't have to characterize the sort of variable while announcing it.
The interpreter binds the value implicitly to its type.

Python supports three kinds of numerical data:-

o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so
on. An integer can be any length you want in Python. Its worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to
within 15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y
signify the genuine and non-existent parts separately. The complex numbers like 2.14j,
2.0 + 2.3j, etc
String
The sequence of characters in the quotation marks can be used to describe the string. A string
can be defined in Python using single, double, or triple quotes.

String dealing with Python is a direct undertaking since Python gives worked-in capabilities and
administrators to perform tasks in the string.

When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.

Because the operation "Python" *2 returns "Python," the operator * is referred to as a


repetition operator.

Boolean
True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or misleading. The class book indicates this. False can be
represented by the 0 or the letter "F," while true can be represented by any value that is not
zero.

Input Function:-
It is used to accept a input from a user ex-str 1= input('enter your name'),b=int(input('any
number'))

eval function:-
full form of eval is to evaluate by making use of eval function we can avoid specify a particular
type in frunt of input function for example x=int(input('enter the number') or
x=eval(input('enter the number')
Assignment 1
Q1. Write a program to display detail enter by user that is name, age, gender, height using eval
function ?

Sol:-

#Q1
a=eval(input('enter the name'))
b=eval(input('enter the age'))
c=eval(input('enter the gender'))
d=eval(input('enter the height'))
print(a)
print(b)
print(c)
print(d)

Q2. write a program to read the radius of a circle from a user and display it ?

Sol:-

#Q2
radius=eval(input('enter the radius of a circle'))
print(radius)

Q3. write a program to read an integer as string convert the string into the integer and display the
type of value before and after converting string ?

Sol:-

#Q3
c=12
print(type(c))
d=str(c)
print(type(d))
print(d)
a='123'
print(type(a))
b=int(a)
print(b)
print(type(b))
Q4. Write a p to display one integer and one floating type number ?

Sol:-

#Q4
a=eval(input('enter the int'))
b=eval(input('enter the float'))
print(a,b)

Q5 . Translate the following information into python step-

1. Insert variable named pounds with value 10.

2. Multiply pounds by 0.45 and assign into a variable kilogram.

3. Display the value of pounds and variable.

Sol:-

#Q5
pound=10
kg=pound*0.45
print(pound,kg)

PYTHON INTERNSHIP DAY 2


Python inbuilt Function
abs()
The python abs() function is used to return absolute value of a number. It takes only one
argument, a number whose absolute value is to be returned. The argument can be an integer
and floating point number. If the argument is a complex number, then, abs() returns its
magnitude.

pow()
Python pow() function is used to compute the powers of a number. It returns x to the power
of y modulus z if a third argument(z) is present, i.e. (x, y) % z.
x: It is a number, a base

y: It is a number, an exponent.

z (optional): It is a number and the modulus.

max()
The max() function returns the item with the highest value, or the item with the highest value
in an iterable.

If the values are strings, an alphabetically comparison is done.

round()
The round() function returns a floating point number that is a rounded version of the specified
number, with the specified number of decimals.

The default number of decimals is 0, meaning that the function will return the nearest integer.

Python mathematical function

ceil(x) The lowest integer bigger than or equal to x is returned.

floor(x) gives back the biggest integer that is less than or equal to x.

exp(x) delivers e**x

log(x[, b]) gives back the x logarithm in base b. (defaults to e)

sqrt(x) gives x's square root back.

acos(x) gives the arc cosine of x back.

asin(x) gives the arc sine of x back.


atan(x) gives the arc tangent of x back.

atan2(y, x) gives back atan(y / x).

cos(x) returns the x's cosine.

sin(x) gives the sine of x back.

tan(x) gives the tangent of x back.

degrees(x) Angle x is transformed from radians to degrees.

radians(x) Angle x is transformed from degrees to radians.

Assignment 2
Q1. Write a program to find a difference between the ascii code of any lower case letter and it corresponding
upper case letter.
Sol
#Q1
ord('a')-ord('A')

Q2. Write a program to calculate the simple interest read the principal amount rate of interest and time from
user
Sol
#Q2
pi=int(input('enter the pi'))
roi=int(input("enter the roi"))
t=int(input('enter the time'))
si=(pi*roi*t)/100
print(si)

Q3. Write a program to read temp. into Celsius from user and convert into Fahrenheit.
Sol
#Q3
tem=int(input('enter the tem in cal'))
f=tem*(9/5)+32
print(f)

Q4 Write a program to reverse 4 digits No.


Sol
#Q4
import math
a=int(input('enter 4 digit no'))
rev=((a%10)*1000)+(((a//10)%10)*100)+(((a//100)%10)*10)+a//1000
print(rev)

Q5 Write a program to calculate distance between two points.


Sol
#Q5
import math
x=10
y=20
p=20
q=10
math.sqrt(pow((p-x),2)+pow((q-y),2))

PYTHON INTERNSHIP DAY 3


Decision-Making Statements in Python
There comes a point in your life where you need to decide what steps should be taken and
based on that you decide your next decisions.
In programming, we often have this similar situation where we need to decide which block
of code should be executed based on a condition.

Python has the following decision-making statements:

 if statements
 if-else statements
 if-elif ladder
 Nested statements
Python if statement
if statement is the most simple form of decision-making statement. It takes
an expression and checks if the expression evaluates to True then the block of code in if
statement will be executed.
If the expression evaluates to False, then the block of code is skipped.

Syntax:
if ( expression ):

Statement 1

Statement 2
.

Statement n

Example :
a = 20 ; b = 20

if ( a == b ):

print( “a and b are equal”)

print(“If block ended”)

Python if-else statement


From the name itself, we get the clue that the if-else statement checks the expression
and executes the if block when the expression is True otherwise it
will execute the else block of code. The else block should be right after if block and
it is executed when the expression is False.

Syntax:

if( expression ):

Statement

else:

Statement
Example 1:
number1 = 20 ; number2 = 30

if(number1 >= number2 ):

print(“number 1 is greater than number 2”)

else:

print(“number 2 is greater than number 1”

Python if-elif ladder


You might have heard of the else-if statements in other languages like C/C++ or Java.
In Python, we have an elif keyword to chain multiple conditions one after another. With elif
ladder, we can make complex decision-making statements.
The elif statement helps you to check multiple expressions and it executes the code as soon
as one of the conditions evaluates to True.

Syntax:

if( expression1 ):

statement

elif (expression2 ) :

statement

elif(expression3 ):

statement

else:

statement

Example:
print(“Select your ride:”)

print(“1. Bike”)

print(“2. Car”)
print(“3. SUV”)

choice = int( input() )

if( choice == 1 ):

print( “You have selected Bike” )

elif( choice == 2 ):

print( “You have selected Car” )

elif( choice == 3 ):

print( “You have selected SUV” )

else:

print(“Wrong choice!“)

Python Nested if statement


In very simple words, Nested if statements is an if statement inside another if statement.
Python allows us to stack any number of if statements inside the block of another if
statements. They are useful when we need to make a series of decisions.

Syntax:

if (expression):

if(expression):

Statement of nested if

else:

Statement of nested if else

Statement of outer if

Statement outside if block


Example :
num1 = int( input())

num2 = int( input())

if( num1>= num2):

if(num1 == num2):

print(f'{num1} and {num2} are equal')

else:

print(f'{num1} is greater than {num2}')

else:

print(f'{num1} is smaller than {num2}')

Assignment 3
Q1. Write a program to calculate the salary, sells bonus and interest based on total sell if the sell >=1 lack then
follow column 1 else follow column 2
column 1 column 2
basic 4000/- 4000
hra 20%ofbasic 10%
da 110%of basic 110%
conveyance 500 500
incentive 10%ofsale 4%
bonus 1000 500
sol
#Q1
sell=eval(input('enter the sell'))
if sell>=100000 :
print(4000+.2*4000+1.1*4000+500+.1*sell+100)
else :
#print(4000+.1*4000+1.1*4000+500+.04*sell+500)

Q2. Write a program to test weather a no is divisible by 5 and 10 or by 5 or 10


Sol
#Q2
a=eval(input('enter the number'))
if a/5and a/10:
print('yes divide by 5 and 10')
elif a/5:
print('only divide by 5')
elif a/10:
print('only divide by 10')

Q3 Write a program when user enter the day of week if the enter day of the week is b/w 1 and 7 then display the
respective name of the day
Sol
#q3
day=int(input('enter the day of week'))
if day==1:
print('monday')
elif day==2:
print('tuesday')
elif day==3:
print('wed')
elif day==4:
print('thr')
elif day==5:
print('fri')
elif day==6:
print('sat')
elif day==7:
print('sun')

Q4. Write a program to find the no of day in a month if the year is leap if it is / by 4 not 100 or / by 400
Sol
#Q4
n=int(input('enter the year'))
y=int(input('enter the no of month'))
if y==1or y==3or y==5or y==7or y==8or y==10or y==12:
print('31')
elif y==2 :
if n%4==0and n%100!=0:
print('29')
else :
print('28')
elif y==4or y==6or y==9or y==11:
print(30)
PYTHON INTERNSHIP DAY 4
Python Loops
The following loops are available in Python to fulfil the looping needs. Python offers 3 choices for
running the loops. The basic functionality of all the techniques is the same, although the syntax and
the amount of time required for checking the condition differ.

We can run a single statement or set of statements repeatedly using a loop command.

Sr.No. Name of Loop Type & Description


the loop

1 While loop Repeats a statement or group of statements while a given condition is


TRUE. It tests the condition before executing the loop body.

2 For loop This type of loop executes a code block multiple times and
abbreviates the code that manages the loop variable.

3 Nested We can iterate a loop inside another loop.


loops

While Loop
While loops are used in Python to iterate until a specified condition is met. However, the statement in
the program that follows the while loop is executed once the condition changes to false.

while <condition>:
{ code block }

# Python program to show how to use a while loop


counter = 0
# Initiating the loop
while counter < 10: # giving the condition
counter = counter + 3
print("Python Loops")

The for Loop


Python's for loop is designed to repeatedly execute a code block while iterating through a list, tuple,
dictionary, or other iterable objects of Python. The process of traversing a sequence is known as
iteration.

Syntax of the for Loop

for value in sequence:


{ code block }

# Python program to show how the for loop works

# Creating a sequence which is a tuple of numbers


numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]

# variable to store the square of the number


square = 0

# Creating an empty list


squares = []

# Creating a for loop


for value in numbers:
square = value ** 2
squares.append(square)
print("The list of squares is", squares)
The range() Function
With the help of the range() function, we may produce a series of numbers. range(10) will produce
values between 0 and 9. (10 numbers).

We can give specific start, stop, and step size values in the manner range(start, stop, step size). If the
step size is not specified, it defaults to 1.

Since it doesn't create every value it "contains" after we construct it, the range object can be
characterized as being "slow." It does provide in, len, and __getitem__ actions, but it is not an iterator.

# Python program to show the working of range() function


print(range(15))

print(list(range(15)))

print(list(range(4, 9)))

print(list(range(5, 25, 4)))

Loop Control Statements


Now we will discuss the loop control statements in detail. We will see an example of each control
statement.

Continue Statement
It returns the control to the beginning of the loop.

# Python program to show how the continue statement works

# Initiating the loop


for string in "Python Loops":
if string == "o" or string == "p" or string == "t":
continue
print('Current Letter:', string)
Break Statement
It stops the execution of the loop when the break statement is reached.

# Python program to show how the break statement works

# Initiating the loop


for string in "Python Loops":
if string == 'L':
break
print('Current Letter: ', string)

Assignment 4
Q1write a programin python to find the factorial of no using while loop

Sol

#Q1
a=int(input('enter any no'))
b=1
c=1
sum=0
while b<=a:
c=b*c
b=b+1
print(c)

Q2 write a program to check the whether the no. enter is Armstrong

Sol

#q2
a=int(input('enter any no'))
n=a
c=0
while a>0:
sum=a%10
a=a//10
sum=sum**3
c=c+sum
print(c)

if n==c :
print('yes')
else:
print('no')

Q3 write a program to generate a triangular number sum from 1 to enter no

Sol

#q3
a=int(input('enter any no'))
b=1
sum=0
while b<=a:
sum=sum+b
b=b+1
print(sum)

Q4 write a program to find the sum of Fibonacci series

#q4
a=int(input('enter any no'))
b=1
c=0
e=1
d=0
print(c)
print(e)
while b<=a:
d=c+e
c=e
e=d
b=b+1
print(d)

Q5 pattern problem
1. **** 2.1 3. 1
*** 12 12
** 123 123
* 1234 1234
12345
123
12
1

Sol

#q5
c=1
n=2
#problem 1
for a inrange(1,5):
for b inrange(5,a,-1):
print('*',end="")
print('\n')
#problem 2
for a inrange(1,6):
for b inrange(0,a,1):
print(c,end="")
c=c+1
print('\n')
c=1
#problem 3
for a inrange(1,10):
if a>5:
n=n+2
for b inrange(1,6):
if a<5:
if b<=a:
print(c,end="")
c=c+1
else:
print(" ",end="")
elif a>4:
if b<=(a-n):
print(c,end="")
c=c+1
else :
print(" ",end="")
print('\n')
c=1

Q6 write a program to check whether the enter no is prime of not

#q6
a=int(input('enter the no'))
for b inrange(2,a):
ifa%b==0:
f=1
break
else:
f=0
b=b+1
if f==1:
print('no')
else:
print('yes')

PYTHON INTERNSHIP DAY 5

Python Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:

def my_function():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:

def my_function():
print("Hello from a function")

my_function()

Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2 arguments, not
more, and not less.

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

def my_function(child3, child2, child1):


print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

print("Hello")
print('Hello')

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:

a = "Hello"
print(a)

String Concatenation
To concatenate, or combine, two strings you can use the + operator.

Example
Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c = a + b
print(c)

Len() , Max() & Min() operators


 len() − This function returns the length of string. If the object has no asssociation with length ,
error is raised .
 min() − This function returns the minimum element from the string.
 max() − This function returns the maximum element from the string.

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.

However, Python does not have a character data type, a single character is simply a string
with a length of 1.

Square brackets can be used to access elements of the string.

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])

Looping Through a String


Since strings are arrays, we can loop through the characters in a string, with a for loop.

for x in "banana":
print(x)
Slicing
You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the
string.

Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])

Slice From the Start


By leaving out the start index, the range will start at the first character:

b = "Hello, World!"
print(b[:5])

Slice To the End


By leaving out the end index, the range will go to the end:

b = "Hello, World!"
print(b[2:])

Negative Indexing
Use negative indexes to start the slice from the end of the string:

b = "Hello, World!"
print(b[-5:-2])
String Methods
Python has a set of built-in methods that you can use on strings.

Note: All string methods return new values. They do not change the original string.

String are immutable.

Method Description

capitalize() Converts the first character to upper case

count() Returns the number of times a specified value occurs in a string

endswith() Returns true if the string ends with the specified value

find() Searches the string for a specified value and returns the position of where it was found

index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

lower() Converts a string into lower case


replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of where it was found

rindex() Searches the string for a specified value and returns the last position of where it was found

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

upper() Converts a string into upper case

ASSIGNMENT 5
Q1 For a quadratic equation of the for ax^2+bx+c find d=b^2-4acif d>0 equation has one real
root
if d<0 eq has two complex root.

Sol

#q1
import math as m
defa(a,b,c):
d=m.pow(b,2)-(4*a*c)
if d>0:
print('equation has one real root')
elif d<0:
print("eq has two complex root")
a(0,1,0)

Q2 write a function to cal. the distance b/w to point.


Sol

#q2
import math as m
defdis(a,b,x,y):
print(m.sqrt(pow((y-b),2)+pow((x-a),2)))
dis(10,20,20,10)

Q3 write a function to compute the Fibonacci series.

Sol

#q3
defs(x):
b=1
c=0
e=1
d=0
print(c)
print(e)
while b<=x:
d=c+e
c=e
e=d
b=b+1
print(d)
s(10)

Q4 write a function which take the word as the argument and return the vowels
a,e,i,o,u.

Sol

#q4
defa(a):
foriinrange(0,len(a)):
if a[i]=='a'or a[i]=='e'or a[i]=='i'or a[i]=='o'or a[i]=='u':
print(a[i])
a("pythonprograming")

Q5 write a function which take two words as argument which return true if the second word is
the reverse of first

Sol

defa(a,b):
c=list(reversed(a))
print©
print(list(b))
print(c==list(b))
a(‘aba’,’aba’)

PYTHON INTERNSHIP DAY 6

Python Lists
List
Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)

List Items
List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

A list can contain different data types:


Example
A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

Len() , Max() & Min() operators


 len() − This function returns the length of list. If the object has no asssociation with length , error
is raised .
 min() − This function returns the minimum element from the list.
 max() − This function returns the maximum element from the list
.

List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.

Example:

Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in
the name.

Without list comprehension you will have to write a for statement with a conditional test
inside:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)

With list comprehension you can do all that with only one line of code:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]


print(newlist)

Access Items
List items are indexed and you can access them by referring to the index number:

Print the second item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])

This example returns the items from "orange" (-4) to, but NOT including "mango" (-1):

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[-4:-1])

List Methods
Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Example
Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


thislist.append("orange")
print(thislist)

ASSIGNMENT 6

Q1 write a function that accept two positive integer let a and b and return the list of all even
no. b/w a and b?

Sol

#q1
defx(a,b):
if a>b:
lst=[x for x inrange(b,a+1) if x%2==0]
print(lst)
elif b>a:
lst=[x for x inrange(a,b+1) if x%2==0]
print(lst)
print(x(1,10))

Q2 write a function to check whether the list is palindrome?

Sol
#q2
defx(lst):
a=lst.copy()
a.reverse()
print(a)
print(lst)
if a==lst:
print(‘yes’)
else:
print(‘no’)
lst=[1,2,3]
x(lst)

Q3 write a program when user enter the element of the list write a function max list and min
list to find max min in the list.

Sol

#q3
defm(lst2):
print(‘max-‘,end=””)
print(max(lst))
print(‘min’,end=””)
print(min(lst))
lst=[]
a=int(input(‘enter the range of list’))
foriinrange(0,a):
b=int(input(“enter the element of list”))
lst.append(b)
print(lst)
m(lst)

Q4 write a function assign grade which read the marks of the student from the list and assign
the grade as follow.

Sol

#q4
defx(lst):
sum=0
foriinrange(0,len(lst)):
sum=sum+lst[i]
per=sum/len(lst)
if per>=90 :
print(‘distinction’)
elif per>=80 :
print(‘I class’)
elif per>=70:
print(‘II class’)
elif per>=60:
print(‘III class’)
elif per<60 :
print(‘fail’)
lst=[]
a=int(input(‘enter the no of subject’))
foriinrange(0,a):
b=int(input(“enter the marks of subject”))
lst.append(b)
print(lst)
x(lst)

Q5 write a program to written prime no from the list.

Sol

#q5
lst=[]
a=int(input(‘enter the range of list’))
foriinrange(0,a):
c=[]
b=int(input(“enter the element of list”))
lst.append(b)
print(lst)
foriinrange(0,len(lst)):
for j inrange(2,lst[i]):
iflst[i]%j==0:
f=0
break
else:
f=1
if f==1:
c.append(lst[i])
print©

PYTHON INTERNSHIP DAY 7

What is Matplotlib?
Matplotlib is a low level graph plotting library in python that serves as a visualization utility.
Matplotlib was created by John D. Hunter.

Matplotlib is open source and we can use it freely.

Matplotlib is mostly written in python, a few segments are written in C, Objective-C and Javascript for Platform
compatibility.

Import Matplotlib

Once Matplotlib is installed, import it in your applications by adding the import module statement:

import matplotlib

Plotting x and y points

The plot() function is used to draw points (markers) in a diagram.

By default, the plot() function draws a line from point to point.

The function takes parameters for specifying points in the diagram.

Parameter 1 is an array containing the points on the x-axis.

Parameter 2 is an array containing the points on the y-axis.

Example:

Draw a line in a diagram from position (1, 3) to position (8, 10):

import matplotlib.pyplot as plt

import numpy as np

xpoints = np.array([1, 8])

ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints)

plt.show()
Plotting Without Line
To plot only the markers, you can use shortcut string notation parameter 'o', which means 'rings'.

Example:

Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):

import matplotlib.pyplot as plt

import numpy as np

xpoints = np.array([1, 8])

ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints, 'o')

plt.show()
Multiple Points
You can plot as many points as you like, just make sure you have the same number of points in both axis.

Example

Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to position (8, 10):

import matplotlib.pyplot as plt

import numpy as np

xpoints = np.array([1, 2, 6, 8])

ypoints = np.array([3, 8, 1, 10])

plt.plot(xpoints, ypoints)

plt.show()
Markers
You can use the keyword argument marker to emphasize each point with a specified marker:

#Format Strings fmt

Example:

import matplotlib.pyplot as plt

import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, '>--m',ms=20,mfc="k",mec="y")

plt.show()
Linestyle
You can use the keyword argument linestyle, or shorter ls, to change the style of the plotted line:

Shorter Syntax

The line style can be written in a shorter syntax:

linestyle can be written as ls.

dotted can be written as :.

dashed can be written as --.

Example

Shorter syntax:

plt.plot(ypoints, ls = ':')

Multiple Lines
You can plot as many lines as you like by simply adding more plt.plot() functions:
import matplotlib.pyplot as plt

import numpy as np

y1 = np.array([3, 8, 1, 10])

y2 = np.array([6, 2, 7, 11])

plt.plot(y1)

plt.plot(y2)

plt.show()

Create Labels,Title for a Plot


With Pyplot, you can use the xlabel() and ylabel() functions to set a label for the x- and y-axis.

With Pyplot, you can use the title() function to set a title for the plot.

Example:

import numpy as np

import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])

y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)

plt.title("Sports Watch Data")

plt.xlabel("Average Pulse")

plt.ylabel("Calorie Burnage")

plt.show()

Add Grid Lines to a Plot


With Pyplot, you can use the grid() function to add grid lines to the plot.

Example:

import numpy as np

import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])

y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.title("Sports Watch Data")

plt.xlabel("Average Pulse")

plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid()

plt.show()

Matplotlib Subplot

Display Multiple Plots.

With the subplot() function you can draw multiple plots in one figure:

The subplot() function takes three arguments that describes the layout of the figure.

The layout is organized in rows and columns, which are represented by the first and second argument.

#The third argument represents the index of the current plot.


plt.subplot(1, 2, 1)

#the figure has 1 row, 2 columns, and this plot is the first plot.

plt.subplot(1, 2, 2)

example:

import matplotlib.pyplot as plt

import numpy as np

#plot 1:

x = np.array([0, 1, 2, 3])

y = np.array([3, 8, 1, 10])

plt.subplot(2, 1, 1)

plt.plot(x,y)

#plot 2:

x = np.array([0, 1, 2, 3])

y = np.array([10, 20, 30, 40])

plt.subplot(2, 1, 2)

plt.plot(x,y)

plt.show()
the figure has 1 row, 2 columns, and this plot is the second plot.

Matplotlib Scatter
Creating Scatter Plots

With Pyplot, you can use the scatter() function to draw a scatter plot.

Example:

import matplotlib.pyplot as plt

import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])

y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

colors =
np.array(["red","green","blue","yellow","pink","black","orange","purple","beige","brown","gray","cyan","magenta"])

plt.scatter(x, y, c=colors)

plt.show()
ColorMap
The Matplotlib module has a number of available colormaps.

A colormap is like a list of colors, where each color has a value that ranges from 0 to 100.

Example:

import matplotlib.pyplot as plt

import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])

y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])

plt.scatter(x, y, c=colors, cmap='viridis')

plt.colorbar()

plt.show()
Size:
You can change the size of the dots with the s argument.

Just like colors, make sure the array for sizes has the same length as the arrays for the x- and y-axis:

Example:

import matplotlib.pyplot as plt

import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])

y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])

plt.scatter(x, y, ,s=sizes)

plt.show()
Combine Color Size and Alpha
You can combine a colormap with different sizes of the dots. This is best visualized if the dots are transparent.

Example:

import matplotlib.pyplot as plt

import numpy as np

x = np.random.randint(100, size=(100))

y = np.random.randint(100, size=(100))

colors = np.random.randint(100, size=(100))

sizes = 10 * np.random.randint(100, size=(100))

plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='nipy_spectral')

plt.colorbar()

plt.show()
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:

Example:

import matplotlib.pyplot as plt

import numpy as np

x = np.array(["A", "B", "C", "D"])

y = np.array([3, 8, 1, 10])

plt.bar(x, y, color = "hotpink")

plt.show()
Histogram
A histogram is a graph showing frequency distributions.

It is a graph showing the number of observations within each given interval.

Example:

import matplotlib.pyplot as plt

import numpy as np

x = np.random.normal(170, 10, 250)

plt.hist(x)

plt.show()
Creating Pie Charts
With Pyplot, you can use the pie() function to draw pie charts.

Example:

import matplotlib.pyplot as plt

import numpy as np

y = np.array([35, 25, 25, 15])

mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

mycolors = ["black", "hotpink", "b", "#4CAF50"]

plt.pie(y, labels = mylabels, colors = mycolors)

plt.show()
Legend:
To add a list of explanation for each wedge, use the legend() function.

Example:

import matplotlib.pyplot as plt

import numpy as np

y = np.array([35, 25, 25, 15])

mylabels = ["Apples", "Bananas", "Cherries", "Dates"]

mycolors = ["black", "hotpink", "b", "#4CAF50"]

plt.pie(y, labels = mylabels, colors = mycolors)

plt.legend(title = "Four Fruits:")

plt.show()
PYTHON INTERNSHIP DAY 8

FILE HANDLING:
The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)

Syntax:

To open a file for reading it is enough to specify the name of the file:

f = open("demofile.txt")

Open a File on the Server:


To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the content of the file:

Example:

f = open("demofile.txt", "r")

print(f.read())

Read Lines()
You can return one line by using the readline() method:

Example:

Read one line of the file:

f = open("demofile.txt", "r")

print(f.readline())

Close Files
It is a good practice to always close the file when you are done with it.

Example:

Close the file when you are finish with it:

f = open("demofile.txt", "r")

print(f.readline())
f.close()

Write to an Existing File


To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

example1:

Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")

f.write("Now the file has more content!")

f.close()

#open and read the file after the appending:

f = open("demofile2.txt", "r")

print(f.read())

example2:

Open the file "demofile3.txt" and overwrite the content:

f = open("demofile3.txt", "w")

f.write("Woops! I have deleted the content!")

f.close()

#open and read the file after the overwriting:

f = open("demofile3.txt", "r")

print(f.read())

Create a New File


To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Example:

Create a file called "myfile.txt":

f = open("myfile.txt", "x")

Delete a File
To delete a file, you must import the OS module, and run its os.remove() function:

Example:

Remove the file "demofile.txt":

import os

os.remove("demofile.txt")

Delete Folder
To delete an entire folder, use the os.rmdir() method:

Example:

Remove the folder "myfolder":

import os

os.rmdir("myfolder")

ASSIGNMENT 9

1. generate 50 radom numbers from 500 to 1000 in a text file.

Sol
from random import randint

f=open("/content/sample_data/abc.txt","w")

for i in range(1,51):

r=str(randint(500,1000))

f.write(r)

f.write(" ")

f.close()

f = open("/content/sample_data/abc.txt", "r")

print(f.read())

2.WAP to add the contents of a file numbers.txt and display sum of all the
numbers to file.

sol

f=open("/content/numbers.txt","w")

for i in range(1,6):

f.write(str(i))

f.write('\n')

f=open("/content/numbers.txt","r")

y=0

for i in range(1,6):

x=f.readline()

y=y+int(x)
f=open("/content/numbers.txt","a")

f.write("sum of the numbers ")

f.write(str(y))

PYTHON INTERNSHIP DAY 9

Python Tuples
Tuple
Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Example
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.

Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.

Allow Duplicates
Since tuples are indexed, they can have items with the same value:

Tuple Length
To determine how many items a tuple has, use the len() function

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the item, otherwise
Python will not recognize it as a tuple.

Tuple items can be of any data type:

Example
thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Python Collections (Arrays)


There are four collection data types in the Python programming language:

 List is a collection which is ordered and changeable. Allows duplicate members.


 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate
members.
 Dictionary is a collection which is ordered** and changeable. No duplicate members.

Access Tuple Items


You can access tuple items by referring to the index number, inside square brackets:

Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])

Negative Indexing
Negative indexing means start from the end.

-1 refers to the last item, -2 refers to the second last item etc.

Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list, change the list, and convert
the list back into a tuple.

Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a tuple:

Unpacking a tuple:
fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)

Using Asterisk*
If the number of variables is less than the number of values, you can add an * to the
variable name and the values will be assigned to the variable as a list

Assign the rest of the values as a list called "red":

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)

Join Two Tuples


To join two or more tuples you can use the + operator:

Join two tuples:

tuple1 = ("a", "b" , "c")


tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)

Multiply Tuples
If you want to multiply the content of a tuple a given number of times, you can use
the * operator:

Example
Multiply the fruits tuple by 2:

fruits = ("apple", "banana", "cherry")


mytuple = fruits * 2

print(mytuple)
Tuple Methods

Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where it
was found

Set
Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

* Note: Set items are unchangeable, but you can remove items and add new items.

Sets are written with curly brackets.

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)

Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered
Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred
to by index or key.

Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has
been created.

Once a set is created, you cannot change its items, but you can remove items and add new
items.

Duplicates Not Allowed


Sets cannot have two items with the same value.

True and 1 is considered the same value:

thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)

Access Items
You cannot access items in a set by referring to an index or a key.

But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword

Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add one item to a set use the add() method.

Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}

thisset.add("orange")

print(thisset)

Add Sets
To add items from another set into the current set, use the update() method.

Example
Add elements from tropical into thisset:

thisset = {"apple", "banana", "cherry"}


tropical = {"pineapple", "mango", "papaya"}

thisset.update(tropical)

print(thisset)

Add Any Iterable


The object in the update() method does not have to be a set, it can be any iterable object
(tuples, lists, dictionaries etc.).

Example
Add elements of a list to at set:

thisset = {"apple", "banana", "cherry"}


mylist = ["kiwi", "orange"]

thisset.update(mylist)

print(thisset)

Remove Item
To remove an item in a set, use the remove(), or the discard() method.

Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}

thisset.remove("banana")

print(thisset)

Example
Remove "banana" by using the discard() method:

thisset = {"apple", "banana", "cherry"}

thisset.discard("banana")

print(thisset)

You can also use the pop() method to remove an item, but this method will remove a
random item, so you cannot be sure what item that gets removed.

The return value of the pop() method is the removed item.

Example
Remove a random item by using the pop() method:

thisset = {"apple", "banana", "cherry"}

x = thisset.pop()

print(x)

print(thisset)

Example
The clear() method empties the set:

thisset = {"apple", "banana", "cherry"}

thisset.clear()

print(thisset)
Example
The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)

Loop Items
You can loop through the set items by using a for loop:

Example
Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Join Two Sets


There are several ways to join two or more sets in Python.

You can use the union() method that returns a new set containing all items from both sets,
or the update() method that inserts all the items from one set into another:

Example
The union() method returns a new set with all items from both sets:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}

set3 = set1.union(set2)
print(set3)

Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between two


or more sets

difference_update() Removes the items in this set that are also included
in another, specified set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other


sets

intersection_update() Removes the items in this set that are not present in
other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not


issubset() Returns whether another set contains this
set or not

issuperset() Returns whether this set contains another


set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric


differences of two sets

symmetric_difference_update( inserts the symmetric differences from this


) set and another

union() Return a set containing the union of sets

update() Update the set with the union of this set


and others

Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow duplicates.


As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.

Dictionaries are written with curly brackets, and have keys and values:

Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key
name.

Example
Print the "brand" value of the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Ordered or Unordered?
When we say that dictionaries are ordered, it means that the items have a defined order,
and that order will not change.

Unordered means that the items does not have a defined order, you cannot refer to an item
by using an index.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:

Example
Duplicate values will overwrite existing values:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)

Accessing Items
You can access the items of a dictionary by referring to its key name, inside square
brackets:

Example
Get the value of the "model" key:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]

There is also a method called get() that will give you the same result:

Example
Get the value of the "model" key:

x = thisdict.get("model")

Get Keys
The keys() method will return a list of all the keys in the dictionary.

Example
Get a list of the keys:

x = thisdict.keys()

Get Values
The values() method will return a list of all the values in the dictionary.

Example
Get a list of the values:

x = thisdict.values()

Get Items
The items() method will return each item in a dictionary, as tuples in a list.

Example
Get a list of the key:value pairs

x = thisdict.items()

Change Values
You can change the value of a specific item by referring to its key name:

Example
Change the "year" to 2018:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Update Dictionary
The update() method will update the dictionary with the items from the given argument.

The argument must be a dictionary, or an iterable object with key:value pairs.

Example
Update the "year" of the car by using the update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})

Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to
it:

Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Removing Items
There are several methods to remove items from a dictionary:

Example
The pop() method removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

Example
The popitem() method removes the last inserted item (in versions before 3.7, a random
item is removed instead):

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)

Example
The del keyword removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

Example
The del keyword can also delete the dictionary completely:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.

Example
The clear() method empties the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)

Loop Through a Dictionary


You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dictionary, but there
are methods to return the values as well.

Example
Print all key names in the dictionary, one by one:

for x in thisdict:
print(x)

Example
Print all values in the dictionary, one by one:

for x in thisdict:
print(thisdict[x])

Example
You can also use the values() method to return values of a dictionary:

for x in thisdict.values():
print(x)

Example
You can use the keys() method to return the keys of a dictionary:

for x in thisdict.keys():
print(x)
Example
Loop through both keys and values, by using the items() method:

for x, y in thisdict.items():
print(x, y)

Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary method copy().

Example
Make a copy of a dictionary with the copy() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)

Another way to make a copy is to use the built-in function dict().

Example
Make a copy of a dictionary with the dict() function:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
Example
Create a dictionary that contain three dictionaries:

myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}

Access Items in Nested Dictionaries


To access items from a nested dictionary, you use the name of the dictionaries, starting with
the outer dictionary:

Example
Print the name of child 2:

print(myfamily["child2"]["name"])

Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.

Method Description
clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with th
specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


Assignment 9
Q1 consider an outgoing test series following are the name of the player and there score in
test1 and test2 calculate the highest no of run score by individual cricketer in the both test
Sol
test1={'a':10,'b':30,'c':40,'d':20,'e':40}
test2={'a':30,'b':40,'c':20,'d':25,'e':40}
total={}
for a in test1:
for b in test2:
if a==b:
sum=test1[a]+test2[b]
total[a]=sum
#print(total)
list1=[]
for a in total:
list1.append(total[a])
#print(list1)
#print(max(list1))
for a in total:
ifint(total[a])==int(max(list1)):
print(f"highest number of run score by indivisual player in both match is :- \
n{a}")

PYTHON INTERNSHIP DAY 10

Turtle Programming in Python


“Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it!
We can use functions like turtle.forward(…) and turtle.right(…) which can move the turtle around.
Commonly used turtle methods are :

Method Parameter Description

Turtle() None Creates and returns a new turtle object


Method Parameter Description

forward() amount Moves the turtle forward by the specified amount

backward() amount Moves the turtle backward by the specified amount

right() angle Turns the turtle clockwise

left() angle Turns the turtle counterclockwise

penup() None Picks up the turtle’s Pen

pendown() None Puts down the turtle’s Pen

up() None Picks up the turtle’s Pen

down() None Puts down the turtle’s Pen

color() Color name Changes the color of the turtle’s pen

fillcolor() Color name Changes the color of the turtle will use to fill a polygon

heading() None Returns the current heading

position() None Returns the current position

goto() x, y Move the turtle to position x,y

begin_fill() None Remember the starting point for a filled polygon

end_fill() None Close the polygon and fill with the current fill color

dot() None Leave the dot at the current position

stamp() None Leaves an impression of a turtle shape at the current location


Method Parameter Description

shape() shapename Should be ‘arrow’, ‘classic’, ‘turtle’ or ‘circle’

Plotting using Turtle


To make use of the turtle methods and functionalities, we need to import turtle.”turtle” comes packed
with the standard Python package and need not be installed externally. The roadmap for executing a
turtle program follows 4 steps:
1. Import the turtle module
2. Create a turtle to control.
3. Draw around using the turtle methods.
4. Run turtle.done().
So as stated above, before we can use turtle, we need to import it. We import it as :
from turtle import *
# or
import turtle
After importing the turtle library and making all the turtle functionalities available to us, we need to
create a new drawing board(window) and a turtle. Let’s call the window as wn and the turtle as skk.
So we code as:
wn = turtle.Screen()
wn.bgcolor("light green")
wn.title("Turtle")
skk = turtle.Turtle()
Now that we have created the window and the turtle, we need to move the turtle. To move forward
100 pixels in the direction skk is facing, we code:
skk.forward(100)
We have moved skk 100 pixels forward, Awesome! Now we complete the program with the done()
function and We’re done!
turtle.done()
So, we have created a program that draws a line 100 pixels long. We can draw various shapes and fill
different colors using turtle methods. There’s plethora of functions and programs to be coded using
the turtle library in python. Let’s learn to draw some of the basic shapes.

# Python program to draw square


# using Turtle Programming
importturtle
skk=turtle.Turtle()

foriinrange(4):
skk.forward(50)
skk.right(90)

turtle.done()

output

importturtle

# Set up the turtle screen and set the background color to white
screen =turtle.Screen()
screen.bgcolor("white")

# Create a new turtle and set its speed to the fastest possible
pen =turtle.Turtle()
pen.speed(0)

# Set the fill color to red


pen.fillcolor("red")
pen.begin_fill()

# Draw the circle with a radius of 100 pixels


pen.circle(100)

# End the fill and stop drawing


pen.end_fill()
pen.hideturtle()

# Keep the turtle window open until it is manually closed


turtle.done()

Output

# Python program to draw


# Rainbow Benzene
# using Turtle Programming
importturtle
colors =['red', 'purple', 'blue', 'green', 'orange', 'yellow']
t =turtle.Pen()
turtle.bgcolor('black')
forx inrange(360):
t.pencolor(colors[x%6])
t.width(x//100+1)
t.forward(x)
t.left(59)
Output

PYTHON INTERNSHIP DAY 11

Plotting using Turtle


Example 1
import turtle
b=turtle.Screen()
b.bgcolor('#76EEC6')
colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']
t=turtle.Turtle()
t.speed(0)
t.pencolor('black')
t.penup()
t.sety(-50)
t.setx(-50)
t.pendown()
t.fillcolor('#FFD700')
t.begin_fill()
t.circle(100)
t.end_fill()
t.penup()
t.sety(60)
t.setx(-15)
t.pendown()
t.left(45)
t.fillcolor('black')
t.begin_fill()
t.circle(20,90)
t.circle(20//2,90)
t.circle(20,90)
t.circle(20//2,90)
t.end_fill()
t.penup()
t.setx(-20)
t.sety(70)
t.pendown()
t.fillcolor('white')
t.begin_fill()
t.right(30)
t.circle(5)
t.end_fill()
t.penup()
t.sety(60)
t.setx(-15)
t.setx(-80)
t.pendown()
t.fillcolor('black')
t.begin_fill()
t.left(30)
t.circle(20,90)
t.circle(20//2,90)
t.circle(20,90)
t.circle(20//2,90)
t.end_fill()
t.penup()
t.setx(-85)
t.sety(70)
t.pendown()
t.fillcolor('white')
t.begin_fill()
t.right(30)
t.circle(5)
t.end_fill()
t.penup()
t.sety(10)
t.setx(-95)
t.pendown()
t.right(70)
for i in range(55):
t.left(2)
t.forward(2)
t.hideturtle()
t.penup()
t.sety(60)
t.setx(-25)
t.pendown()
t.right(90)
a=0
for i in range(2):
t.penup()
t.sety(46+a)
a=-20
t.pendown()
t.fillcolor('blue')
t.begin_fill()
t.circle(5)
t.end_fill()

Example 2

import turtle
b=turtle.Screen()
b.bgcolor('#76EEC6')
colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']
t=turtle.Turtle()
t.speed(1)
t.shape('turtle')
t.pencolor('black')
t.penup()
t.sety(-50)
t.setx(-50)
t.pendown()
t.fillcolor('#FFD700')
t.begin_fill()
t.circle(100)
t.end_fill()
t.width(5)
t.penup()
t.sety(80)
t.pendown()
t.fillcolor('black')
t.begin_fill()
t.setx(44)
t.setx(-146)
t.sety(70)
t.right(90)
for i in range(16):
t.width(6)
t.left(10)
t.forward(8)
t.setx(-44)
t.right(145)
for i in range(16):
t.width(6)
t.left(10)
t.forward(8)
t.end_fill()
t.penup()
t.setx(-74)
t.sety(0)
t.right(170)
t.pendown()
for i in range(5):
t.width(15)
t.left(30)
t.forward(15)
t.penup()
t.setx(-135)
t.sety(60)
t.pendown()
t.right(300)
for i in range(20):
t.pencolor('white')
t.width(5)
t.right(5)
t.forward(1)
t.penup()
t.setx(-30)
t.sety(60)
t.pendown()
t.left(90)
for i in range(20):
t.pencolor('white')
t.width(5)
t.right(5)
t.forward(1)

t.hideturtle()

PYTHON INTERNSHIP DAY 12

Machine Learning
Machine Learning is making the computer learn from studying data and statistics.
Machine Learning is a step into the direction of artificial intelligence (AI).

Machine Learning is a program that analyses data and learns to predict the outcome.

Where To Start?
In this tutorial we will go back to mathematics and study statistics, and how to calculate
important numbers based on data sets.

We will also learn how to use various Python modules to get the answers we need.

And we will learn how to make functions that are able to predict the outcome based on what
we have learned.

Data Set
In the mind of a computer, a data set is any collection of data. It can be anything from an
array to a complete database.

Example of an array:

[99,86,87,88,111,86,103,87,94,78,77,85,86]

Example of a database:

Carname Color Age Speed AutoPass

BMW red 5 99 Y

Volvo black 7 86 Y

VW gray 8 87 N
VW white 7 88 Y

Ford white 2 111 Y

VW white 17 86 Y

Tesla red 2 103 Y

BMW black 9 87 Y

Volvo gray 4 94 N

Ford white 11 78 N

Toyota gray 12 77 N

VW white 9 85 N

Toyota blue 6 86 Y

By looking at the array, we can guess that the average value is probably around 80 or 90,
and we are also able to determine the highest value and the lowest value, but what else can
we do?

And by looking at the database we can see that the most popular color is white, and the
oldest car is 17 years, but what if we could predict if a car had an AutoPass, just by looking
at the other values?

That is what Machine Learning is for! Analyzing data and predicting the outcome!
In Machine Learning it is common to work with very large data sets. In this tutorial we will
try to make it as easy as possible to understand the different concepts of machine learning,
and we will work with small easy-to-understand data sets.

Data Types
To analyze data, it is important to know what type of data we are dealing with.

We can split the data types into three main categories:

 Numerical
 Categorical
 Ordinal

Numerical data are numbers, and can be split into two numerical categories:

 Discrete Data
- numbers that are limited to integers. Example: The number of cars passing by.
 Continuous Data
- numbers that are of infinite value. Example: The price of an item, or the size of an
item

Categorical data are values that cannot be measured up against each other. Example: a
color value, or any yes/no values.

Ordinal data are like categorical data, but can be measured up against each other.
Example: school grades where A is better than B and so on.

By knowing the data type of your data source, you will be able to know what technique to
use when analyzing them.

You will learn more about statistics and analyzing data in the next chapters.

Machine Learning - Mean Median


Mode
Mean, Median, and Mode
What can we learn from looking at a group of numbers?

In Machine Learning (and in mathematics) there are often three values that interests us:

 Mean - The average value


 Median - The mid point value
 Mode - The most common value

Example: We have registered the speed of 13 cars:

speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]

What is the average, the middle, or the most common speed value?

Mean
The mean value is the average value.

To calculate the mean, find the sum of all values, and divide the sum by the number of
values:

(99+86+87+88+111+86+103+87+94+78+77+85+86) / 13 = 89.77

The NumPy module has a method for this. Learn about the NumPy module in our NumPy
Tutorial.

Example
Use the NumPy mean() method to find the average speed:

import numpy

speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]

x = numpy.mean(speed)

print(x)

PROJECT 1
COW AND BULL GAME
The "Cow and Bull" game is a word-based or number-based guessing game where one player (the codemaker) selects a
secret word or number, and the other player (the codebreaker) attempts to guess it within a certain number of
attempts. In the context of your Python script, it's a number-based version of the game.
Here's how the game works:

1. *Secret Code Generation*:

- The codemaker generates a secret code, which is typically a 4-digit number with no repeating digits. This secret code
is what the codebreaker needs to guess.

2. *Guessing Process*:

- The codebreaker makes guesses by entering 4-digit numbers.

- After each guess, the codemaker provides feedback in terms of "bulls" and "cows" to help the codebreaker refine
their guess.

3. *Bulls and Cows Feedback*:

- "Bulls" represent correct digits that are in the correct position in the secret code.

- "Cows" represent correct digits that are in the wrong position in the secret code.

4. *Winning Conditions*:

- The codebreaker continues to make guesses until they guess the secret code correctly (4 bulls).

- If the codebreaker successfully guesses the secret code within the specified number of attempts, they win.

- If they run out of attempts without guessing the code, the codemaker wins.

Here's an example to illustrate how Bulls and Cows feedback works:

- Secret code: 1234

- Codebreaker's guess: 1438

- Feedback: 2 Bulls (1 and 3 are in the correct positions), 1 Cow (4 is a correct digit but in the wrong position).

The game continues until the codebreaker either correctly guesses the entire secret code or exhausts their allowed
attempts.
Your Python script implements this game by generating a secret code, allowing the player to make guesses, providing
feedback, and determining the game's outcome based on the player's performance.

PROJECT 1 CODE:-

import random

def generate_secret_code():
digits = list(range(10))
random.shuffle(digits)
return ''.join(map(str, digits[:4]))

def evaluate_guess(secret, guess):


bulls = 0
cows = 0
for i in range(4):
if guess[i] == secret[i]:
bulls += 1
elif guess[i] in secret:
cows += 1
return bulls, cows

def play_bulls_and_cows(max_attempts):
secret_code = generate_secret_code()
attempts = 0
print("Welcome to Bulls and Cows!")
print("Try to guess the 4-digit secret code with no repeating digits.")
print(f"You have {max_attempts} attempts.")
while attempts < max_attempts:
guess = input("Enter your guess: ")
attempts += 1
if len(guess) != 4 or not guess.isdigit() or len(set(guess)) != 4:
print("Invalid input. Please enter a 4-digit number with no repeating
digits.")
continue
bulls, cows = evaluate_guess(secret_code, guess)
if bulls == 4:
print(f"Congratulations! You guessed the secret code '{secret_code}' in
{attempts} attempts!")
break
else:
print(f"Bulls: {bulls}, Cows: {cows}")
if bulls != 4:
print(f"Sorry, you've run out of attempts. The secret code was
'{secret_code}'.")

if __name__ == "__main__":
max_attempts = int(input("Enter the number of guesses you'd like to have: "))
play_bulls_and_cows(max_attempts)

PROJECT 1 OUTPUT:-
Enter the number of guesses you'd like to have: 3
Welcome to Bulls and Cows!
Try to guess the 4-digit secret code with no repeating digits.
You have 3 attempts.
Enter your guess: 2
Invalid input. Please enter a 4-digit number with no repeating digits.
Enter your guess: 1234
Bulls: 1, Cows: 0
Enter your guess: 6321
Bulls: 0, Cows: 0
Sorry, you've run out of attempts. The secret code was '0954'.
PYTHON SUMMER INTERNSHIP PHOTOS

You might also like