Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
33 views21 pages

DSA Lab 1

This lab report introduces Python as a programming language, covering its basic concepts, features, and installation process. It includes hands-on tasks for practicing Python programming, such as arithmetic operations and control flow using if-else statements. The report also discusses data types, functions, and control structures in Python, providing examples and outputs for clarity.

Uploaded by

amjidprogrammer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views21 pages

DSA Lab 1

This lab report introduces Python as a programming language, covering its basic concepts, features, and installation process. It includes hands-on tasks for practicing Python programming, such as arithmetic operations and control flow using if-else statements. The report also discusses data types, functions, and control structures in Python, providing examples and outputs for clarity.

Uploaded by

amjidprogrammer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

UNIVERSITYOF ENGINEERING AND TECHNOLOGY

TAXILA

Submitted To:
Engr. Iqra Jabeen

Submitted By:
Amjid Khan (23-TE-86)

Subject:
Data Structure and Algorithms Lab

DEPARTMENT OF TELECOMMUNICATION
ENGINEERING
1

Lab Report: 1
Introduction to Python and Demonstration of Python Basic Concepts

Objective:
➢ Introduce Python as a programming language.
➢ To understand the basics of Python programming language.
➢ Set up the Python environment.
➢ Demonstrate basic concepts like variables, data types, operators, control structures, and
functions.
➢ Encourage hands-on practice.
➢ Prepare learners for more advanced Python topics.

Theory:

Programming language:
A Programming language is a formally constructed language designed to communicate
instructions to a machine, particularly a computer. Programming languages can be used to create
programs to control the behavior of a machine or to express algorithms. Traits often considered
important for what constitutes a programming language include.

Function and target:


A computer programming language is a language used to write computer programs, which involve
a computer performing some kind of computation or algorithm and possibly controlling devices
such as printers, disk drives, robots, and so on. More generally, a programming language may
describe computation on some, possibly abstract, machine.

Abstractions:
Programming languages usually contain abstractions for defining and manipulating data
structures or controlling the flow of execution. The practical necessity that a programming
language supports adequate abstractions is expressed by the abstraction principle; this principle
is sometimes formulated as a recommendation to the programmer to make proper use of such
abstractions.
2

Types and Programming Languages:

Python Programming Language:


Python is a high-level, general-purpose, and very popular programming language. Python
programming language (latest Python 3) is being used in web development and machine Learning
applications, along with all cutting-edge technology in the Software Industry. Python
Programming Language is very well suited for Beginners, also for experienced programmers with
other programming languages like C++ and Java.
1. Python is currently the most widely used multi-purpose, high-level programming
language.
2. Python allows programming in Object-Oriented and Procedural paradigms.
3. Python programs generally are smaller than other programming languages like Java.
Programmers have to type relatively less and the indentation requirement of the language
makes them readable all the time.
4. Python language is being used by almost all tech-giant companies like – Google, Amazon,
Facebook, Instagram, Dropbox, Uber etc

Features of Python:
Some major features of python are given below.

1. Easy to Learn and Use: Python has a simple syntax that resembles natural language,
making it accessible for beginners.
2. Interpreted Language: Python code is executed line-by-line, allowing for quick testing
and debugging.
3. Cross-Platform: Python runs on various operating systems like Windows, macOS, and
Linux without modification.
4. Extensive Standard Library: Python comes with a large standard library, providing
modules and functions for tasks like file handling, internet protocols, and more.
5. Object-Oriented: Python supports object-oriented programming (OOP) concepts like
classes and inheritance, making it versatile and scalable.
6. Dynamic Typing: Variables in Python do not require explicit declaration of their data
type, offering flexibility in coding.
7. Large Community and Support: Python has a vast, active community, which means
extensive documentation, tutorials, and third-party packages are readily available.
8. Versatile and Extensible: Python can be used for web development, data analysis,
automation, scientific computing, and more, with the ability to integrate with other
languages like C/C++.
9. Open Source: Python is free to use and distribute, with a strong community contributing
to its development.
3

Python Installation

Download Python:
Go to the official Python website: python.org.
Navigate to the "Downloads" section.
Choose the appropriate version for your operating system (Windows, macOS, or Linux).

Run the Installer:


Open the downloaded installer file.
On Windows, make sure to check the box that says "Add Python to PATH" before clicking "Install
Now."
Follow the prompts to complete the installation.
4

Verify Installation:
Open a terminal or command prompt.
Type python --version or python3 --version and press Enter.
If installed correctly, it will display the Python version number.

Install an IDE (Optional):


You can install an Integrated Development Environment (IDE) like PyCharm, VS Code, or use
Jupyter Notebook for writing and running Python code.
After installation, Python is ready to use, and you can start coding right away!

Integrated Development and Learning Environment:


An Integrated Development and Learning Environment (IDLE) is a software application that
provides comprehensive tools for writing, testing, and debugging code. It’s particularly useful for
beginners learning to code and experienced developers working on projects. Here are the key
aspects:
1. Code Editor:
• An IDLE offers a text editor where you can write, edit, and manage your Python code. It
often includes features like syntax highlighting, auto-completion, and indentation support.
2. Interactive Shell:
• The interactive shell allows you to run Python commands one at a time and see immediate
results, which is excellent for testing small code snippets.
3. Debugger:
• A built-in debugger helps you find and fix errors in your code by stepping through it line
by line, inspecting variables, and setting breakpoints.
5

4. File Management:
• IDLEs often include tools to manage files and projects, making it easier to organize and
navigate your codebase.
5. Learning Features:
• Some IDLEs offer integrated tutorials, code examples, and documentation, helping you
learn Python as you code.
6. Popular IDLEs:
• PyCharm: A powerful IDE with advanced features like code analysis, refactoring, and
integration with version control systems.
• VS Code: A lightweight, customizable code editor with a rich ecosystem of extensions for
Python development.
• Jupyter Notebook: An interactive environment that allows you to write and execute
Python code in a notebook format, great for data science and educational purposes.
• IDLE: The default Python IDE, simple and easy to use, especially for beginners.
Using an IDLE enhances productivity and simplifies the learning process, making it easier to write,
test, and refine your Python code.

Functions:
Functions in Python are blocks of reusable code designed to perform a specific task. They help in
organizing code, making it more modular, and reducing repetition. Here's an overview:

Output using print() function:


print("This is my first dsa class")

Output:
6

Separator:
The print () function can accept any number of positional arguments. To separate these
positional arguments, the keyword argument “sep” is used.

a=10
b=20
c=30
print(a,b,c,sep="-")

Output:

Taking input in Python:

Input ():
This function first takes the input from the user and converts it into a string. The type of the
returned object always will be . It does not evaluate the expression it just returns the complete
statement as string. For example, Python provides a built-in function called input which takes the
input from the user. When the input function is called it stops the program and waits for the user’s
input. When the user presses enter, the program resumes and returns what the user typed.

a=int(input("Enter your age"))


print("Your age is",a)

Output:
7

Taking multiple inputs from user in Python Using split() method:


This function helps in getting multiple inputs from users. It breaks the given input by the specified
separator. If a separator is not provided, then any white space is a separator. Generally, users use
a split () method to split a Python string, but one can use it in taking multiple inputs.

x,y=input("enter two number").split()


print("your two number are:",x,y)

Output:

Python Operators:
Python Operators in general are used to perform operations on values and variables. These are
standard symbols used for logical and arithmetic operations. We will investigate different types
of Python operators.

• OPERATORS: Are special symbols. Eg- +, * , /, etc.


• OPERAND: It is the value on which the operator is applied.

Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, and division.
In Python the result of division is a floating-point while in Python 2.x division of 2 integer was an
integer and to obtain an integer result in Python 3.x floored (// integer) is used.

a = 2
b = 4
Add = a + b
Sub = b - a
Mul = a * b
8

Div = b / a
Mod = b % a

print(f"Add = {Add}\nSub = {Sub}\nMul = {Mul}\nDiv =


{Div}\nMod = {Mod}")

Output:

PRECEDENCE:
• P – Parentheses
• E – Exponentiation
• M – Multiplication (Multiplication and division have the same precedence)
• D – Division
• A – Addition (Addition and subtraction have the same precedence)
• S – Subtraction

Comparison Operators:
Comparison of Relational operators compares the values. It either returns True or False according
to the condition.

a=7
b=8
print(a<b)
print(b==a)
print(b!=a)
9

print(b>a)

Output:

Assignment Operators:
Assignment operator are used to assign a value to a variable.
It is represented by the symbol (=).
Like: x=5
y=10
z=x+y

Precedence and Associativity of Operators:


This is used in an expression with more than one operator with different precedence to
determine which operation to perform first.

var=2+5*4/3
print(var)

Output:
10

Type Conversion in python:


Python defines type conversion functions to directly convert one data type to another which is
useful in day-to-day and competitive programming.

Implicit Type Conversion:


In Implicit type conversion of data types in Python, the Python interpreter automatically
converts one data type to another without any user involvement.

x=10
y="This is my string"
print('x is a type of:', type(x))
print('y is a type of:', type(y))

Output:

Data Types:

Strings in Python:
A string is a sequence of characters that can be a combination of letters, numbers, and special
characters. It can be declared in Python by using single quotes, double quotes, or even triple
quotes. These quotes are not a part of a string, they define only the starting and ending of the
string. Strings are immutable, i.e., they cannot be changed. Each element of the string can be
accessed using indexing or slicing operations.

Accessing characters in Python String:


In Python, individual characters of a String can be accessed by using the method of Indexing.
Indexing allows negative address references to access characters from the back of the String, e.g.
- 1 refers to the last character, -2 refers to the second last character, and so on.
11

Updating Strings:
You can "update" an existing string by (re)assigning a variable to another string. The new value
can be related to its previous value or to a completely different string altogether.

Lists in Python:
Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and
Array List in Java). In simple language, a list is a collection of things, enclosed in [ ] and separated
by commas.

A=['a','b','c']
print(A)

Tuples in Python:
A tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple
can be of any type, and they are indexed by integers. The values of a tuple are syntactically
separated by ‘commas. Although it is not necessary, it is more common to define a tuple by closing
the sequence of values in parentheses. This helps in understanding the Python tuples more easily.

t=(1,2,3,4,5,6,7,8,9)
print(t)

Output:
12

Sets in Python:
In Python, a Set is an unordered collection of mutable data types with no duplicate elements. The
order of elements in a set is undefined though it may consist of various elements.

s={1,2,3,4,5,6,7,8,9}
s2={1,2,3,'a','b','c'}
print(s)
print(type(s))
print(s2)

Output:

Dictionary in Python:
A dictionary in Python is a collection of key values, used to store data values like a map, which,
unlike other data types holds only a single value as an element. In Python, a dictionary can be
created by placing a sequence of elements within curly {} braces, separated by a ‘comma’. The
dictionary holds pairs of values, one being the Key and the other corresponding pair element
being its Key: value. Values in a dictionary can be of any data type and can be duplicated, whereas
keys can’t be repeated and must be immutable.

d={1:'Amjid',2:'Shahen',3:'Khan'}
print(d)
print(d[1])

Output:
13

Python Functions:
Python Functions is a block of statements that return the specific task. The idea is to put some
commonly or repeatedly done tasks together and make a function so that instead of writing the
same code again and again for different inputs, we can do the function calls to reuse code
contained in it repeatedly.

Calling a Python Function:


After creating a function, we can call it by using the name of the function followed by parenthesis
containing the parameters of that function.

Control Flow in Python:


Decision-making statements in programming languages decide the direction of the flow of
program execution. In Python, the if-else elif statement is used for decision-making.

def myfunction():
print('This is my function')

myfunction()

Output:

if statement:
if statement is the simplest decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a
block of statement is executed otherwise not.

a=10
if (a>5):
print('You are not a kid')
else:
print('You are a kid')
14

Output:

if-else:
if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here
comes the else statement. We can use the else statement with if statement to execute a block of
code when the condition is false.

num=int(input("enter an integer"))

if (num%2==0):
print("This is an even number")

else:
print("This is an odd number")

Output:

For Loops:
Python For loop is used for sequential traversal i.e. it is used for iterating over an iterable like
String, Tuple, List, Set, or Dictionary. In Python, there is no C style for loop, i.e., for (i=0;
i<n;i++).There is a for loop like each loop in each language.

for i in range(100):
print(i)
15

Output:

While Loop:
Python While Loop executes a block of statements repeatedly until a given condition is satisfied.
When the condition becomes false, the line immediately after the loop in the program is
executed.

i=0
while (i<20):
i=i+1
print(i,"UET TAXILA")

Output:
16

Break statement:
Python break is used to terminate the execution of the loop.

for i in range(10):
print(i)
if i == 5:
break

Output:

Python Continue Statement:


Python Continue Statement ends the iteration from loops and starts to continue the next
iteration.

for i in range(10):
if i == 5:
continue
print(i)

Output:
17

Lab Tasks:
Write a program that performs all arithmetic operations (addition, subtraction, multiplication,
division) on two variables by taking input from the user at run time.

a = int(input("Enter first number."))


b = int(input("Enter second number."))
Add = a + b
Sub = b - a
Mul = a * b
Div = b / a
Mod = b % a

print(f"Add = {Add}\nSub = {Sub}\nMul = {Mul}\nDiv =


{Div}\nMod = {Mod}")

Output:

Write a program if else statement to check whether a character entered by the user at run-time
is a vowel.

#Write a program if else statement to check whether a


character entered by the user at run-time
#is a vowel.

ch = input("Enter a character: ").lower()


if ch in ('a','e','i','o','u'):
print("This character is vowel")
18

else:
print("This character is Consonant")

Output:

Write a Python program to check whether a given number is an even or an odd number.

#Write a Python program to check whether a given number


is an even or an odd number.

num = int(input("Enter a number:"))

if (num % 2 == 0):
print(num,"is an Even number.")

else:
print(num,"is an Odd number.")

Output:
19

Write a program that displays the average and percentage of given subjects.

#Write a program that displays the average and


percentage of given subjects.
sub1 = int(input("Enter the marks of your first
Subject."))

sub2 = int(input("Enter the marks of your second


Subject."))

sub3 = int(input("Enter the marks of your third


Subject."))

sub4 = int(input("Enter the marks of your fourth


Subject."))

sub5 = int(input("Enter the marks of your fifth


Subject."))

ave = (sub1 + sub2 + sub3 + sub4 + sub5)/5

per = ((sub1 + sub2 + sub3 + sub4 + sub5)/500)*100

print("The average is:", ave)


print("The percentage is:", per,"%")

Output:
20

Write a program to print the below pattern of stars (*) using loops.

rows = 5
for i in range(1, rows + 1):
print(" " * (rows - i), end="")
print("* " * i)

Output:

You might also like