Python Note

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

PROGRAMS:

Computer Programs are set of instructions written in any particular computer programming language that tells
the computer what to do and how to do it.
It is a series of instructions written in the language of the computer which specifies processing operations that
the computer is to carry out on data. It is a coded list of instructions that tell" a computer how to perform a set of
calculations or operations.

Characteristics of a Good Program


Every good program must have the following characteristics:

❖ Accuracy: Every good program must be error free.

❖ Readability: The program should be easy for any programmer to read and understand.

❖ Maintainability: A carefully written program should be very easy to amend and maintain if need be.

❖ Efficiency: One of the characteristics of a good program is it ability to solve a particular problem
skillfully.

❖ Generality: A good program should be able to solve all similar problems.

❖ Clarity: Every good and tested program must be clear, straightforward and easy to understand.

❖ Reliability: The program should be depended upon at all times.

Precautions to be taken when writing a Program


1. Do not rush. Be careful, stable and patient.
2. Follow/observe all the steps involved in program development. No step should be skipped.
3. The order of execution must be followed sequentially.

PROGRAMMING LANGUAGES:
A programming language is a set of grammatical rules for instructing a computer to perform a particular task.
Programmers write instructions in various programming languages, some directly understandable by computers
and others requiring intermediate translation steps. We have hundreds of computer programming languages in
use today.

Attributes of a Good Programing Language


Despite the importance of external influence, the programmer ultimately determines which language stand the
test of time or which language is in high demand. Many reasons explain why programmer prefers one language
to another some of the reasons are:

1. Clarity, simplicity and unity.


A good programming language should be an aid to the programmer by providing a clear, simple and unified
set of concepts that can be used as primitives in developing algorithms. As for simplicity, a good
programming language should have property in which constructs that mean different things look different,
that is semantic difference should be clear in the language syntax

2. Orthogonality
This refers to the attribute of being able to combine various features of a language in all possible
combinations, with every combination being meaningful. Orthogonality feature makes it easier to learn a
programming language it also makes it easier to write program because there are fewer exceptions.

3. Naturalness for the application.


A good programming language should provide appropriate data structures, operations, control structures, and
a natural syntax for the problem to be solved.

4. Support for abstraction


An ideal programming language should allow data structures, data types and operations to be defined and
maintained as self-contained abstractions.

5. Ease of program verification


The process of verifying that a program is correct should be easy because it is of great concern to the
reliability of the program. Ease of verification is made easier by the simplicity of semantic and syntactic
structure.

6. Programming environment
The availability of a reliable, efficient and well-documented implementation of a language is important. This
ensures that the speed of creation, testing, maintaining and modifying large programs much simpler.

7. Portability of programs.
Good programming language should have the attributes of transportability. That is, it should be easy to move
program projects from the computer on which they are developed to other computer systems. In order words,
the definitions of the program should be independent of the features of a particular machine.

CODING (PROGRAMMING)
Once an algorithm is finalized, it should be coded in a high-level programming language as selected by the
programmer. The ordered set of instructions are written in that programming language by following its syntax.

Syntax and Semantics:


syntax is the set of rules or grammar that governs the formulation of the statements in the language, such as
spellings, order of words, punctuations, etc, while Semantics is the meaning associated with the statements in a
programming language. It is all about the meaning of the statement which interprets the program easily.

Source Code:
A program written in a high -level language is called source code.
The source code is translated into machine language using a compiler or interpreter, so that it can be understood
by the computer/machine.
Decomposition:
Decomposition is a process of braking down complex problem into smaller sub problem. It is helpful, when we
have to solve any big complex problem.

➢ Breaking down a complex problem into sub problems also means that each sub problem can be examined
in details.
➢ Each sub problem can be solved independently and by different persons (or teams).
➢ Having different teams working on different sub problems can also be advantageous because specific sub
problems can be assigned to teams who are experts in solving such problems.
➢ Once the individual sub problems are solved, it is necessary to test them for their correctness and
integrate them to get complete solutions.

Programming Language Evaluation


Programming languages differ in various ways. However, a good understanding of some of the features in a
programming language can be of use. Some of the factors that may influence the choice of a
programming language by a programmer include:
➢ Programmer experience. This is basically the level of technical-know-how of the programmer.
➢ Ease of Development and Maintenance (Simplicity).
➢ Suitability of the programming language for the problem.
➢ Readability
➢ Error Checking
➢ Reliability
➢ Portability- This feature allows the programmer to program to run on many different platforms, with minimal
rewriting.
➢ Efficiency- The compiler should be fast. The code itself should be fast.
➢ Low Learning Cost- The language should be easy to learn. Training is expensive.
➢ Reusability- Writing software components once is cheaper than writing them twice.
➢ Pedagogical value-The language should support and enforce the concepts you want to teach.
➢ Writability- This criterion describes to the programmer to say what you mean, without excessive verbiage.
➢ Orthogonality- The language should support the combination of its concepts/features in a meaningful way.
➢ Consistency- The language should not include needless inconsistencies.
➢ Expressiveness- The programmer should be able to express their algorithm naturally.
➢ Abstraction- The language should support a high level of data and control abstraction.

Variable Declaration in Programming Languages


There are various kinds of programming languages. Some languages do not require that variables are declared in
a program before being used while some require that variables are declared. We can therefore have implicit and
explicit variable declaration. Variables can also be classified as global or local, depending on the level of access
from within the program.
➢ Implicit Variable Declaration
In Implicit Variable Declaration programming languages in which the variables to be used in a program may not
be declared are said to support implicit variable declaration. A good example of programming language that
supports this variable declaration type is Python. That is, in Python, a programmer may declare or choose not to
declare the variable that he intends using in a programming language.

➢ Explicit Variable Declaration


Programming languages in which the variables to be used in a program should be declared are said to support
Explicit variable declaration. Examples of such languages that support explicit variable declaration are: Java, C,
C++, PASCAL, FORTRAN, and many others.

Global Variable
A Global variable is the kind of variable that is accessible from other classes outside the program or class in which
it is declared. Different programming languages have various of ways in which global variables are being declared,
when the need arises.

Local Variable
A local variable is the kind of variable that is not accessible from other classes outside the program or class in
which it is declared. These are variables that are used within the current program unit (or function) in a later section
we will looking at global variables - variables that are available to all the program's functions.

TESTING
When first written, many programs contain bugs. Syntax errors and runtime errors are usually quickly removed,
but it can take a long time to deduce where a logic error lies and why. The purpose of testing is to help
programmers remove such bugs and to ensure that the program functions as intended. you should be building and
testing components as you develop the program. If you encounter a problem, there should be only a small
amount of new code that is not known to be correct.
It is important to note the following during program testing:
➢ The program created should be tested on various parameters.
➢ The program should meet the requirements of the user.
➢ The program must respond within the expected time.
➢ The program should generate correct output for all possible inputs.
➢ In the presence of syntactical errors, no output should be obtained from the program.
➢ In case the output generated is incorrect, then the program should be checked for logical errors.
WRITING MAINTAINABLE CODE
It is important to write program code that is easy to read and maintain so that extra features can be added later on.
Additionally, another programmer may wish to modify the program in order to improve it or debug an error.
In both situations, the understanding of the program, how it works and the purpose of the code will be made
easier if the program is written in a maintainable style. This includes using:
➢ comments
➢ descriptive names for variables, constants and subprograms
➢ indentation

➢ Comments
Comments are lines in programs that provide information about what the different parts of the program do.
They serve no other purpose and are not executed when the program is run - the program simply ignores
them and moves on to the next line of code.
Different languages express comments in different ways. In Python, for example, a comment begins with a
hash symbol, and is printed in red in some integrated development environments (IDEs), eg:
#ensures the input is restricted to a y or an n

➢ Descriptive names
Many programmers choose meaningless variable names such as x or y. While a program might run with such
names, it is difficult to understand the purpose of the variable. Programmers should choose a variable name
that reflects the purpose of the variable and the data the variables intended to hold, eg:
h - poor choice. What does it mean?
height - better choice as it describes the value the variable will hold.
The preferred use of descriptive names also applies to constants and sub-programs. For example, a constant is
often used to hold the value of Pi since this does not change. This can be called ‘PI’.
Subprograms usually perform a specific task. Giving a descriptive name like ‘multiply’ for a function that
multiplies two numbers together is sensible.

➢ Indentation
Code within selection or iteration construct should be indented. This allows programmers to easily see which
code falls within the selection or iteration, and where it ends.

FOR count FROM 1 TO 10 DO


SEND count TO DISPLAY
END FOR
The indentation of the SEND keyword inside the FOR loop (iteration) shows what parts of the code will be run
within the FOR loop.

Object-Oriented Programming (OOP)


Object Oriented Programming is a programming concept that works on the principle that objects are the most
important part of your program. It allows programmers to create the objects that they want and then create methods
to handle those objects. Manipulating these objects to get results is the goal of Object-Oriented Programming.
The major motivating factor in the invention of object-oriented approach is to remove some of the flaws
encountered in the procedural approach. OOP treats data as a critical element in the program development and does
not allow it to flow freely around the system. It ties data more closely to the function that operate on it, and protects
it from accidental modification from outside function. OOP allows decomposition of a problem into a number of
entities called objects and then builds data and function around these objects. The organization of data and function
in object-oriented programs is shown in the diagram below. The data of an object can be accessed only by the
function associated with that object. However, function of one object can access the function of other objects.

In object-oriented programming, OOP, a program code is organized into objects that contain state that is only
modified by the code that is part of the object. Examples of Object-Oriented Programming (OOP) languages
include: Java, C++, Python, Smalltalk, C# and a host of others.

Some of the features of object-oriented programming are:


➢ Emphasis is on data rather than procedure.
➢ Programs are divided into what are known as objects.
➢ Data structures are designed such that they characterize the objects.
➢ Functions that operate on the data of an object are ties together in the data structure.
➢ Data is hidden and cannot be accessed by external function.
➢ Objects may communicate with each other through function.
➢ New data and functions can be easily added whenever necessary.
➢ Follows bottom-up approach in program design.

The Fundamental Concepts (Features) of OOP


➢ Abstraction
Using simple things to represent complexity. We all know how to turn the TV on, but we don’t need to know
how it works in order to enjoy it.
Abstraction is a process of hiding the implementation details and showing only functionality to the user. It only
indicates important things to the user and hides the internal details. In other words, the user will have the
information on what the object does instead of how it does it. Abstraction is selecting data from a larger pool to
show only the relevant details to the object. It helps to reduce programming complexity and effort.
Suppose you want to create a banking application and you are asked to collect all the information about your
customer. There are chances that you will come up with so many information about the customer but, not all of
the above information is required to create a banking application.
So, you need to select only the useful information for your banking application from that pool. Data like name,
address, tax information, etc. make sense for a banking application
Since we have fetched/removed/selected the customer information from a larger pool, the process is referred as
Abstraction.
However, the same information once extracted can be used for a wide range of applications. For instance, you
can use the same data for hospital application, job portal application, a government database, etc. with little or no
modification. Hence, it becomes your Master Data. This is an advantage of Abstraction.
➢ Encapsulation
Encapsulation is the principle of wrapping the data (variables) and code acting on the data (methods) together as a
single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only
through the methods of their current class. Therefore, it is also known as data hiding.
Encapsulation is the practice of keeping fields within a class private, then providing access to those fields via
public methods. Encapsulation is a protective barrier that keeps the data and code safe within the class itself. We
can then reuse objects like code components or variables without allowing open access to the data system-wide.
But more than data hiding, encapsulation concept is meant for better management or grouping of related data. With
encapsulation, developers can change one part of the code easily without affecting other.

➢ Inheritance
Inheritance is an OOPS concept in which one object acquires the properties and behaviors of the parent object. It’s
creating a parent-child relationship between two classes. It offers robust and natural mechanism for organizing and
structuring of any software.
Inheritance lets programmers create new classes that share some of the attributes of existing classes. Using
Inheritance lets us build on previous work without reinventing the wheel.
This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in
a new class. In this scenario, the existing class is called the superclass and the derived class is called the subclass.

➢ Polymorphism
Polymorphism refers to the ability of a variable, object or function to take on multiple forms. For example, in
English, the verb run has a different meaning if you use it with a laptop, a foot race, and business. Here, we
understand the meaning of run based on the other words used along with it. The same also applied to
Polymorphism.
It Allows programmers to use the same word in a program to mean different things in different contexts. One form
of polymorphism is method overloading. That’s when the code itself implies different meanings. The other form
is method overriding. That’s when the values of the supplied variables imply different meanings.
The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child
class object.

➢ Class
A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports.
A class determines how an object will behave and what the object will contain. In other words, it is a blueprint or
a set of instruction to build a specific type of object. A class is a group of similar entities. It is only a logical
component and not a physical entity. For example, if you had a class called “Expensive Cars” it could have objects
like Mercedes, BMW, Toyota, etc. Its properties (data) can be price or speed of these cars. While the methods may
be performed with these cars are driving, reverse, braking etc.
A class system allows the program to define a new class (derived class) in terms of an existing class (superclass)
by using a technique like inheritance, overriding and augmenting.

➢ Object
An object is nothing but a self-contained component which consists of methods and properties to make a particular
type of data useful. An object can be defined as an instance of a class, and there can be multiple instances of a class
in a program. Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior
such as wagging their tail, barking, eating. An Object contains both the data and the function, which operates on
the data.
From a programming point of view, an object can be a data structure, a variable or a function. It has a memory
location allocated. The object is designed as class hierarchies.

The difference between Object and Class


A class is a blueprint or prototype that defines the variables and the methods (functions) common to all objects of
a certain kind.
While an object is a specimen of a class. Software objects are often used to model real-world objects you find in
everyday life.

➢ Methods
A method is basically a behavior. A class can contain many methods. It is in methods where the logics are
written, data is manipulated and all the actions are executed.

➢ Instance Variables
Each object has its unique set of instance variables. An object's state is created by the values assigned to these
instance variables.

➢ Dynamic binding
Binding refers to linking of procedure call to the code to be executed in response to the call. Dynamic binding (or
late binding) means the code associated with a given procedure call is not known until the time of call at run
time.

Application of OOP
OOP has become one of the programming buzzwords today. There appears to be a great deal of excitement and
interest among software engineers in using OOP.
Applications of OOP are beginning to gain importance in many areas. The most popular application of object-
oriented programming, up to now, has been in the area of user interface design such as window. Hundreds of
windowing systems have been developed, using the OOP techniques. Real-business system are often much more
complex and contain many more objects with complicated attributes and method. OOP is useful in these types of
application because it can simplify a complex problem.
The promising areas of application of OOP include:
➢ Real-time system
➢ Simulation and modeling
➢ Object-oriented data bases
➢ Hypertext, Hypermedia, and expertext
➢ AI and expert systems
➢ Neural networks and parallel programming
➢ Decision support and office automation systems
➢ CIM/CAM/CAD systems.

Python Multi Words Variable Names


Variable names with more than one word can be difficult to read. There are several techniques you can use to
make them more readable:
❖ Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"

❖ Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"

❖ Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"

HOW TO CONVERT FROM ONE TYPE TO ANOTHER:


x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

print(a)
print(b)
print(c)

HOW TO VERIFY THE TYPE OF ANY OBJECT IN PYTHON


To verify the type of any object in Python, use the type() function:

print(type(a))
print(type(b))
print(type(c))
UPPER CASE METHOD
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())

LOWER CASE METHOD


The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())

REMOVE WHITESPACE
Whitespace is the space before and/or after the actual text, and very often you want to remove this space.
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
PYTHON SAMPLE PROGRAMS
PROGRAM TO FIND THE ROOTS OF QUADRATIC EQUATION (METHOD 1)

1. # import complex math module


2. import cmath
3. a = float(input('Enter a: '))
4. b = float(input('Enter b: '))
5. c = float(input('Enter c: '))
6.
7. # calculate the discriminant
8. d = (b**2) - (4*a*c)
9.
10. # find two solutions
11. sol1 = (-b-cmath.sqrt(d))/(2*a)
12. sol2 = (-b+cmath.sqrt(d))/(2*a)
13. print('The solution are {0} and {1}'.format(sol1,sol2))

PROGRAM TO FIND THE ROOTS OF QUADRATIC EQUATION (METHOD 2)

1. # Python program to find roots of quadratic equation


2. import math
3.
4. # function for finding roots
5. def findRoots(a, b, c):
6.
7. dis_form = b * b - 4 * a * c
8. sqrt_val = math.sqrt(abs(dis_form))
9.
10. if dis_form > 0:
11. print(" real and different roots ")
12. print((-b + sqrt_val) / (2 * a))
13. print((-b - sqrt_val) / (2 * a))
14.
15. elif dis_form == 0:
16. print(" real and same roots")
17. print(-b / (2 * a))
18.
19. else:
20. print("Complex Roots")
21. print(- b / (2 * a), " + i", sqrt_val)
22. print(- b / (2 * a), " - i", sqrt_val)
23. a = int(input('Enter a:'))
24. b = int(input('Enter b:'))
25. c = int(input('Enter c:'))
26.
27. # If a is 0, then incorrect equation
28. if a == 0:
29. print("Input correct quadratic equation")
30.
31. else:
32. findRoots(a, b, c)

PROGRAM TO FIND THE DIAMETER, CIRCUMFERENCE, AND AREA OF A CIRCLE


The mathematical formulas are:
1. Diameter of a Circle = 2r = 2 * radius
2. Area of a circle is: A = πr² = π * radius * radius
3. Circumference of a Circle = 2πr = 2 * π * radius

# Python Program to find Diameter, Circumference, and Area Of a Circle


import math

def find_Diameter(radius):
return 2 * radius

def find_Circumference(radius):
return 2 * math.pi * radius

def find_Area(radius):
return math.pi * radius * radius

r = float(input(' Please Enter the radius of a circle: '))

diameter = find_Diameter(r)
circumference = find_Circumference(r)
area = find_Area(r)

print("\n Diameter Of a Circle = %.2f" %diameter)


print(" Circumference Of a Circle = %.2f" %circumference)
print(" Area Of a Circle = %.2f" %area)
PYTHON PROGRAM TO FIND FACTORIAL OF GIVEN NUMBER (METHOD 1)

1. # Python program to find


2. # factorial of given number
3. import math
4. def fact(n):
5. return(math.factorial(n))
6.
7. num = int(input("Enter the number:"))
8. f = fact(num)
9. print("Factorial of", num, "is", f)

PYTHON PROGRAM TO FIND FACTORIAL OF GIVEN NUMBER (METHOD 2)


1. n! = n* (n-1) * (n-2) *........1
2. num = int(input("Enter a number: "))
3. factorial = 1
4. if num < 0:
5. print(" Factorial does not exist for negative numbers")
6. elif num == 0:
7. print("The factorial of 0 is 1")
8. else:
9. for i in range(1,num + 1):
10. factorial = factorial*i
11. print("The factorial of",num,"is",factorial)

PYTHON PROGRAM TO FIND VOLUME AND SURFACE AREA OF SPHERE (METHOD 1)


4
(The surface area of a sphere is: 𝐴𝑟𝑒𝑎 = 4𝜋𝑟 2 and the volume is: 𝑉𝑜𝑙𝑢𝑚𝑒 = 3 𝜋𝑟 3 where r is the radius).

1. pi=22/7
2. radian = float(input('Radius of sphere: '))
3. sur_area = 4 * pi * radian **2
4. volume = (4/3) * (pi * radian ** 3)
5. print("Surface Area is: ", sur_area)
6. print("Volume is: ", volume)
PYTHON PROGRAM TO FIND VOLUME AND SURFACE AREA OF SPHERE (METHOD 1)
4
(The surface area of a sphere is: 𝐴𝑟𝑒𝑎 = 4𝜋𝑟 2 and the volume is: 𝑉𝑜𝑙𝑢𝑚𝑒 = 3 𝜋𝑟 3 where r is the radius).

1. import math

2. def Area_of_Triangle(radius):
3. sa = 4 * math.pi * radius * radius
4. Volume = (4 / 3) * math.pi * radius * radius * radius
5. print("\n The Surface area of a Sphere = %.2f" %sa)
6. print("\n The Volume of a Sphere = %.2f" %Volume)

You might also like