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

Merge Lab Till 11 PF

The document discusses variables and data types in Python programming. It defines a variable as a reserved memory location used to store values. It outlines rules for constructing variable names in Python and provides examples of assigning values to single and multiple variables. The document also discusses Python keywords, which are reserved words that cannot be used as variable or function names. Finally, it briefly introduces different data types in Python like integers, floating point numbers, strings, and Boolean values.
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)
71 views

Merge Lab Till 11 PF

The document discusses variables and data types in Python programming. It defines a variable as a reserved memory location used to store values. It outlines rules for constructing variable names in Python and provides examples of assigning values to single and multiple variables. The document also discusses Python keywords, which are reserved words that cannot be used as variable or function names. Finally, it briefly introduces different data types in Python like integers, floating point numbers, strings, and Boolean values.
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/ 59

Programming Fundamentals (CS-116L) LAB # 01

LAB # 01

INTRODUCTION

OBJECTIVE
To become familiar with the Python Programming by using an Integrated Development
Environment

THEORY
Programming
The act of writing computer programs is called computer programming. A computer program is a
sequence of instructions written using a computer programming language to perform specified tasks
by the computer. There are a large number of programming languages that can be used to write
computer programs, for example: Python, C, C++, Java, PHP, Perl, Ruby etc.

Python Programming Language


Python is a general-purpose, interpreted, object-oriented programming language. Python was
created by Guido van Rossum in the Netherlands in 1990. Python has become a popular
programming language widely used in industry and academia due to its simple, concise, and
intuitive syntax and extensive library. Python is a general-purpose programming language. That
means Python can be used to write code for any programming task. Python is now used in the
Google search engine and in mission-critical projects at NASA etc. Python is interpreted, which
means that Python code is translated and executed by an interpreter.

Integrated Development Environment


An Integrated Development Environment (IDE) is a software application that provides
comprehensive facilities to computer programmers for software development. Typically, an IDE
contains a code editor, a compiler or interpreter and a debugger that the developer accesses through
a single graphical user interface (GUI). An IDE may be a standalone application, or it may be included
as part of one or more existing and compatible applications. IDEs are also available online that can
be accessed through a web browser.

Using an IDE will save a lot of time and effort in writing a program. However, one should be careful
of some of the pitfalls of using an IDE as it may not be ideal for everyone and might not be suitable
in every situation. Some IDEs are very complicated to use and may consume a lot of resources.

Many IDEs support Python Programming Language. Some of the popular IDEs are listed below.

Standalone IDEs:
• Microsoft Visual Studio Code
https://code.visualstudio.com/
• Eclipse

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 1|Page
Programming Fundamentals (CS-116L) LAB # 01

https://www.eclipse.org/downloads
• NetBeans
https://netbeans.org/downloads/
• Thonny
https://thonny.org/
• Anaconda
https://www.anaconda.com/distribution/

Online IDEs:
• Ideone
https://ideone.com/
• Online GDB
https://www.onlinegdb.com/online_python_debugger

Creating a Python program file with Thonny


Thonny is a free Python Integrated Development Environment (IDE) that is designed for beginners.
Thonny comes with Python 3.7 built in, so just one simple installer is needed to get started.

Step#1: Go to https://thonny.org

Step#2: Download the version for Windows and wait a few seconds while it downloads.

Step#3: Run the .exe file.


Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 2|Page
Programming Fundamentals (CS-116L) LAB # 01

Step#4: Follow the installation wizard to complete the installation process and just click "Next".

Step#5: After completing the installation, open Thonny IDE. A window as shown in the following
figure should open.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 3|Page
Programming Fundamentals (CS-116L) LAB # 01

A simple Python program


Following is a simple Python program.
#Description: Display two messages
'''Writes the words "Hello, World! and Python is fun" on the screen'''
print("Hello, World! \n Python is fun")

print("Hello, World! \n Python is fun") instructs the computer to print on the screen the string of
characters enclosed by the quotation marks.

\n is an escape sequence that means newline. It causes the cursor to position to the beginning of the
next line on the screen.

pound sign (#) is a comment on a line, called a line comment, or enclosed between three consecutive
single quotation marks (''') on one or several lines, called a paragraph comment.

Python programs are case sensitive. It would be wrong, for example, to replace print in the program
with Print. Several special characters can be seen (#, ", ()) in the program. They are used in almost
every program. Table 1.1 summarizes their uses.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 4|Page
Programming Fundamentals (CS-116L) LAB # 01

Table1.1: Special characters


Character Name Description
() Opening and closing parentheses Used with function
# Pound sign or comment Precedes a comment line
“ “ Opening and closing quotation marks Encloses a string (i.e.,sequence
of characters)
‘‘’ ‘’’ Paragraph comments Encloses a paragraph comment

Build and Run a Python Program

Step#1: Go to File > New. Then save the file with .py extension.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 5|Page
Programming Fundamentals (CS-116L) LAB # 01

Step#2: Write your code in .py file.

Step#3: Then Go to Run > Run current script or simply click F5 to run it

The output would be displayed in a separate window.

EXERCISE
A. Create a file named lab1.py. Write the following code in the file. Execute it and show the
output. (You can use the Snipping Tool to take a snapshot of your output window).
1. Code:
# My first program
print("\nWelcome in the world of programming!")

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 6|Page
Programming Fundamentals (CS-116L) LAB # 01

Output:

2. Code:
#My second program
print("Welcome in the\n ")
print("world of programming! ")

Output:

B. Write a program in Python language that prints your bio-data on the screen. Show your
program and its output

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 7|Page
Programming Fundamentals (CS-116L) LAB # 02

LAB # 02

VARIABLES AND OPERATORS

OBJECTIVE
Implement different type of data types, variables and operators used in Python.

THEORY

Variable
Variables are nothing but reserved memory locations to store values. This means that when you create
a variable you reserve some space in memory.

Rules for constructing variable names


A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:

• A variable name must start with a letter or the underscore character


• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)

Example
x= 5
y= "John"
print(x)
print (y)

Output:
>>> %Run task1.py
5
John

Variables do not need to be declared with any particular type and can even change type after they have been
set.

Example:

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 1|Page
Programming Fundamentals (CS-116L) LAB # 02

x= 4
x= "Sally"
print(x)

Output:
>>> %Run task2.py
Sally

Assign Value to Multiple Variables


Python allows you to assign values to multiple variables in one line

Example:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Output:
>>> %Run task3.py
Orange
Banana
Cherry

To combine both text and a variable, Python uses the + character

Example:
x= "awesome"
print("Python is " , x)

Output:
>>> %Run task4.py
Python is awesome

Python Keywords
Keywords are the words whose meaning have already been explained to the Python compiler. The
keywords cannot be used as variable names,function name or any identifier because if we do so we
are trying to assign a new meaning to the keyword, which is not allowed by the computer. Keywords
are also called ‘Reserved words’. Some keywords are as follows:

false class finally Is return none continue for try break


true def for From while and del not with as
elif if or except in raise yield

Data Types
Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 2|Page
Programming Fundamentals (CS-116L) LAB # 02

Data types specify how we enter data into our programs and what type of data we enter. Python Data
Types are used to define the type of a variable.
Python has five standard data types −
• Numbers (int, float)
• String
• List
• Tuple
• Dictionary

You can get the data type of any object by using the “type( )” function.

Operators
Operators are special symbols in Python that carry out arithmetic or logical computation.

Python divides the operators in the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x**y
// Floor division x // y

Python Relational Operators


Comparison operators are used to compare two values:
Operator Name Example
== Equal x==y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Python Logical Operators
Logical operators are used to combine conditional statements:
Operator Name Example
and Return True if both statements are true x < 10 and x > 5
Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 3|Page
Programming Fundamentals (CS-116L) LAB # 02

or Return True if one of the statements is x < 5 or x < 4


true
not Reverse the result, returns False if the not (x<5 and x< 10)
result is true

EXERCISE
A. Point out the errors, if any,and also paste the output in the following Python statements.

1. x=5:
print(x)

2. 1TEXT
=

"SSUET"
NUMBER = 1
print(NUMBER+ TEXT)

3. a = b
= 3 =
4

B.
Evaluate the operation in each of the following statements, and show the resultant value after
each statement is executed.

1. a = 2 % 2 + 2 * 2 - 2 / 2;

2. b = 3
/ 2 +
5 * 4
/ 3 ;

3. c = b
= a =
3 + 4
;

C. Write
the
following

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 4|Page
Programming Fundamentals (CS-116L) LAB # 02

Python programs:

1. Write a program that calculates area of a circle 𝐴 = 𝜋𝑟 2 . (Consider r = 50).

2. Write a program that performs the following four operations and prints their result on the screen.
a. 50 + 4
b. 50 – 4
c. 50 * 4
d. 50 / 4

3. Write a Python program to convert height (in feet and inches) to centimeters. Convert height of
5 feet 2 inches to centimeters.

• First, convert 5 feet to inches: 5 feet × 12 inches/foot = 60 inches


• Add up our inches: 60 + 2 = 62 inches
• Convert inches to cm: 62 inches × 2.54 cm/inch = 157.48 cm

4. Write a program to compute distance between two points by creating variables (Pythagorean
Theorem)
Distance =((x2−x1)^2+(y2−y1)^2)^1/2

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 5|Page
Programming Fundamentals (CS-116L) LAB # 03

LAB # 03

CONSOLE INPUT AND OUTPUT

OBJECTIVE
Taking input from user and controlling output position.

THEORY

Console I/O Functions


The keyboard and visual display unit (VDU) together are called a console. Python programming
language provides many built-in functions to read any given input and to display data on screen,
Console (also called Shell) is basically a command line interpreter that takes input from the user i.e
one command at a time and interprets it. If it is error free then it runs the command and gives required
output otherwise shows the error message.

Accepting Input from Console


To take input from the user we make use of a built-in function input().

Syntax : input(prompt)

Displaying Input from Console


The print( ) function prints the specified message to the screen, or other standard output device.

The message can be a string, or any other object, the object will be converted into a string before
written to the screen.

Syntax: print(object(s), separator=separator, end=end, file=file, flush=flush)

Example:
name=input('Please enter your name: "') print("Hello, " , name ,
"!")

Output:
>>> %Run task1.py Please enter your name:ABC
Hello, ABC!
>>>

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 1|Page
Programming Fundamentals (CS-116L) LAB # 03

Whatever you enter as input, input function convert it into a string. if you enter an integer value still
input() function convert it into a string. You need to explicitly convert it into an integer in your code
using typecasting.

Example:
# Program to check input
num = input ("Enter number :")
print(num)
name1 = input("Enter name : ")
print(name1)

# Printing type of input value


print ("type of number",type(num))
print ("type of name",type(name1))

We can also type cast this input to integer, float or string by specifying the input() function inside the
type.
Typecasting the input to Integer/Float: There might be conditions when you might require integer
input from user/console, the following code takes two input(integer/float) from console and typecasts
them to integer then prints the sum.

Example
# input num1 =
int(input()) num2
= int(input())

# printing the sum in integer


print(num1 + num2)

Escape Sequence
In Python strings, the backslash "\" is a special character, also called the "escape" character. An
escape sequence is a sequence of characters that does not represent itself when used inside a character
or string literal, but is translated into another character or a sequence of characters that may be
difficult or impossible to represent directly.

Escape Description
Example Output
Sequence
\\ Prints Backslash print ("\\") \
\` Prints single-quote print ("\'") '
\" Pirnts double quote print ("\"") "
print hello
\n ASCII linefeed ( LF )
("hello\nworld") world
ASCII backspace ( BS ) removes print ("az" + "\b"
\b ac
previous character + "c")
Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 2|Page
Programming Fundamentals (CS-116L) LAB # 03

ASCII horizontal tab (TAB). Prints


\t print ("\t*hello") *hello
TAB

EXERCISE

A. Point out the errors or undefined/missing syntax, if any, in the following python programs.

1. print("Hello \b World!")

2. first_number = str (input ("Enter first number") )


second_number = str (input ("Enter second number") )
sum = (first_number + second_number)
print("Addition of two number is: ", sum)

3. age = 23
message = "Happy " + age + "rd Birthday!" print(message)

B. What would be the output of the following programs:

1. a=5
print("a =", a, sep='0', end=',')

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 3|Page
Programming Fundamentals (CS-116L) LAB # 03

2. name = input("Enter Employee Name")


salary = input("Enter salary")
company = input ("Enter Company name")
print("Printing Employee Details")
print ("Name", "Salary", "Company")
print (name, salary, company)

3. n1=int(input('"enter n1 value'))
n2=int(input('enter n2 value'))

C. Write Python programs for the following:

1. Write a program to print a student’s bio data having his/her Date of birth, Roll no, Section,
Percentage and grade of matriculation and Intermediate. All the fields should be entered from the
console at run time.

2. Write a program that asks the user what kind of food they would like. Print a message about that
food, such as “Let me see if I can find you a Chowmein”. Food name must be in uppercase.
(hint: use upper( ) for food name)
3. Take the marks of 5 courses from the user and calculate the average and percentage, display the
result:
Eachcourse=50 marks
Total_marks= course1+course2+course3+course4+course5
average=Total_marks/5
percentage=(Total_marks x 100)/250

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 4|Page
Programming Fundamentals (CS-116L) LAB # 04

LAB # 04

DECISIONS

OBJECTIVE
To get familiar with the concept of conditional statement for simple decision making.

THEORY
Decision making statements in programming languages decides the direction of flow of program
execution.
The if…elif…else statement is used in Python for decision making.

The if Statement
Like most languages, python uses the keyword if to implement the decision control instruction. 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. The general form of if
statement looks like this:

Syntax:
if condition:
# Statements to execute if
# condition is true

As a general rule, we express a condition using python’s ‘relational’ operators. The relational
operators allow us to compare two values to see whether they are equal to each other, unequal, or
whether one is greater than the other. Here is how they look and how they are evaluated in python.

This expression Is true if


x==y x is equal to y
x!=y x is not equal to y
x<y x is less than y
x>y x is greater than y
x<=y x is less than or equal to y
x>=y x is greater than or equal to y

Example:
# python program to illustrate If statement
i = 10
if (i > 15):
print (i, "is greater than 15")
print ("I am not greater")

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 1|Page
Programming Fundamentals (CS-116L) LAB # 04

Output:
>>> %Run task1.py
I am not greater
>>>

The if-else Statement


We can use the else statement with if statement to execute a block of code when the condition is false.

Syntax
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Example:
# python program to illustrate If else statement
i = 20;
if (i < 15):
print (i,“is smaller than 15")
print ("i'm in if Block")
else:
print (i,"is greater than 15")
print ("i'm in else Block")
print ("i'm not in if and not in else Block")

Output:
>>> %Run task2.py
20 is greater than 15
i'm in else Block
i'm not in if and not in else Block
>>>

The if-elif-else Statement


The elif is short for else if. It allows us to check for multiple expressions. If the condition
for if is False, it checks the condition of the next elif block and so on. If all the conditions are False,
body of else is executed.
Syntax
if (condition):
statement
elif (condition):
statement
.
.
else:
statement

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 2|Page
Programming Fundamentals (CS-116L) LAB # 04

Example:
# Python program to illustrate if-elif-else
i = 30
if (i == 10):
print ("i is 10")
elif (i == 20):
print ("i is 20")
elif (i == 30):
print ("i is 30")
else:
print ("i is not present")
Output:
>>> %Run task3.py
i is 30
>>>

EXERCISE

C. Point out the errors, if any, and paste the output also in the following Python programs.
1. Code
a = 500,b,c;
if ( a >= 400 ):
b = 300
c = 200
print( "Value is:", b, c )

2. Code
&number = eval(input("Enter an integer: "))
print(type(number))
if number % 5 == 0
print("HiFive")
else
print("No answer")

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 3|Page
Programming Fundamentals (CS-116L) LAB # 04

3. Code
if score >= 60.0
grade = 'D'
elif score >= 70.0
grade = 'C'
elif score >= 80.0
grade = 'B'
elif score >= 90.0
grade = 'A'
else:
grade = 'F'

D. What would be the output of the following programs:


1. Code
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")

Output

2. Code
num = 3
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")

Output

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 4|Page
Programming Fundamentals (CS-116L) LAB # 04

3. Code
age = 15
if age < 4:
price = 0
elif age < 18:
price = 1500
else:
price = 2000
print("Your admission cost is Rs" + str(price) + ".")

Output

E. Write Python programs for the following:

1. Any integer is input through the keyboard. Write a program to find out whether it is an odd number
or even number.

2. Write a program that asks for years of service and qualification from the user and calculates the
salary as per the following table:
Years of Service Qualifications Salary
>= 10 Masters 150,000
>= 10 Bachelors 100,000
< 10 Masters 100,000
< 10 Bachelors 70,000

3. Write an if-elif-else chain that determines a person’s stage of life, take input value for the variable
age, and then apply these conditions:

• If the person is less than 2 years old, print a message that the person is a baby.
• If the person is at least 2 years old but less than 4, print a message that the person is a toddler.
• If the person is at least 4 years old but less than 13, print a message that the person is a kid.
• If the person is at least 13 years old but less than 20, print a message that the person is a teenager.
• If the person is at least 20 years old but less than 65, print a message that the person is an adult.
• If the person is age 65 or older, print a message that the person is an elder.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 5|Page
Programming Fundamentals (CS-116L) LAB # 05

LAB # 05

Control Statements
OBJECTIVE:
To get familiar with the concept of control statement for simple controlling and repetition of program
statements.
Theory:

Control Statements (Loops)

In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on. There may be a situation when you need to execute
a block of code several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times.
The following diagram illustrates a loop statement:
Python programming language provides following types of loops to handle looping
requirements.

Loop Type Description


Repeats a statement or group of statements while a given condition is
while loop
TRUE. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the
for loop
code that manages the loop variable.
nested loops You can use one or more loop inside any another while, for loop.

The while Loop


A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is True.
Syntax
The syntax of a while loop in Python programming language is: while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non-zero value. The loop iterates while
the condition is true. When the condition becomes false, program control passes to the line
immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 6|Page
Programming Fundamentals (CS-116L) LAB # 05

Example-1: Example-2:
i=1 i=1
while i < 4: while i < 4:
print i print i
i+=1 i+=1
print “END” print “END”

Output-1: Output-2:

1 END 1
2 END 2
3 END 3
END
Example: Write a program to display factorial of a given number. Program:
n=input("Enter the number: ")
f=1
while n>0:
f=f*n
n=n-1
print "Factorial is", f

Output:
Enter the number: 5 Factorial is 120

The For loop:


The for loop is useful to iterate over the elements of a sequence. It means, the for loop
can be used to execute a group of statements repeatedly depending upon the number of elements
in the sequence. The for loop can work with sequence like string, list, tuple, range etc.
The syntax of the for loop is given below:
for var in sequence:
statement (s)

The first element of the sequence is assigned to the variable written after „for‟ and then the
statements are executed. Next, the second element of the sequence is assigned to the variable and
then the statements are executed second time. In this way, for each element of the sequence, the
statements are executed once. So, the for loop is executed as many times as there are number of
elements in the sequence.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 7|Page
Programming Fundamentals (CS-116L) LAB # 05

for i range(1,5): for i range(1,5):


print i print i
print “END” print “END”

1 END 1
2 END 2
3 END 3
END

Output-1: Output-2:

Example-3: Example-4: 10 9 8 7 6 5 4 3 2 1
Name= "python"
for x in range(10,0,-1):
for letter in Name:
print x,
print letter

Output-3: Output-4:
py t h o n

Exampe: Write a program to display the factorial of given number.


n=input("Enter the number: ")
f=1
for i in range(1,n+1): f=f*i
print "Factorial is",f

Program:
Output:
Enter the number: 5 F
factorial is 12

TASK:
Perform the following tasks using Python source code using loops
• To generate a random number from 3 to 13.
• To print the odd number from 10 to 100 and even numbers from 200 to 96.
• To take an integer value from a user and print the factorial of that number.
• To take two integer values from the user and print the table. The first indicates the table number
and the second value represents the limit of the table.
• To take two integer values from the user and print out the highest and lowest value.
• To calculate the factorial of 3 numbers which will be provided by the user

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 8|Page
Programming Fundamentals (CS-116L) LAB # 06

LAB # 06
NESTED STATEMENTS,
BREAK AND CONTINUE STATEMENTS

OBJECTIVE
Working on nested statements and control loop iteration using break and continue.

THEORY

Nested Statements:
A Nested statement is a statement that is the target of another statement. Nested if:
A Nested if is an if statement that is the target of another if statement. Nested if statements
means an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Example:
#using nested if x=int(input("enter
number=")) y=int(input("enter 2nd
number=")) if x > 2:
if y > 2:
z = x + y
print("z is", z)
else:
print("x is", x)

Output:
>>> %Run task1.py
enter number=3
enter 2nd number=8
z is 11
>>>

Nested loops:
Nested loops consist of an outer loop and one or more inner loops. Each time the outer loop
repeats, the inner loops are reinitialized and start again.
Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 9|Page
Programming Fundamentals (CS-116L) LAB # 06

Example:
height=int(input("Enter height: ")) for
row in range(1, height):
for column in range(1,height):
print(row, end=" ")
print()

Output:
>>> %Run task2.py
Enter height: 7
111111
222222
333333
444444
555555 666666
Keywords break and continue:
The break and continue keywords provide additional controls to a loop.

The Break Statement:


The keyword break in a loop to immediately terminate a loop. Listing example presents a program
to demonstrate the effect of using break in a loop.

Syntax: break

Example:
# Use of break statement inside loop
for word in "string":
if word == "i":
break
print(word)
print("The end")
Output:
>>> %Run 'lab1-task1!.py' s t r
The end
>>>

The continue Statement:


The continue statement breaks out of the current iteration in the loop.

Syntax: continue

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 10 | P a g e
Programming Fundamentals (CS-116L) LAB # 06

Example:
# Program to show the use of continue statement inside
Loops for val in "string":
if val == "i":
continue
print(val)
print("The end")

Output:
>>> %Run 'lab1-task1!.py' s t r n
g The end
>>>

EXERCISE

A. Point out the errors, if any, and paste the output in the following Python programs.

1. Code
prompt = "\nPlease enter the name of a city you have visited:"
prompt+="\n(Enter 'quit' when you are finished.)"
while True:
city = str(input(prompt))
if city == quit:
break;
else:
print("I'd love to go to " , city.title() , "!") Output

2. Code
if x>2: if y>2:
z=x+y
print(“z is”, y)
else:
print (“x is”, x)

Output

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 11 | P a g e
Programming Fundamentals (CS-116L) LAB # 06

3. Code
balance = int(input("enter yourbalance1:"))
while true:
if balance <=9000:
continue;
balance = balance+999.99
print("Balance is", balance)

Output

B. What will be the output of the following programs:

1. Code
i = 10 if
(i==10):
#First if statement
if (i < 15): print ("i is
smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print ("i is smaller than 12 too") else:
print ("i is greater than 15")

Output

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 12 | P a g e
Programming Fundamentals (CS-116L) LAB # 06

2. Code
i = 1 j = 2 k i = 1 j =
= 3 if i > j: 2 k = 3
if i > k: if i > j:
print('A') if i> k:
else: print('A') else:
print('B') print('B')

Output

3. Code
# nested for loops for i in
range(0, 5): for j
in range(i):
print(i, end=' ')
print()

Output

C. Write Python programs for the following:

1. Write a program to add first seven terms twice of the following series:

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 13 | P a g e
Programming Fundamentals (CS-116L) LAB # 06

2. Write a program to print all prime numbers from 900 to 1000.


[Hint: Use nested loops, break and continue]

3. Write a program to display multiplication table (1-5) using nested looping


Sampled output: [hint: '{ } ' .format(value)]
02 X 01 = 02

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 14 | P a g e
Programming Fundamentals (CS-116L) LAB # 07

LAB # 07

FUNCTIONS

OBJECTIVE
Create python function using different argument types.

THEORY

Functions can be used to define reusable code and organize and simplify code. Basically, we can
divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves.

A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
As already known, Python gives you many built-in functions like print(), etc. But also allow to
create your own functions. These functions are called user-defined functions.

Defining a Function:
A function definition consists of the function’s name, parameters, and body. Python allows to define
functions to provide the required functionality. Here are simple rules to define a function in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses
( ( ) ).

• Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.

• The code block within every function starts with a colon (:) and is indented.

Syntax:
def functioname (list of parameters):
Statement

Example:

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 15 | P a g e
Programming Fundamentals (CS-116L) LAB # 07

def greet_user(username): """Display a


simple greeting"""
print("Hello," , username , "!")

Calling a Function:
Calling a function executes the code in the function. If the function returns a value, a call to that
function is usually treated as a value.
Example:
def greet_user(username): """Display a
simple greeting""" print("Hello," ,
username , "!") greet_user('Jesse')

Output:
>>> %Run task1.py Hello, Jesse !
>>>

Return Value:
The python return statement is used in a function to return something to the caller program. Use the
return statement inside a function only.

Example:
def xFunction(x, y):
print(“Add”, x + y) return
xFunction(2, 3)

Output:
>>> %Run task2.py
Add: 5
>>>

When a function doesn’t have a return statement and return statement has no value, the function
returns None.

Argument Types:
An argument is a piece of information that is passed from a function, When a function is called, it
place the value to work with in parentheses.
Following are the ways to call a function by using the following types of formal arguments:

• Required arguments
• Keyword arguments
• Default arguments

Required Arguments:

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 16 | P a g e
Programming Fundamentals (CS-116L) LAB # 07

Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.

Example:
def square(x):
y=x*x return
y x=10
result=square(x)
print("The result of" , x , "squared is", result)

Output:
>>> %Run task2.py
The result of 10 squared is 100 >>>

Keyword Arguments:
Keyword arguments are related to the function calls. When thw keyword argument is used in a
function call, the caller identifies the arguments by the parameter name. This allows to skip the
arguments or place them out of order because the Python interpreter is able to use the keywords
provided to match the values with parameters.

Example:
def print_info(name,age):
"This prints a passed info into this
function"
print("Name:", name) print("Age:" , age)
return
print_info(name ='Mike',age=50)

Output:
>>> %Run task3.py
Name: Mike
Age: 50
>>>

Default Arguments:
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.

Example:

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 17 | P a g e
Programming Fundamentals (CS-116L) LAB # 07

def print_info(name,age=35):
"This prints a passed info into this
function" print("Name:", name)
print("Age:" , age) return

print_info(name ='Mike',age=50)
print_info(name ='Mary')

Output:
>>> %Run task4.py
Name: Mike
Age: 50
Name: Mary
Age: 35 >>>

EXERCISE

A. Point out the errors, if any, and paste the output also in the following Python programs.
1. Code
define sub(x, y)
return x + y

Output

2. Code
define describe_pet(pet_name, animal_type='dog'):
print("\nI have a " , animal_type ,".")
print("My " , animal_type + "'s name is " , pet_name +
".")

Output

2. Code

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 18 | P a g e
Programming Fundamentals (CS-116L) LAB # 07

def type_of_int(i): if i
// 2 == 0: return
'even' else:
return 'odd'

Output

B. What will be the output of the following programs:


1. Code
def test(a):
def add(b):
a =+ 1
return a+b
return
add func = test(4)
print(func(4))

Output

2. Code
def return_none(): return
print(return_none())

Output

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 19 | P a g e
Programming Fundamentals (CS-116L) LAB # 07

3. Code
def test_range(n):
if n in range(3,9):
print( n,"is in the range")
else :
print("The number is outside the given range.")
test_range(7)
test_range(10)
test_range(4)

Output

C. Write Python programs for the following:

1. Write a function called favorite_book() that accepts one parameter, title. The function should
print a message, such as One of my favorite books is Alice in Wonderland. Call the function,
making sure to include a book title as an argument in the function call.

2. Write a function called max( ), that returns the maxium of three integer numbers.

3. Write a Python program to find GCD of two numbers

4. Write a function called describe_city() that accepts the name of a city and its country. The
function should print a simple sentence, such as Reykjavik is in Iceland. Give the parameter for
the country a default value. Call your function for three different cities, at least one of which is
not in the default country.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 20 | P a g e
Programming Fundamentals (CS-116L) LAB # 09

LAB # 08
LISTING

OBJECTIVE
Exploring list/arrays in python programming.

THEORY

A list can store a collection of data of any size. It is a collection which is ordered and changeable.
The elements in a list are separated by commas and are enclosed by a pair of brackets [ ].

Creating a lists:
A list is a sequence defined by the list class but also have alternative for creation of list without
built-in function.
Syntax: With Built-in function list( )
list1 = list() # Create an empty list
list2 = list([2, 3, 4])
# Create a list with elements 2, 3, 4
list3 = list(["red", "green", "blue"])
#Create a list with strings
list4 = list(range(3, 6))
# Create a list with elements 3, 4, 5
list5 = list("abcd") # Create a list with characters a, b, c, d

Without Built-in Function


list1 = []
#Empty list list2 = [2, 3, 4]
#Integer type list
list3 = ["red", "green"]
#String type list list4 = [2, "three", 4] #Mixed
data type list

Example:
#Create list
list_1 = ["apple", "banana", "cherry"]
#display list print("Current List:",list_1)

Accessing items from the list:


An element in a list can be accessed through the index operator, using the following syntax:
myList[index]. List indexes are starts from 0 to len(myList)-1.
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second
last item etc.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 21 | P a g e
Programming Fundamentals (CS-116L) LAB # 09

Example:
myList = ["The", "earth", "revolves", "around", "sun"]
print("Postive index:",myList[4]) print("Negative
index:",myList[-2])
Output:
>>> %Run task1.py
Postive index: sun Negative index: around

List Slicing [start : end]:


The index operator allows to select an element at the specified index. The slicing operator returns a
slice of the list using the syntax list[start : end]. The slice is a sublist from index start to index end
– 1.
Example:
list1= [1,2,4,5,6,7,8]
print("Slicing 2 to 5 index:",list1[2:5]) print("Slicing before
3rd index value:",list1[:3]) print("Slicing after 3rd index
value:",list1[3:])

Output:
>>> %Run task2.py
Slicing 2 to 5 index: [4, 5, 6]
Slicing before 3rd index value: [1, 2, 4] Slicing
after 3rd index value: [5, 6, 7, 8]

Modifying Elements in a List:


The syntax for modifying an element is similar to the syntax for accessing an element in a list.
Example:
#Create a list
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles) #Modify list through indexes
motorcycles[0] = 'Swift' print(motorcycles)
Output:
>>> %Run task3.py
['honda', 'yamaha', 'suzuki']
['Swift', 'yamaha', 'suzuki']

List Methods for Adding , Changing and Removing items:


Python has a set of built-in methods that you can use on lists/arrays.
Method Description
append( ) Adds an element at the end of the list

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 22 | P a g e
Programming Fundamentals (CS-116L) LAB # 09

copy( ) Returns a copy of the list


count( ) Returns the number of elements with the specified value
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 first item with the specified value
reverse( ) Reverses the order of the list
sort( ) Sorts the list

EXERCISE

A. Point out the errors, if any, and paste the output also in the following Python programs.
1. Code

Output

2. Code
motorcycles = {'honda', 'yamaha', 'suzuki'}
print(motorcycles) del motorcycles(0)
print(motorcycles)

Output:

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 23 | P a g e
Programming Fundamentals (CS-116L) LAB # 09

3. Code
Def dupe_v1(x):
y = []
for i in x:
if i not in y:
y(append(i))
return y
a = [1,2,3,4,3,2,1]
print a
print dupe_v1(a)

Output:

B. What will be the output of the following programs:


1. Code
list1= [1,2,4,5,6,7,8]
print("Negative Slicing:",list1[-4:-1]) x
= [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("Odd number:", x[::2])

Output

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 24 | P a g e
Programming Fundamentals (CS-116L) LAB # 09

2. Code
def multiply_list elements ):
(
t = 1
r
fo x in :
elements
t *= x ([1,2,9]))
return t
print(multiply_list

Output

3. Code
def add(x,lst=[] ):
if x not in lst:
lst.append(x)
return lst
def main():
list1 = add(2)
print(list1)
list2 = add(3, [11, 12, 13, 14])
print(list2) main()

Output

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 25 | P a g e
Programming Fundamentals (CS-116L) LAB # 09

C. Write Python programs for the following:

1. Write a program that store the names of a few of your friends in a list called ‘names’. Print
each person’s name by accessing each element in the list, one at a time.

2. Write a program that make a list that includes at least four people you’d like to invite to
dinner. Then use your list to print a message to each person, inviting them to dinner.
But one of your guest can’t make the dinner, so you need to send out a new set of invitations. Delete
that person on your list, use del statement and add one more person at the same specified index, use
the insert( ) method. Resend the invitation.

3. Write a program that take list = [30, 1, 2, 1, 0], what is the list after applying each of the
following statements? Assume that each line of code is independent.
• list.append(40)
• list.remove(1)
• list.pop(1)
• list.pop()
• list.sort()
• list.reverse()

4. Write a program to define a function called ‘printsquare’ with no parameter, take first 7 integer
values and compute their square and stored all square values in the list.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 26 | P a g e
Programming Fundamentals (CS-116L) LAB # 09

LAB # 09

SEARCHING & SORTING

OBJECTIVE
Searching and sorting data in the form of list.

THEORY
Searching:
Searching is a very basic necessity when you store data in different data structures/list. The simplest
appraoch is to go across every element in the data structure/list and match it with the value you are
searching for. This is known as Linear search.
In Python, the easiest way to search for an object is to use Membership Operators , to check whether
a value/variable exists in the sequence like string, list, tuples, sets, dictionary or not.
Syntax:
• in - Returns True if the given element is a part of the sequence.
• not in - Returns True if the given element is not a part of the sequence.

Example:
# declare a list and a string
str1 = "Hello world"
list1 = [10, 20, 30, 40, 50]

# Check 'w' (capital exists in the str1 or not


if 'w' in str1:
print ("Yes! w found in ", str1)
else:
print("No! w does not found in " , str1)
# check 30 exists in the list1 or not
if 30 in list1:
print ("Yes! 30 found in ", list1)
else:
print ("No! 30 does not found in ", list1)

Output:
>>> %Run task1.py
Yes! w found in Hello world
Yes! 30 found in [10, 20, 30, 40, 50]

Sorting:
Sorting, like searching, is a common task in computer programming.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 27 | P a g e
Programming Fundamentals (CS-116L) LAB # 09

A Sorting is used to rearrange a given list/array elements according to a comparison operator on the
elements. The comparison operator is used to decide the new order of element in the respective data
structure.
Many different algorithms have been developed for sorting like selection sort, insertion sort , bubble
sort etc.
Bubble sort:
Bubble sort is one of the simplest sorting algorithms. The two adjacent elements of a list are checked
and swapped if they are in wrong order and this process is repeated until we get a sorted list. The
steps of performing a bubble sort are:
• Compare the first and the second element of the list and swap them if they are in wrong order.
• Compare the second and the third element of the list and swap them if they are in wrong order.
• Proceed till the last element of the list in a similar fashion.
• Repeat all of the above steps until the list is sorted.

Example:
a = [16, 19, 11, 15, 10, 12, 14]

#repeating loop len(a)(number of elements) number of times

for j in range(len(a)):
#initially swapped is false
swapped = False
i = 0
while i<len(a)-1:
#comparing the adjacent elements
if a[i]>a[i+1]:
#swapping
a[i],a[i+1] = a[i+1],a[i]
#Changing the value of swapped
swapped = True
i = i+1
#if swapped is false then the list is sorted
#we can stop the loop
if swapped == False:
break
print (a)

Output:
>>> %Run task2.py
[10, 11, 12, 14, 15, 16, 19]
>>>

EXERCISE

F. Point out the errors, if any, and paste the output also in the following Python programs.
3. Code
'apple' is in ['orange', 'apple', 'grape']

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 28 | P a g e
Programming Fundamentals (CS-116L) LAB # 09

Output

2. Code
def countX(lst, x):
return lst.count(x)

Output:

What will be the output of the following programs:


1. Code
strs = ['aa', 'BB', 'zz', 'CC']
print (sorted(strs))
print (sorted(strs, reverse=True))

Output

2. Code
test_list = [1, 4, 5, 8, 10]
print ("Original list : " , test_list)

# check sorted list

if(test_list == sorted(test_list)):
print ("Yes, List is sorted.")

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 29 | P a g e
Programming Fundamentals (CS-116L) LAB # 09

else :
print ("No, List is not sorted.")

Output

C. Write Python programs for the following:

1. Write a program that take function which implements linear search. It should take a list and an
element as a parameter, and return the position of the element in the list. The algorithm consists of
iterating over a list and returning the index of the first occurrence of an item once it is found. If the
element is not in the list, the function should return ‘not found’ message.

2. Write a program that create function that takes two lists and returns True if they have at least one
common member. Call the function with atleast two data set for searching.

3. Write a program that create function that merges two sorted lists and call two list with random
numbers.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 30 | P a g e
Programming Fundamentals (CS-116L) LAB # 10

LAB # 10

TUPLE AND DICTIONARY

OBJECTIVE
Getting familiar with other data storing techniques - Tuple and Dictionary.

THEORY

Tuple:
A tuple is a sequence of immutable Python objects. Tuples are like lists, but their elements are fixed,
that once a tuple is created, you cannot add new elements, delete elements, replace elements, or
reorder the elements in the tuple.
Syntax for creating tuple:
tup1 =() #Empty tuple
tup2 = ('physics', 'chemistry') #Tuple of string)
tup3 = (1, 2, 3, 4, 5 ) #Tuple of integer

#Create a tuple from a list


tup4 = tuple([2 * x for x in range(1, 5)]) # (2, 4, 6, 8)
#Create Single item in tuple
tup1 = (50,)

Example: Accessing Values in Tuples


tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[2])
print ("tup2[1:5]: ", tup2[1:5])

Output:
>>> %Run task1.py
tup1[2]: 1997
tup2[1:5]: (2, 3, 4, 5)

Tuple Functions:
cmp(tuple1, tuple2) Compares elements of both tuples.
len(tuple) Gives the total length of the tuple.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 31 | P a g e
Programming Fundamentals (CS-116L) LAB # 10

max(tuple) Returns item from the tuple with max value.


min(tuple) Returns item from the tuple with min value.
tuple(seq) Converts a list into tuple.

Dictionary:
A dictionary is a container object that stores a collection of key/value pairs. It enables
fast retrieval, deletion, and updating of the value by using the key. A dictionary is also known as a
map, which maps each key to a value.

Syntax for creating dictionary:


dict1={} # Create an empty dictionary
dict2={1: 'apple', 2: 'ball'} # dictionary with integer keys

Example: Accessing Values in Dictionary


my_dict = {'name':'xyz', 'age': 26}
print("value:",my_dict['name'])
print("value:",my_dict.get('age'))

Output:
>>> %Run task2.py
value: xyz
value: 26

Example: Adding, Modifying, Retrieving and Deleting Values


To add,modify and retrieve an item to a dictionary, use the syntax: dictionaryName[key] = value
To delete an item from a dictionary, use the syntax: del dictionaryName[key],
dictionaryName.pop(key)
students = {"111-31":"John", "111-32":"Peter"}
students["111-33"] = "Susan" # Add a new item
print("Add item:",students)
del students["111-31"] # Delete item
print("Delete item:",students)

Output:
>>> %Run task3.py
Add item:{'111-31':'John', '111-32':'Peter', '111-33': 'Susan'}
Delete item: {'111-32': 'Peter', '111-33': 'Susan'}

Dictionary Methods:
keys(): tuple Returns a sequence of keys in form of tuple.
values(): tuple Returns a sequence of values.
items(): tuple Returns a sequence of tuples. Each tuple is (key, value) for an item.
clear(): None Deletes all entries.
get(key): value Returns the value for the key.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 32 | P a g e
Programming Fundamentals (CS-116L) LAB # 10

popitem(): tuple Returns a randomly selected key/value pair as a tuple and removes
the selected item.

EXERCISE

G. Point out the errors, if any, and paste the output also in the following Python programs.
4. Code
t = (1, 2, 3)
t.append(4)
t.remove(0)
del tup[0]

Output

2. Code
1user_0=['username':'efermi','first':'enrico','last':'fermi',]
for key, value in 1user_0.items():
print("\nKey: " ,key)
print("Value: " ,value)

Output:

What will be the output of the following programs:


3. Code
tuple1 = ("green", "red", "blue")
tuple2 = tuple([7, 1, 2, 23, 4, 5])
tuple3 = tuple1 + tuple2
print(tuple3)
tuple3 = 2 * tuple1
print(tuple3)
print(tuple2[2 : 4])
print(tuple1[-1])
Output

4. Code
def main():
Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 33 | P a g e
Programming Fundamentals (CS-116L) LAB # 10

d = {"red":4, "blue":1, "green":14, "yellow":2}


print(d["red"])
print(list(d.keys()))
print(list(d.values()))
print("blue" in d)
print("purple" in d)
d["blue"] += 10
print(d["blue"])
main() # Call the main function

Output

C. Write Python programs for the following:

1. Write a program that create a buffet-style restaurant offers only five basic foods. Think of five
simple foods, and store them in a tuple. (Hint:Use a for loop to print each food the restaurant
offers. Also the restaurant changes its menu, replacing two of the items with different foods and
display the menu again.

2. Write a program for “Guess the capitals” using a dictionary to store the pairs of states and
capitals so that the questions are randomly displayed. The program should keep a count of the
number of correct and incorrect responses.

3. Write a pogram that make a dictionary called favorite_places. Think of three names to use as keys
in the dictionary, and store three favorite places for each person through list. Loop through the
dictionary, and print each person’s name and their favorite places.
Output look alike:
abc likes the following places:
- Bear Mountain
- Death Valley
- Tierra Del Fuego

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 34 | P a g e
Programming Fundamentals (CS-116L) LAB # 11

LAB # 11
MODULES AND PACKAGES

OBJECTIVE
Getting familiar with the envoirnment for using modules and packages.

THEORY
Modules
A module allows you to logically organize your Python code. A file containing a set of functions
you want to include in your application.
Create a Module
To create a module just save the code you want in a file with the file extension .py:

Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " ,name)
Use a Module
Now use different ways to call the module we just created, by using the import statement:
i) import module1[, module2[,... moduleN]
ii) import module as m
iii) from module import functionName

Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("XYZ")

Built-in Modules
There are several built-in modules in Python, which you can import, here is the example of math
and sys module;

Python - math Module


Math module provide the usage of mathematical functions.

Example:
from math import pi
r=int(input("Enter:"))
print("Area:" , pi*(r**2))
Output:
>>> %Run task1.py
enter:3

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 35 | P a g e
Programming Fundamentals (CS-116L) LAB # 11

Area: 28.27

Functions in Python Math Module


Functions Description
ceil(x) Returns the smallest integer greater than or equal to x.
factorial(x) Returns the factorial of x
floor(x) Returns the largest integer less than or equal to x
exp(x) Returns e**x
cosh(x) Returns the hyperbolic cosine of x

sinh(x) Returns the hyperbolic cosine of x

tanh(x) Returns the hyperbolic tangent of x

pow(x, y) Returns x raised to the power y

sqrt(x) Returns the square root of x


Mathematical constant, the ratio of circumference of a circle to it's
pi diameter (3.14159...)
e mathematical constant e (2.71828...)

Python - sys Module


The sys module provides functions and variables used to manipulate different parts of the Python
runtime environment
Example:
import sys
print(sys.version) #version number of the current Python interpreter

Output:
>>> %Run task2.py
3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 14 2019, 23:09:19) [MSC v.1916 32 bit (Intel)]

Packages
A package is a collection of python modules, i.e., a package is a directory of python modules
containing an additional __init__.py file. Each package in Python is a directory which must contain
a special file called __init__.py. This file can be empty, and it indicates that the directory it contains

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 36 | P a g e
Programming Fundamentals (CS-116L) LAB # 11

is a Python package, so it can be imported the same way a module can be imported. There are 130k
+ packages and still growing , numpy is one of the most running and useful python’s package
NumPy
NumPy is a purposely an 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.

Installation:
In Thonny, there is a menu and select Tools option and then select Manage packages,
search numpy and install it.

Example: Create 1D,2D,3D array


import numpy as np
#1D array
print("1D:",np.arange(2,6).reshape(4))
#2D array
print("2D:",np.arange(2,10).reshape(2,4))
#3D array
print("3D:",np.arange(24).reshape(4,3,2))

EXERCISE

H. Point out the errors, if any, and paste the output also in the following Python programs.
1. Code:

import sys as s
print(sys.executable)

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 37 | P a g e
Programming Fundamentals (CS-116L) LAB # 11

print(sys.getwindowsversion())

Output:

2. Code:
import datetime
from datetime import date
import times
# Returns the number of seconds
print(time.time())
# Converts a number of seconds to a date object
print(datetime.datetime.now())

Output:

3. Code:
From math import math
# using square root(sqrt) function contained
print(Math.sqrt(25) )
print(Math.pi)
# 2 radians = 114.59 degreees
print(Math.degrees(2))

Output:

I. What would be the output of the following programs:

4. Code:
import calendar
yy = 2017
mm = 11
# display the calendar
print(calendar.month(yy, mm))

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 38 | P a g e
Programming Fundamentals (CS-116L) LAB # 11

Output:

5. Code:
import sys
print(sys.argv)
for i in range(len(sys.argv)):
if i==0:
print("The function is",sys.argv[0])
else: print("Argument:",sys.argv[i])

Output:

6. Code:
import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3],
[ 4, 2, 5]] )

# Printing array dimensions (axes)


print("No. of dimensions: ", arr.ndim)

# Printing shape of array


print("Shape of array: ", arr.shape)

# Printing size (total number of elements) of array


print("Size of array: ", arr.size)

Output:

J. Write Python programs for the following:


Department of Computer Science & Information Technology
Sir Syed University of Engineering & Technology 39 | P a g e
Programming Fundamentals (CS-116L) LAB # 11

1. Write a NumPy program to create an 1D array of 10 zeros, 10 ones, 10 fives

2. Write a NumPy program to create a 3x3 matrix with values ranging from 2 to 10.

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 40 | P a g e
Programming Fundamentals (CS-116L) LAB # 11

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 1|Page
Programming Fundamentals (CS-116L) LAB # 06

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 1|Page
Programming Fundamentals (CS-116L) LAB # 06

Department of Computer Science & Information Technology


Sir Syed University of Engineering & Technology 1|Page

You might also like