0% found this document useful (0 votes)
25 views23 pages

Lab Programs 1 To 3

from my teacher

Uploaded by

ankithakarmanchi
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)
25 views23 pages

Lab Programs 1 To 3

from my teacher

Uploaded by

ankithakarmanchi
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/ 23

INTRODUCTION TO PYTHON PROGRAMMING

Theory:- Python is a general-purpose interpreted, interactive, object-oriented, and high-level


programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python
source code is also available under the GNU General Public License (GPL). This tutorial gives
enough understanding of Python programming language.

Prerequisites

We should have a basic understanding of Computer Programming terminologies. A basic


understanding of any of the programming languages is a plus.

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is


designed to be highly readable. It uses English keywords frequently where as other languages use
punctuation, and it has fewer syntactical constructions than other languages.

• Python is Interpreted − Python is processed at runtime by the interpreter. You do not need
to compile your program before executing it. This is similar to PERL and PHP.
• Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
• Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
• Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.

Why the name python?

Guido van Rossum was interested on watching a comedy show, which


is telecasting on the BBC channel from 1969 to 1974. The complete
Monty Python's Flying Circus.

Guido Van Rossum thought he needed a name that was short, unique,
and slightly mysterious for his programming language, so he decided to
call the language Python.
History of Python

Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).

Python is now maintained by a core development team at the institute, although Guido van Rossum
still holds a vital role in directing its progress.

Why Python?
• Easy to learn.
• Currently it has become the trend.
• More usage in Web or computer-oriented applications.
• High demand for the python expert in IT industry.

Job Nature and Work?


• Python Developer: Writing code, Application Design, Server side logic.
• Web Developer: Writing and testing code, Code Debug, Third party web services using
Application Integration.
• Software Developer: Writing code, Designing Software, Installation of software & testing
the software.
• Data Scientist: Analysis of Raw Data, Data Analysis techniques and tools usage.
• Business Analyst: Segregation of large amount of data, Recognition of usage of big data.

What are the skills required for Python Developer?


• Python Language: know about Data Structures, Semantics.
• Python Framework: should have knowledge about Django, Web2Py, CherryPy, Flask,
Bottle frameworks.
• Python Libraries: should have knowledge about different libraries like Numpy, PyTorch,
Pandas etc.
• ORM Libraries: should have knowledge about SQL or Django application linking.
Tips for Python Developer?
• Become expert in Python.
• Learn Fundamentals of Python.
• Learn advanced subjects like Byte Code Semantics, Data Models, Run Time Stackin
Sections, Metaclasses, Multithreading etc.
• Choose anyone specialization and become expert in that like Business Analytics, Data
Analytics, Machine Learning or Web Development.
• Do Certification courses.
• Follow Blog and Tutorials of Python for updates.

Python Features
Python's features include −

• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• Easy-to-maintain − Python's source code is fairly easy-to-maintain.
• A broad standard library − Python's bulk of the library is very portable and cross-platform
compatible on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
• Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
• Databases − Python provides interfaces to all major commercial databases.
• GUI Programming − Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.
• Scalable − Python provides a better structure and support for large programs than shell
scripting.

Apart from the above-mentioned features, Python has a big list of good features, few are listed
below −
• It supports functional and structured programming methods as well as OOP.
• It can be used as a scripting language or can be compiled to byte-code for building large
applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Applications of Python Programming

• Web Development
• Game Development
• Scientific and Numeric applications
• Artificial Intelligence and Machine Learning based applications
• Data Science related applications
• Desktop GUI applications
• Software Development
• Enterprise-level/Business Applications
• Education programs and training courses
• Web Scraping Applications
• Image Processing and Graphic Design Applications
• Data Analysis
• Simple and Easy to Learn
• Freeware and Open Source
• Dynamically typed
• Object Oriented Programming and Procedure Oriented Programming
• Extensive Library
• Embedded
• Extensible
• Interpreted
• Portability
• Platform Independent

**********
How to Install Python on Windows Platform
Introduction
The Python programming language is an increasingly popular choice for both beginners and
experienced developers. Flexible and versatile, Python has strengths in scripting, automation, data
analysis, machine learning, and back-end development.

In this tutorial you’ll install Python on Windows 10 using the Python installer for Windows.

Prerequisites
You’ll need a computer running Windows 10 with administrative privileges and an internet
connection.

Step 1 — Downloading the Python Installer

1. Go to the official Python download page for Windows.


2. Find a stable Python 3 release. This tutorial was tested with Python version 3.10.10.
3. Click the appropriate link for your system to download the executable file: Windows
installer (64-bit) or Windows installer (32-bit).
Step 2 — Running the Executable Installer

1. After the installer is downloaded, double-click the .exe file, for example python-3.10.10-
amd64.exe, to run the Python installer.
2. Select the Install launcher for all users checkbox, which enables all users of the computer
to access the Python launcher application.
3. Select the Add python.exe to PATH checkbox, which enables users to launch Python
from the command line.

4. If you’re just getting started with Python and you want to install it with default features as
described in the dialog, then click Install Now and go to Step 4 - Verify the Python
Installation. To install other optional and advanced features, click Customize Installation
and continue.
5. The Optional Features include common tools and resources for Python and you can install
all of them, even if you don’t plan to use them.
Select some or all of the following options:
Documentation: recommended
pip: recommended if you want to install other Python packages, such as NumPy or pandas
tcl/tk and IDLE: recommended if you plan to use IDLE or follow tutorials that use it
Python test suite: recommended for testing and learning
py launcher and for all users: recommended to enable users to launch Python from the
command line

6. Click Next.
7. The Advanced Options dialog displays.
Select the options that suit your requirements:
• Install for all users: recommended if you’re not the only user on this computer
• Associate files with Python: recommended, because this option associates all the
Python file types with the launcher or editor
• Create shortcuts for installed applications: recommended to enable shortcuts for
Python applications
• Add Python to environment variables: recommended to enable launching Python
• Precompile standard library: not required, it might down the installation
• Download debugging symbols and Download debug binaries: recommended
only if you plan to create C or C++ extensions
Make note of the Python installation directory in case you need to reference it later.
8. Click Install to start the installation.
9. After the installation is complete, a Setup was successful message displays.

Step 3 — Adding Python to the Environment Variables (optional)

Skip this step if you selected Add Python to environment variables during installation.
If you want to access Python through the command line but you didn’t add Python to your
environment variables during installation, then you can still do it manually.

Before you start, locate the Python installation directory on your system. The following directories
are examples of the default directory paths:

▪ C:\Program Files\Python310: if you selected Install for all users during installation, then
the directory will be system-wide.
▪ C:\Users\Sammy\AppData\Local\Programs\Python\Python310: if you didn’t select
Install for all users during installation, then the directory will be in the Windows user
path.

Note that the folder name will be different if you installed a different version, but will still start
with Python.

1. Go to Start and enter advanced system settings in the search bar.


2. Click View advanced system settings.
3. In the System Properties dialog, click the Advanced tab and then click Environment
Variables.
4. Depending on your installation:
▪ If you selected Install for all users during installation, select Path from the list of
System Variables and click Edit.
▪ If you didn’t select Install for all users during installation, select Path from the
list of User Variables and click Edit.
5. Click New and enter the Python directory path, then click OK until all the dialogs are
closed.

Step 4 — Verify the Python Installation

You can verify whether the Python installation is successful either through the command line or
through the Integrated Development Environment (IDLE) application, if you chose to install it.

Go to Start and enter cmd in the search bar. Click Command Prompt.

Enter the following command in the command prompt:


An example of the output is:

You can also check the version of Python by opening the IDLE application. Go to Start and enter
Python in the search bar and then click the IDLE app, for example IDLE (Python 3.10 64-bit).

We can start coding in Python using IDLE or your preferred code editor.

Conclusion

We’ve installed Python on your Windows 10 computer and are ready to start learning and
programming in Python. Next, you can write your first program in Python 3 and continue your
learning with more Python tutorials.

Python Installation Reference Video Link

Python Installation: https://www.youtube.com/watch?v=Kn1HF3oD19c

**********
How to Install PyCharm on Windows Platform
PyCharm is a featured IDE for application development in Python. It provides us with various
tools that help in developing efficient applications in less time. It also supports web application
development using AngularJS, NodeJS, and Django. Consequently, PyCharm is available for
different operating systems such as Windows, Linux, Ubuntu, and MacOS. In this blog, you will
first learn how to install Python on your computer system. After that, you will see PyCharm
installation in different operating systems.

Installing PyCharm

For developing applications in Python using PyCharm, you need to install it in your system.

PyCharm is available in two versions:

• Professional version: It is a full-featured IDE used by professional developers.


• Community version: It is an open-source and free software that is not full-featured. You
can use it for learning Python application development.

The Professional version is a paid tool and comes with a free trial. You have to buy a license key
for it after your free trial period is over.

The Community version, on the other hand, is open-source without any subscription charge.

In this, we will see the installation of the Community version that includes enough features to help
us write efficient programs.

Steps to Install PyCharm

Step 1: To download PyCharm, visit the official website of JetBrains: Download PyCharm

Step 2: Click on the ‘Download’’ button

Step 3: After that, you will see the below window with two options, Professional and Community.

Step 4: Download the Community version

Note: If you are interested to work with the Professional version, then you can download the
Professional version and avail a free trial.
Step 5: After downloading the file, click on it.

Step 6: When the following window appears, click on Next and the installation process will start.
Step 7: After clicking on Next, first, a window for setting up the installation location will appear.

Note: You can either select a folder for the installation location or retain the default path.
Step 8: In the next step, you can set the Installation Options as per requirements, and then, click
on the Next button to proceed.

Step 9: Now, you have to select the Start Menu folder, or you can leave it as default
Step 10: After these steps, click on the Install button as above to start the installation process

Step 11: When you click on the Finish button, your PyCharm installation completes

Now, you have successfully installed PyCharm and Python both in your system.

PyCharm Installation Reference Video Link


PyCharm Installation: https://www.youtube.com/watch?v=SZUNUB6nz3g
**********
LAB PROGRAM 01 (a)
1 a) Write a python program to find the best of two test average marks out of three test’s
marks accepted from the user.

PROGRAM
print("Enter the three internals marks (> zero:")
m1 = int(input("Enter marks1:"))
m2 = int(input("Enter marks2:"))
m3 = int(input("Enter marks3:"))
print("Marks1:", m1)
print("Marks2:", m2)
print("Marks3:", m3)
small=m1
if small > m2:
small = m2
if small > m3:
small = m3
avg=(m1+m2+m3-small)/2;
print("Average of best two test out of three test is",avg)

OUTPUT
//Output 01
Enter the three internals marks:
Enter marks1:22
Enter marks2:24
Enter marks3:23
Marks1: 22
Marks2: 24
Marks3: 23
Average of best two test out of three test is 23.5

//Output 02
Enter the three internals marks:
Enter marks1:23
Enter marks2:19
Enter marks3:21
Marks1: 23
Marks2: 19
Marks3: 21
Average of best two test out of three test is 22.0

**********
LAB PROGRAM 01 (b)
1 b) Develop a Python program to check whether a given number is palindrome or not and
also count the number of occurrences of each digit in the input number.

PROGRAM
rev = 0
num = int(input("Enter the number:"))

temp = num

n=str(temp)

while num > 0:


digit = num%10
rev = rev*10+digit
num //= 10

print("Given Number is", temp)


print("Reversed Number is", rev)

if temp == rev:
print(temp, "is a Palindrome")
else:
print(temp, "is not a Palindrome")

# Finding Number of Digits using built-in function


print("Number of Digits using Built-in Function: ", len(str(n)))

#Finding the occurrences of each digit


s={}
for i in n:
if i in s:
s[i]+=1
else:
s[i]=1
print("Number of occurrences of each digit in the input number are:")
print(s)

OUTPUT
//Output 01
Enter the number:1441
Given Number is 1441
Reversed Number is 1441
1441 is a Palindrome
Number of Digits using Built-in Function: 4
Number of occurrences of each digit in the input number are:
{'1': 2, '4': 2}

//Output 02
Enter the number:1234
Given Number is 1234
Reversed Number is 4321
1234 is not a Palindrome
Number of Digits using Built-in Function: 4
Number of occurrences of each digit in the input number are:
{'1': 1, '2': 1, '3': 1, '4': 1}
LAB PROGRAM 02 (a)
2 a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a
value for N (where N >0) as input and pass this value to the function. Display suitable error
message if the condition for input value is not followed.

PROGRAM
def fibonacci(n):
if n <= 0:
print("Error: N must be greater than 0.")
return None
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)

n = int(input("Enter a value for N: "))


result = fibonacci(n)
if result is not None:
print("The", n, "th term of the Fibonacci sequence is", result)

OUTPUT
//Output 01
Enter a value for N: 10
The 10 th term of the Fibonacci sequence is 34

//Output 02
Enter a value for N: 20
The 20 th term of the Fibonacci sequence is 4181

**********
LAB PROGRAM 02 (b)
2 b) Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.

PROGRAM
def binary_to_decimal(binary):
decimal = 0
power = 0

while binary > 0:


decimal += (binary % 10) * (2 ** power)
binary //= 10
power += 1

return decimal

def octal_to_hexadecimal(octal):
decimal = 0
power = 0

while octal > 0:


decimal += (octal % 10) * (8 ** power)
octal //= 10
power += 1

hexadecimal = ""
hex_digits = "0123456789ABCDEF"

while decimal > 0:


remainder = decimal % 16
hexadecimal = hex_digits[remainder] + hexadecimal
decimal //= 16

return hexadecimal

binary_number = int(input("Enter a binary number: "))


decimal_number = binary_to_decimal(binary_number)
print("Decimal:", decimal_number)

octal_number = int(input("Enter an octal number: "))


hexadecimal_number = octal_to_hexadecimal(octal_number)
print("Hexadecimal:", hexadecimal_number)

OUTPUT
//Output 01
Enter a binary number: 1111
Decimal: 15
Enter an octal number: 45
Hexadecimal: 25

//Output 02
Enter a binary number: 1001
Decimal: 9
Enter an octal number: 20
Hexadecimal: 10

**********
LAB PROGRAM 03 (a)
3 a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters and lowercase letters.

PROGRAM
sentence = input("Enter a sentence: ")

word_count = len(sentence.split())

digit_count = 0
upper_count = 0
lower_count = 0

for char in sentence:


if char.isdigit():
digit_count += 1
elif char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1

print("Number of words:", word_count)


print("Number of digits:", digit_count)
print("Number of uppercase letters:", upper_count)
print("Number of lowercase letters:", lower_count)

OUTPUT
//Output 01
Enter a sentence: Python Programming 21CSL46
Number of words: 3
Number of digits: 4
Number of uppercase letters: 5
Number of lowercase letters: 15

//Output 02
Enter a sentence: Python Programming Laboratory
Number of words: 3
Number of digits: 0
Number of uppercase letters: 3
Number of lowercase letters: 24

**********
LAB PROGRAM 03 (b)
3 b) Write a Python program to find the string similarity between two given strings

Sample Output: Sample Output:


Original string: Original string:
Python Exercises Python Exercises
Python Exercises Python Exercise
Similarity between two said strings: Similarity between two said
1.0 0.967741935483871

PROGRAM
import difflib
def string_similarity(str1, str2):
result = difflib.SequenceMatcher(a=str1.lower(), b=str2.lower())
return result.ratio()

str1 = 'Python Exercises' or str1 = input("Enter a sentence: ")


str2 = 'Python Exercises' or str2 = input("Enter a sentence: ")
print("Original string:")
print(str1)
print(str2)
print("Similarity between two said strings:")
print(string_similarity(str1,str2))

str1 = 'Python Exercises' or str1 = input("Enter a sentence: ")


str2 = 'Python Exercise' or str2 = input("Enter a sentence: ")
print("\nOriginal string:")
print(str1)
print(str2)
print("Similarity between two said strings:")
print(string_similarity(str1,str2))

OUTPUT
Original string:
Python Exercises
Python Exercises
Similarity between two said strings:
1.0

Original string:
Python Exercises
Python Exercise
Similarity between two said strings:
0.967741935483871

You might also like