You are on page 1of 16

PYTHON

1.1 Setup python environment.


Step 1: Open web browser and go to https://www.python.org/downloads/
Step 2: Depending on operating system in your PC select the software.
Step 3: Follow the link for Windows Installer python.msi file. Confirm the version you need to
install.
Step 4: Run the download file. This brings up the python install wizard. Just accept the default setting, wait until the
install is finished, and you are done.
1.2 Executing python: explore different ways to run python program.
Interactive Interpreter : You can start python from Unix, DOS, or any other system that provides you a command-
line interpreter or shell window. Enter python the command line.

C:>python

Script from the command line: A Python script can be executed at command line by invoking the interpreter on
your application, as in the following.

C:>python script.py
Integrated Development Environment (IDE): You can run Python from a graphical user interface (GUI)
environment as well , if you have a GUI application on your system that supports python.

1.3 Debug python code

Step 1: In the Shell window, click on the Debug menu option at the top and then on Debugger. Step 2: Notice that
the Shell shows "[DEBUG ON]".
Step 3: Click on Run and run the program.
Step 4: Note that the Debug Control window is opened.
Step 5: After debugging the program close the debug control window.
…………………………………………………………………………………………………………………………
2.1 Code,execute and debug programs that .

a) Use I/O statement


Input:- To take user input at some point in the program. To do this Python provides an input() function.

Synatx:- input('prompt')

Code:- name = input("Enter your name: ")

Output:- Python provides the print() function to display output to the standard output devices.

Syntax:- print(value)

Code :- print(“Python Programming”)


Output>> Python Programming

b) Evaluate expression and displays formatted output.

Syntax:
<format_string> % <values>
Code:>>
print('Hello, my name is %s.' % 'Graham')
Output:>>
Hello, my name is Graham

c) Evaluate expression to examine the operator precedence. Code: >>


num=((10+20)*30)
print(num)
Output:>>
900

2.2 Identify and resolve syntactic and semantic issue in the given code snippet.

Syntactic error :-
Make sure you are not using a python keyword for variable name. as given in[2 b]
‘name’ is a variable name we cannot swap his name with python keywords like as ‘print’

Semantic error :- Make sure that use operators and write program as you want right output in [ 2 c] if we change order
of operation so output will change.

…………………………………………………………………………………………………………………………....

3.1 Identify the Code, execute and debug program using conditional statements.

Conditional Statement: Conditional statements are also called decision-making statements. We use those statements
while we want to execute a block of code when the given condition is true or false.

Syntax:>>
If(condition):
print(statement)
else:
print(statement)
Code:>>
grade=60
If grade >= 65:
print(“Passing Grade”) else:
print(“Failing Grade”)

Output:>>
Failing Grade

Debug:-
i) Come back on IDEL Shell and click on debug section and tick on debugger ii) Go to
program window and click on Run>Run Module or press F5

3.2 Identify and resolve the syntactic and semantic issue in the given code snippet.

Syntactic Error :- We found this error on operator which identify if given value is right then output will be Passing
grade otherwise else will Failing grade

Semantic Error :- If operator correct is not written then the output will not come as stated.

…………………………………………………………………………………………………………………………….

4.1 Code, execute and debug programs using loops.


Loop : A loop is a sequence of instruction s that is continually repeated until a certain condition is reached.

Syntax for loop :>> for val in sequence:

loop body

Code: >> colors=['yellow','black','green','purple']


fruits=['mango',"banana",'apple'] for x in colors:
for y in fruits:

print(x,y)

Output:>>

yellow mango yellow


banana yellow apple
black mango black
banana black apple
green mango green
banana green apple
purple mango purple
banana
purple apple

4.2 Code, execute and debug programs using loops and conditional statement.
Conditional statement:

Syntax:>> break

Code:>>
for i in range (1,4):

print(i)

break
else:

print("No break")
Output:>> 1

4.3 Identify and resolve the syntactic and semantic issue in the given code snippet.
Syntactic error:-
Keywords are only allowed to be used in specific situations. If you use them incorrectly, then you’ll have invalid
syntax in your Python code. If you move back from the caret, then you can see that the in keyword is missing
from the for loop syntax.
Semantic error:-

Error will show on executing time when any keyword later placed wrong as for example
(break >brek) It will display error on shell
>>>>
brek
NameError: name 'brek' is not defined

…………………………………………………………………………………………………………………………….
5.1 Code, execute and debug programs to perform following.
* Set operations

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

set(iterable)
Syntax:>>

Code:>>
set1={1,2,3,4} set2={2,3,5,6}
set3={3,4,6,7}
print(set1.union(set2))
print(set2.union(set3))
print(set3.union(set1)) Output:>>
{1, 2, 3, 4, 5, 6}
{2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 6, 7}

Set Iteration :- Code :


>>
test_set = set("geEks")

test_list = list(test_set)
for id in range(len(test_list)):
print(test_list[id])
Output :>>
se
Ek
g

** Set Comprehension
set1={1,2,3,4} set2={2,3,5,6}
set3={3,4,6,7}
print(set1.difference(set2))
print(set2.difference(set3))
print(set3.difference(set1))
Output:>>
{1, 4}
{2, 5}
{6, 7}

5.2 Code, execute and debug programs to perform following.


* Basic operations on 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

Code:-

a=[10,20,30,40]
b=[50,60,70,80]
list=[1,2,3,4] len(a) 4
a+b
[10, 20, 30, 40, 50, 60, 70, 80] a*2
[10, 20, 30, 40, 10, 20, 30, 40]
10 in a True
for ele in a:
print(ele) 10
20
30 40
max(a)
40
min(a)
10
a.index(10)
0
a.count(20) 1
tuple(list) (1,
2, 3, 4)
tuple("Hello")
('H', 'e', 'l', 'l', 'o')

** Tuple indexing and slicing


>> indexing : - The index() method finds the first occurrence of the specified value. The index() method raises an
exception if the value is not found

Syntax :- tuple.index(value)

Code:- tuple1=(1,2,3,4)
for i in range(len(tuple1)):
print("tuple 1",[i])

Output:-
tuple 1 [0] tuple
1 [1] tuple 1 [2]
tuple 1 [3]

>> Slicing :- Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a
Tuple. Slicing can also be done to lists and arrays. Indexing in a list results to fetching a
single element whereas Slicing allows to fetch a set of elements.

Code:-
tuple1=(10,11,12,13,14,15)
tuple2=tuple1[3:5]
print(tuple2)

Output:- (13, 14)

# 2. Identify and resolve syntactic and semantic issues in the given code snippet

1} append() :- The append() method in python adds a single item to the existing list.

syntax: list.append(value)

ex: fruits=[‘apple’,’cherry’] fruits.append(“orange”)


print(fruits) # output:[‘apple’,’cherry’,’orange’]
2} count() :- The count() method returns the number of times a specified value appears in the string.

Syntax: list.count(value) ex:


points=[1,4,2,9,7,8,9,3,1]
x=points.count(9)
print(x) # output:2
3} index() :- The index() method returns the position at the first occurrence of the specified value.
Syntax: list.index(value) ex:
carno=[‘ka04’,’ka02’,’ka05’,’ka02’]
y=carno.index(“ka02”)
print(y) # output:3
4}extend() :- The extend() method adds all the elements of an iterable (list, tuple, string etc.) Syntax:
list.extend(value)
ex: u=[‘hii’,’hello’] bite=(6,7,8.4)
u.extend(bite)
print(u) # output:[‘hii’,’hello’,6,7,8,4] 5}insert() :- The
insert() method inserts the specified value at the specified position. Syntax: list.insert(value) ex:
who=[‘sun’,’earth’] who.insert(1,”moon”)
print(who) # output:[‘sun’,’earth’,1,’moon’]

#03) To access specific value of a dictionary, we must pass its key,


>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> x=dict1 ["brand"]
>>> X
Output:- 'mrcet'

# 2. Identify and resolve syntactic and semantic issues in the given code snippet
1}(dictionary)syntax:dict{values}
2}(index)syntax: Using list comprehension with enumerate() 3}(iteration)syntax:for loop, use
items(value) or use keys()

Semantic error:-

Error will show on executing time when any keyword later placed wrong.
……………………………………………………………………………………………………………………………
……………………………………………………

8.1 Code, execute and debug the programs to perform using string manipulation.
String:-
Strings in python are surrounded by either single quotation marks, or double quotation marks.

Code :-
>>> a="hello welcome to python program"
>>> print(a)
hello welcome to python program
>>> a.capitalize()
'Hello welcome to python program'
>>> print(a)
hello welcome to python program
>>> res=a.capitalize()
>>> print(res)
Hello welcome to python program
>>> b="HELLO"
>>> print(b)
HELLO
>>> b.center(11,"x")
'xxxHELLOxxx'
>>> a.center(11,"x")
'hello welcome to python program'
>>> a.count("o",0,len(a))
5
>>> a.endswith("g",0,len(a)) False
>>> a.endswith("x",0,len(a))
False
>>> a.find("o",0,len(a))
4
>>> a.index("m",0,len(a))
11
>>> print(a)
hello welcome to python program
>>> a.islower()
True
>>> c="Hello"
>>> c.islower()
False
>>> print(a)
hello welcome to python program
>>> a.isupper()
False
>>> c="HELLO"
>>> c.isupper()
True

8.2:- Code, execute and debug the programs to perform using array manipulation.

Array :- Arrays are used to store multiple values in one single variable:

Code a):-
cars = ["Ford", "Volvo", "BMW"] #output :- ['Ford', 'BMW'] cars.pop(1)
print(cars)

Code b):-
import numpy as np #output:- Array with Rank 1:
arr = np.array([1, 2, 3]) [1 2 3] print("Array with Rank 1:
\n",arr) Array with Rank 2: arr = np.array([[1, 2, 3],
[[1 2 3] [4, 5, 6]]) [4 5 6]]
print("Array with Rank 2: \n", arr) Array created using arr = np.array((1, 3, 2))
passed tuple: print("\nArray created using " [1 3
2]
"passed tuple:\n", arr)

8.3:- Identify and resolve syntactic and semantic issues in the given code snippet

Syntax :- Array in Python can be created by importing array module. array(data_type, value_list) is used to
create an array with data type and value list specified in its arguments.

cars = ["Ford, "Volvo", "BMW"] cars.pop(1)


print(cars)
SyntaxError: invalid syntax

Semantic error:-
cars = ["Ford, "Volvo", "BMW"] crs.pop(1)
print(cars)
Traceback (most recent call last)
File "F:/Program Files X Install/Python/thh.py", line 2, in <module>
crs.pop(1
NameError: name 'crs' is not defined
…………………………………………………………………………………………………………………………
9.1 :- Code, execute and debug programs to solve the given problems using built in function

Built-in :- This function supports dynamic execution of Python code. object must be either a string or a code object.

Code :-
s = "This is good" #Output :- True print(all(s))
True
True

s = '000'
print(all(s))
s = ''
print(all(s))

9.2 :- Code, execute and debug programs to solve the given problem by defining a function.

Code :- def sum():


x=int(input("Enter the first no.")) #Output:- Enter the first no. 5
y=int(input("Enter the second no.")) Enter the second no. 4
z=x+y 9 print(z) sum()

9.3 :- Code, execute and debug programs to solve the given problem using recursion.

Recursion :- The term Recursion can be defined as the process of defining something in terms of itself. In
simple words, it is a process in which a function calls itself directly or indirectly.

Code :-
def recursive_fibonacci(n): if n <= 1: return n else: return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))

n_terms = 10

if n_terms <= 0:
print("Invalid input ! Please input a positive value") else: print("Fibonacci
series:") for i in range(n_terms):
print(recursive_fibonacci(i))

Output :-
Fibonacci series:
0
1
1
2
3
5
8
13
21
34

9.4 :- Define anonymous function and code to solve the given problem.
Anonymous function :- A lambda function is a small anonymous function. A lambda function can take any
number of arguments, but can only have one expression.

Syntax :- lambda arguments : expression

Output :- 22
33

9.5 :- Identify and resolve syntactic and semantic issues in the given code snippet.

Syntactic error:-
Keywords are only allowed to be used in specific situations. If you use them incorrectly, then you’ll have invalid
syntax in your Python code.

…………………………………………………………………………………………………………………………

10.1 :- Create Modules and Packages.

Code : - a) def summation(num1,num2):

return num1+num2

b) def multiplication(num1,num2):
return num1*num2

Step 1 : To create a module just save the code you want in a file with the file extension .py

Step 2 : Save this code in a file named sum.py , mul.py

Step 3 : Import the module named cal.py , and call the greeting function:

Step 4 : Save this code in the file mymodule

Code :- import sum


import mul
print(sum.summation(1,5))
print(mul.multiplication(2,5))

Output :- 6
10

10.2:- Code, execute and debug the programs using built in function.
A) Code:- >>> import platform
>>> platform.system()
'Windows'
>>> platform.version()
'10.0.19042'
>>> platform.python_version()
'3.9.7'
b) Code :- >>> import math
>>> math.sqrt(25)
5.0
>>> math.factorial(4)
24
>>> math.pow(2,3)
8.0
>>> math.ceil(2.4)
3
>>> math.floor(2.4)
2
>>> math.sin(2)
0.9092974268256817
>>> math.cos(0.5)
0.8775825618903728
>>> math.gcd(5,15)
5

11.1 :- Code, execute and debug programs using NumPy module.


NumPy : Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional
array object, and tools for working with these arrays. It is the fundamental package for scientific computing with
Python.
Code :-
import numpy as np arr=np.array([1,2,3])
print("Array with Rank 1:\n",arr)

arr=np.array([[1,2,3], [4,5,6]])
print("Array with Rank 2:\n",arr)

arr=np.array((1,3,2)) print("\nArray created


using"
"Passed tuple:\n",arr)
Output :-

Array with Rank 1:


[1 2 3]
Array with Rank 2:
[[1 2 3]
[4 5 6]]
Array created usingPassed tuple:
[1 3 2]

11.2 :- Code, execute and debug programs using series.

Series:- Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float,
python objects, etc.)
Code :-
import pandas as pd import numpy as np
data=np.array(['W','e','l','c','o','m'])
ser=pd.Series(data)
print(ser)

Output :-

0 w
1 e
2 l
3 c
4 o
5 m
dtype: object

11.3 :- Code, execute and debug programs using dataframes.

Dataframe :- Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure with
labeled axes (rows and columns).
Code :-
import pandas as pd

lst = ['India', 'Dubai', 'Japan', 'America',


'Russia', 'Germany', 'London']
df = pd.DataFrame(lst)
print(df)

Output :-
0
0 India
1 Dubai
2 Japan
3 America
4 Russia
5 Germany
6 London

……………………………………………………………………………………………………………………………
……………………………………………………
12.1 :- write code snippet to perform following operations on different types of files .

(a) read file (b) write to file.

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

file.

Code :-
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
with open("myfile.txt", "w") as file1:
file1.write("Hello \n") file1.writelines(L)
file1.close() with open("myfile.txt", "r+") as file1:
print(file1.read())

Output :-

Hello
This is Delhi
This is Paris
This is London

(b) write to file :- To write to an existing file, you must add a parameter to the open() function. “a” –
Append - will append to the end of file

Code :-
f=open("demofile2.txt","a")
f.write("Now the file has more content !")
f.close

Output :-

Now the file has more content !

12.2. Write code to perform file operations using dataframes on different file types.

Dataframes :- Pandas DataFrame is two-dimensional size-mutable, potentially heterogeneous tabular data structure
with labeled axes (rows and columns).

Code :- import pandas as


pd
data = {'Name':['Tom', 'nick', 'krish', 'jack'],
'Age':[20, 21, 19, 18]} df =
pd.DataFrame(data) print(df)

Output :-
Name Age
0 Tom 20
1 nick 21
2 krish 19
3 jack 18

12.3 Identify and resolve syntactic and semantic issues in the given code snippet

…………………………………………………………………………………………………
13.1 :- Integrate exception handling into above code.
Syntax errors and Exceptions. Errors are the problems in a program due to which the program will stop the
execution.
Code :-
a = [1, 2, 3] try:
print ("Second element = %d" %(a[1]))
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")

Output :-
Second element = 2
An error occurred

13.2 :- Write code snippet to raise exceptions.

Raise exceptions :- exceptions are raised when some internal events occur which changes the normal flow of the

program. Code :-

try:
raise NameError("Hi there") except NameError:
print("An Exception") raise

Output :- raise NameError("Hi


there")
NameError: Hi there

You might also like