Python Programs //




developers developers developer
Introduction To Python

Python is one of the most popular programming languages today, and for good reason. Not only is it incredibly powerful and versatile, it's also incredibly easy to learn. Python is an interpreted language, which means that it can be written and executed from the command line without the need for a compiler. This makes it perfect for quick scripting tasks, as well as more complex applications. Python is a great choice for many types of software development, from web applications to game development. Its simple syntax and powerful libraries make it a great choice for beginners, while its advanced features make it a powerful tool for more experienced developers. Python also has a large community of developers and users, which makes it easier to find help when you need it. Python is also a great choice for data science. It has a wide range of libraries and tools that make it easy to work with data, including tools for data visualization, machine learning, and natural language processing. With Python, you can quickly develop sophisticated models and algorithms for data analysis, and use these models to make predictions and insights. Python also has a wide range of applications in the world of artificial intelligence. Its libraries and tools make it easy to build AI applications, from simple chatbots to more complex machine learning systems. Python is also popular in the world of robotics, where it can be used to control robotic arms and other hardware. In short, Python is an incredibly powerful and versatile programming language, with a wide range of applications across many different fields like web design. Whether you're a beginner python class savailable or an experienced developer, Python is an excellent choice for your next project.

Thanks for reading.


1: How to write Python First Program in IDLE Shell 3.11.1

First Python Program to print Hello world: 

   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 on Python programming language. 

Prerequisites 

You should have a basic understanding of Computer Programming terminologies. A basicunderstanding 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. 

     History of Python 

Python was developed by Guido van Rossum in the late eighties and early nineties at the NationalResearch 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 GeneralPublic License (GPL). 

Python is now maintained by a core development team at the 

institute, although Guido vanRossum still holds a vital role in directing  its progress. 

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-platformcompatible 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, andthe 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 listedbelow − 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. 

PROGRAM:-

Print (“Hello World”) 



OUTPUT :-


What is a Variable in Python? 

A Python variable is a reserved memory location to store values. In other words, a variable in apython program gives data to the computer for processing. 

Every value in Python has a datatype. Different data types in Python are  Numbers, List, Tuple, Strings, Dictionary, etc. Variables can be declared by any name or even alphabets like a, aa, abc, etc. 

How to Declare and use a Variable 

Let see an example. We will declare variable "a" and print it. 

a=100 

print a 

100 

Constants 

A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as containers that hold information which cannot be changed later. 

Non technically, you can think of constant as a bag to store some books and those books cannot be replaced once place inside the bag. 

List of some different variable types 

x = 123 # integer 

x = 123L # long integer 

x = 3.14 # double float 

x = "hello" # string 

x = [0,1,2] # list 

x = (0,1,2) # tuple 

x = open(‘hello.py’, ‘r’) # file

Assigning value to a constant in Python 

In Python, constants are usually declared and assigned on a module. Here, the module means a new file containing variables, functions etc which is imported to main file. Inside the module, constants are written in all capital letters and underscores separating the words. 

Example 3: Declaring and assigning value to a constant 

Create a constant.py 

PI = 3.14 

GRAVITY = 

9.8 

Create a main.py 

import constant 

print(constant.PI) 

print(constant.GRAVIT Y) 

When you run the program, the output will be: 

3.14 

9.8 

Types of Operator 

Python language supports the following types of operators. 

• Arithmetic Operators 

• Comparison (Relational) Operators 

• Assignment Operators 

• Logical Operators 

• Bitwise Operators 

• Membership Operators 

• Identity Operators 

Let us have a look on all operators one by one. 

Python Arithmetic Operators 

Assume variable a holds 10 and variable b holds 20, then –


Operator 

Description 

Example

+ Addition 

Adds values on either side of the operator. 

a + b =30

- Subtraction 

Subtracts right hand operand from left hand operand. 

a – b =10

Multiplicatio n

Multiplies values on either side of the operator 

a * b =200

/ Division 

Divides left hand operand by right hand operand 

b / a = 2

% Modulus 

Divides left hand operand by right hand operand and returns remainder

b % a = 0

** Exponent 

Performs exponential (power) calculation on operators 

a**b =10to the power 20

// 

Floor Division - The division of operands where the result isthe quotient in which the digits after the decimal point are

9//2 = 4and


removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity) −

9.0//2.0 

= 4.0, 

11//3 = 

-4, - 11.0//3 

= -4.0



Python Comparison Operators


These operators compare the values on eithersides of them and decide the 
relation among them.They are also called Relational operators. 
Assume variable a holds 10 and variable b holds 20, then −[ Show 


Operator

Example ] Description 

Example

== 

If the values of two operands are equal, then the condition becomes true.

(a == b) is 

not true.

!= 

If values of two operands are not equal, then condition becomes true.

(a != b) is 

true.

<> 

If values of two operands are not equal, then condition becomes true.

(a <> b) is 

true. Thisis  similar to 

!= 

operator.

If the value of left operand is greater than the value of right operand, then condition becomes true.

(a > b) isnot true.



If the value of left operand is less than the value of right operand, then condition becomes true.

(a < b) 

istrue.

>= 

If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.

(a >= b) 

isnot 

true.

<= 

If the value of left operand is less than or equal to the value ofright operand, then condition becomes true.

(a <= b) 

istrue.



Python Assignment Operators 


Assume variable a holds 10 and variable b holds 20, then −[ Show 


Operator Example 

] Description 

Example

Assigns values from rightside operands to left side operand 

c = a + b 

assigns 

value of a 

+ b into c

+= Add AND 

It adds right operand to the left operand and assign the result to left operand

c += a is 

equivalent to c = c + 

a

-= Subtract 

AND

It subtracts right operand from the left operand and assign the result to left operand

c -= a is 

equivalent to c = c - a


*=  

Multiply 

AND

It multiplies right operand with the left operand and assignthe result to left operand 

c *= a is 

equivalent



to c = c * a

/= Divide AND 

It divides left operand with the right operand and assign the result to left operand

c /= a is 

equivalent to c = c / 

ac /= a is 

equivalent to c = c / a

%=  

Modulus 

AND

It takes modulus using two operands and assign the result to left operand

c %= a is 

equivalent to c = c % 

a

**= Exponent AND

Performs exponential (power) calculation on operators and assign value to the left operand

c **= a is 

equivalent to c = c ** a

//= Floor 

Division

It performs floor division on operators and assign value tothe left operand

c //= a is 

equivalent to c = c // 

a



Python Bitwise Operators


Bitwise operator works on bits and performs bit by bit operation.  

Assume if a = 60; and b = 13;Now in binary format they will be as 

follows –


a = 0011 1100 

b = 0000 1101 

a&b = 0000 1100 

a|b = 0011 1101 

a^b = 0011 0001 

~a = 1100 0011


Operator 

Description 

Example

& Binary AND 

Operator copies a bit to the result if it exists in both operands

(a & b) (means 0000 1100)

| Binary OR 

It copies a bit if it exists in either operand. 

(a | b) = 61(means 

0011 1101)

^ Binary XOR 

It copies the bit if it is set in one operand but notboth. 

(a ^ b) = 49(means 

0011 0001)



~ Binary 

Ones 

Comple 

ment

It is unary and has the effect of 'flipping' bits. 

(~a ) = -61 

(means 1100 

0011 

in 2's complement 

form due to a signed binary number.


There are following Bitwise operators supported by Python language


<< Binary Left Shift 

The left operands value is moved left by the numberof bits specified by the right operand.

a << 2 = 240 (means 

1111 0000)

>> Binary Right 

Shift

The left operands value is moved right by the number of bits specified by the right operand.

a >> 2 = 15 

(means 

0000 1111)



Python Logical Operators 

There are following logical operators supported by Python language. 

Assume variable a holds10 and variable b holds 20 then 


Operator 

Descriptio 

n

Example

and  

Logical 

AND

If both the operands are true then condition becomes true. 

(a and 

b) is 

true.

or Logical OR 

If any of the two operands are non-zero then condition becomes true.

(a or b) 

is true.

not  

Logical 

NOT

Used to reverse the logical state of its operand. 

Not(a 

and b) is 

false.

Used to reverse the logical state of its operand


Python Membership Operators 

Python’s membership operators test for membership in a sequence, such as 

strings, lists, ortuples. There are two membership operators as explained below −


 

Operator 

Descriptio 

n

Example

In 

Evaluates to true if it finds a variable in the specified sequenceand false otherwise.

x in y, 

here in results in 

a 1 if x is a member of sequence y.

not in 

Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.

x not in y,here not in  results in 

a 1 if x is not a 

member of sequencey.



Result: Thus we have studied about basics of python.




2: Write a program to demonstrate the use of Python to add two numbers together and calculate the sum.



Theory: This program demonstrates the use of variables and arithmetic operations in Python.


Procedure:


Declare two variables, a and b, and assign values to them.

Add the values of a and b and assign the result to a new variable, c.

Print the value of c.


Program :-


a = 5

b = 3

c = a + b

print(c)


Output:




3: Write python program to store data in list and then try to print them.

Theory: 

List

A list is a collection which is ordered and changeable. In Python lists are written with square  brackets. 

Example 

Create a List: 

a = ["apple", "banana", "cherry"

print(a) 

Access Items 

You access the list items by referring to the index number: 

Example 

Print the second item of the list: 

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

print(a[1]) 

Negative Indexing 

Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second  last item etc. 

Example 

Print the last item of the list: 

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

print(a[-1]) 

Range of Indexes 

You can specify a range of indexes by specifying where to start and where to end the range. When  specifying a range, the return value will be a new list with the specified items. Example 

Return the third, fourth, and fifth item: 

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

print(a[2:5])

Example 

This example returns the items from the beginning to "orange": 

a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(a[:4]) 

By leaving out the end value, the range will go on to the end of the list: Example 

This example returns the items from "cherry" and to the end: a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(a[2:]) 

Range of Negative Indexes 

Specify negative indexes if you want to start the search from the end of the list: Example 

This example returns the items from index -4 (included) to index -1 (excluded) a = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"] print(a[-4:-1]) 

Change Item Value 

To change the value of a specific item, refer to the index number: 

Example 

Change the second item: 

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

a[1] = "blackcurrant" 

print(a) 

Loop Through a List 

You can loop through the list items by using a for loop: 

Example 

Print all items in the list, one by one: 

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

for x in a: 

 print(x) 

List Length 

 

To determine how many items a list has, use the len() function: Example 

Print the number of items in the list: 

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

print(len(a))

 

Add Items 

To add an item to the end of the list, use the append() method: 

Example 

Using the append() method to append an item: 

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

a.append("orange") 

print(a) 

To add an item at the specified index, use the insert() method: 

Example 

Insert an item as the second position: 

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

a.insert(1, "orange") 

print(a) 

Remove Item 

There are several methods to remove items from a list: 

Example 

The remove() method removes the specified item: 

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

a.remove("banana") 

print(a) 

Example 

The pop() method removes the specified index, (or the last item if index is not specified): a = ["apple", "banana", "cherry"] 

a.pop() 

print(a) 

Example 

The del keyword removes the specified index: 

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

del a[0] 

print(a)

Example 

The del keyword can also delete the list completely: 

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

del

Example 

The clear() method empties the list: 

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

a.clear() 

print(a) 

Copy a List 

You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1,  and changes made in list1 will automatically also be made in list2

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

Make a copy of a list with the copy() method: 

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

mylist = a.copy() 

print(mylist) 

Join Two Lists 

There are several ways to join, or concatenate, two or more lists in Python. 

One of the easiest ways are by using the + operator. 

Example 

Join two list: 

list1 = ["a", "b" , "c"] 

list2 = [1, 2, 3] 

list3 = list1 + list2 

print(list3)

 

List Methods 

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

Method Description 

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

clear() Removes all the elements from the list 

copy() Returns a copy of the list 

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

index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the item with the specified value reverse() Reverses the order of the list 

sort() Sorts the list


1. 2. 


PROGRAM :-


characters = ["thomas shelby", "Jack reacher", "john wick","Walter White"]
print(characters) 
Actors = ["Cillian Murphy", "Alan Ritchson", "keanu Reeves"]
print (Actors)
characters.append("Bryan Cranston")
print(characters)
print(Actors[-1])
characters.remove("Bryan Cranston")
print(characters)
print(len(Actors))


OUTPUT :-





Result: - Thus we have studied the use of lists in py.




4 : Write python program to print list of numbers using range and for loop.

PROGRAM :-


list=[" KL Rahul","Shubman Gill","Cheteshwar Pujara","Virat Kohli","Rishabh Pant","Shreyas Iyer","Axar Patel","Ravichandran Ashwin","Jaydev Unadkat","Umesh Yadav","Mohammed Siraj"]

for i in range(0,11):

 print(list[i])

 print(i)



OUTPUT :-






Result: - Thus we have studied the use of for loop using range function.





5 : Write a program in python in which a function is defined and calling that function prints .


Theory

Function: A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

 

Creating a Function:


In Python a function is defined using the def keyword:

 

def function_name():

            function_body

 

Calling a Function:


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

 

function_name()

 

Arguments:

Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. 

 

def function_name(arg1,arg2,arg3):

          function_body


PROGRAM:-



Program1 (Function without parameters):

def my_function():

          print(“HEY THERE”)

my_function()

 

Program2 (Function with parameters):

def my_new_function(msg):

          print(msg)

my_new_function(“HELLO EVERYONE”)


 

OUTPUT :-







Result: Thus we have studied the concept of defining and calling the functions in python.





6 :  Write a python script to print the current date in the following format.

“Sun May 29 02:26:23 IST 2022”


PROGRAM :-


import time;
ltime=time.localtime();
print(time.strftime(&quot;%a %b %d %H:%M:%S %Z %Y&quot;,ltime)); #returns the formatted time




OUTPUT :- 






Result:-  Thus we have studied to print current date in standard time format.




7 :  Write a python program to find largest of three numbers.

 

PROGRAM:-


a = int(input('Enter first number  : '))

b = int(input('Enter second number : '))

c = int(input('Enter third number  : '))

 

largest = 0

 

if a > b and a > c :

    largest = a

elif b > c :

    largest = b

else :

    largest = c

 

print(largest, "is the largest of three numbers.")


OUTPUT :-






Result:  - Thus we have studied to find largest of three numbers.

 



8 : Write a program to create, concatenate and print a string and accessing sub-string from a given string.


PROGRAM:-


a = "mostha"

b = "thomas"

c = a+b

print(c)

print(a[3:6])

print(b[:4])

 

OUTPUT:-








Result: Thus we have studied concatenation of strings and accessing sub-string from it.

 


9 : Write a Python script that prints prime numbers less

 than 20.


PROGRAM:-

 

print("Prime numbers between 1 and 75 are:")

ulmt=75;

for num in range(ulmt):

   # prime numbers are greater than 1

   if num > 1:

       for i in range(2,num):

           if (num % i) == 0:

               break

       else:

           print(num)

 

OUTPUT :- 






10 : Write a python class to reverse string word by word .

 

PROGRAM:-   

 

 class py_reverse:

   def revr(self, strs):

       sp=strs.split()

       sp.reverse()

       res=" ".join(sp)

       return res

str1=input("Enter a string with 2 or more words : ")

print("Reverse of string word by word: \n",py_reverse().revr(str1));

 

OUTPUT:- 








11 : Write a Python scrip t to visualize data by plotting

 various graphs using matplotlib.


 THEORY :- 


Data Visualization is the process of presenting data in the form of graphs or charts.

 It helps to understand large and complex amounts of data very easily. It allows the decision-makers to make

decisions very efficiently and also allows them in identifying new trends and patterns very easily.

It is also used in high-level data analysis for Machine Learning and Exploratory Data Analysis (EDA).

 Data visualization can be done with various tools like Tableau, Power BI, Python.

 

In this article, we will discuss how to visualize data with the help of the Matplotlib library of Python.

 

Matplotlib

Matplotlib is a low-level library of Python which is used for data visualization.

It is easy to use and emulates MATLAB like graphs and visualization.

This library is built on the top of NumPy arrays and consist of several plots like line chart,

 bar chart, histogram, etc. It provides a lot of flexibility but at the cost of writing more code.


Pyplot

Pyplot is a Matplotlib module that provides a MATLAB-like interface.

Matplotlib is designed to be as usable as MATLAB, with the ability to use Python

and the advantage of being free and open-source. Each pyplot function makes some change to a

 figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area,

 decorates the plot with labels, etc. The various plots we can utilize using Pyplot are Line Plot, Histogram,

 Scatter, 3D Plot, Image, Contour, and Polar.

 

After knowing a brief about Matplotlib and pyplot let’s see how to create a simple plot.


PROGRAM:-

# Online Python-3 Compiler (Interpreter)

import matplotlib.pyplot as plt

# initializing the data

x = [10, 20, 30, 80]

y = [20, 25, 35, 45]

# plotting the data

plt.plot(x, y)

plt.show()



OUTPUT : -








12 : Write python program in which an class is define,

 then create object of that class and call simple print

 function define in class.

 

PROGRAM:-

 

# define a class

class bike:

    name = ""

    gear = 0

    topspeed = 0

# create object of class

bike1 = bike()

bike2 = bike()

# access attributes and assign new values

bike1.gear = 6

bike1.name = "Ducati panigale v4"

bike1.topspeed = 321

bike2.gear = 6

bike2.name = "kawasaki ninja h2"

bike2.topspeed = 400

 

print(f"Name: {bike1.name}, Gears: {bike1.gear} , topspeed: {bike1.topspeed}")

print(f"Name: {bike2.name} , Gears: {bike2.gear} , top peed: {bike2.topspeed}")

 

OUTPUT:-








13 : Write a program to demonstrate working with tuple

 in python.


THEORY:-

What is tuple in Python with example?

Tuple is a sequence of python objects like list with immutable feature. We cannot add or remove an item in tuple. Tuples are created by ( ). It contains heterogeneous data-types. 

eg: t=(1,2,'hello',20.5)


PROGRAM:-


my_tuple = ()

print(my_tuple)

my_tuple = (1, 2, 3)

print(my_tuple)

my_tuple = (24,"Hello",23)

print(my_tuple)

my_tuple = ("mouse", [8, 4, 8], (3, 2, 3))

print(my_tuple)

 

OUTPUT :-











14 : Write a program to demonstrate working of numpy library in python.


THEORY :-

This article will help you get acquainted with the widely used array-processing library in Python, NumPy. What is NumPy? NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object, and tools for working with these arrays. It is the fundamental package for scientific computing with Python. It is open-source software. It contains various features including these important ones:

•           A powerful N-dimensional array object

•           Sophisticated (broadcasting) functions

•           Tools for integrating C/C++ and Fortran code

•           Useful linear algebra, Fourier transform, and random number capabilities

Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined using Numpy which allows NumPy to seamlessly and speedily integrate with a wide variety of databases. Installation:

•           Mac and Linux users can install NumPy via pip command:

Windows does not have any package manager analogous to that in linux or mac. Please download the pre-built windows installer for NumPy from here (according to your system configuration and Python version). And then install the packages manually.

Note: All the examples discussed below will not run on an online IDE. 1. Arrays in NumPy: NumPy’s main object is the homogeneous multidimensional array.

 

It is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers.

In NumPy dimensions are called axes. The number of axes is rank.

NumPy’s array class is called ndarray. It is also known by the alias array.

 

Example : 
[[ 1, 2, 3],
 [ 4, 2, 5]]
Here,
rank = 2 (as it is 2-dimensional or it has 2 axes)

first dimension(axis) length = 2, second dimension has length = 3
overall shape can be expressed as: (2, 3)

PROGRAM :-

import numpy as np
# Creating array object
arr = np.array( [[ 1, 2, 3],[ 5, 2, 5]] )
# Printing type of arr object
print("Array is of type: ", type(arr))
# 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)
# Printing type of elements in array
print("Array stores elements of type: ", arr.dtype)
 

OUTPUT :







Post a Comment

Previous Post Next Post