
Structured Programming Paradigm
Procedural Programming Paradigm
Object-Oriented Programming
Declarative paradigm
Structured Programming Paradigm
•Structured programming is a paradigm that is based on improving clarity and quality of programs by using subroutines, block structures and loops (for and while) and discouraging the use of goto statement.
Structured code for the individual modules:
Structured coding relates to division of modules into set of instructions organized within control structures. A control structure defines the order in which a set of instructions are executed. The statements within a specific control structure are executed:
•sequentially – denotes in which order the controls are executed. They are executed one after the other in the exact order they are listed in the code.
•conditionally – allows choosing which set of controls is executed. Based on the needed condition, one set of commands is chosen while others aren’t executed.
•repetitively – allows the same controls to be performed over and over again. Repetition stops when it meets certain terms or performs a defined number of iterations.
SIMPLE IF
if test expression:
statement(s)
IF….ELSE
if test expression:
Body of if
else:
Body of else
IF...ELIF...ELSE
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
NESTED IF
if test expression:
if test expression:
Body of if
else:
Body of else
else:
Body of else
Procedural Programming Paradigm
•In a multi-function program, many important data items are placed as global so that they may be accessed by all functions. Each function may have its own local data. If a function made any changes to global data, these changes will reflect in other functions. Global data are more unsafe to an accidental change by a function. In a large program it is very difficult to identify what data is used by which function.
•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.
•There are 2 types of function
Built-in function ex. Print() max(3,4) min(3,4), len(), range(), Round(),int(), float(), input(), tuple()
User defined function -User can create their own functions.
•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 first statement of a function can be an optional statement - the documentation string of the function or docstring.
•The code block within every function starts with a colon (:) and is indented.
•The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
Object-Oriented Programming
It is an approach that provides a way of modularizing programs by creating partitioned memory area for both data and functions that can be used as templates for creating copies of such modules on demand. Thus the object is considered to be a partitioned area of computer memory that stores data and set of operations that can access that data.
•Objects
•Classes
•Data Abstraction and Encapsulation
•Inheritance
•Polymorphism
•Dynamic Binding
•Message Passing
Declarative paradigm
•Declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow.
•Logic, functional and domain-specific languages belong under declarative paradigms
Examples would be HTML, XML, CSS, SQL, Prolog, Haskell, F# and Lisp.
•Declarative code focuses on building logic of software without actually describing its flow. You are saying what without adding how. For example with HTML you use <img src="./image.jpg" /> to tell browser to display an image and you don’t care how it does that.
Control Structures in Python
Most programs don't operate by carrying out a straightforward sequence of statements. A code is written to allow making choices and several pathways through the program to be followed depending on shifts in variable values.
All programming languages contain a pre-included set of control structures that enable these control flows to execute, which makes it conceivable.
This tutorial will examine how to add loops and branches, i.e., conditions to our Python programs.
Sequential - The default working of a program
Selection - This structure is used for making decisions by checking conditions and branching
Repetition - This structure is used for looping, i.e., repeatedly executing a certain piece of a code block.
Sequential
Sequential statements are a set of statements whose execution process happens in a sequence. The problem with sequential statements is that if the logic has broken in any one of the lines, then the complete source code execution will break.
Code
# Python program to show how a sequential control structure works
# We will initialize some variables
# Then operations will be done
# And, at last, results will be printed
# Execution flow will be the same as the code is written, and there is no hidden flow
a = 20
b = 10
c = a - b
d = a + b
e = a * b
print("The result of the subtraction is: ", c)
print("The result of the addition is: ", d)
print("The result of the multiplication is: ", e)
Output:
The result of the subtraction is: 10
The result of the addition is :
30
The result of the multiplication is: 200
Selection/Decision Control Statements
The statements used in selection control structures are also referred to as branching statements or, as their fundamental role is to make decisions, decision control statements.
A program can test many conditions using these selection statements, and depending on whether the given condition is true or not, it can execute different code blocks.
There can be many forms of decision control structures. Here are some most commonly used control structures:
Only if
if-else
The nested if
The complete if-elif-else
Simple if
If statements in Python are called control flow statements. The selection statements assist us in running a certain piece of code, but only in certain circumstances. There is only one condition to test in a basic if statement.
The if statement's fundamental structure is as follows:
Syntax
if <conditional expression> :
The code block to be executed if the condition is True
These statements will always be executed. They are part of the main code.
All the statements written indented after the if statement will run if the condition giver after the if the keyword is True. Only the code statement that will always be executed regardless of the if the condition is the statement written aligned to the main code. Python uses these types of indentations to identify a code block of a particular control flow statement. The specified control structure will alter the flow of only those indented statements.
if-else
If the condition given in if is False, the if-else block will perform the code t=given in the else block.
Code
# Python program to show how to use the if-else control structure
# Initializing two variables
v = 4
t = 5
print("The value of v is ", v, "and that of t is ", t)
# Checking the condition
if v > t :
print("v is greater than t")
# Giving the instructions to perform if the if condition is not true
else :
print("v is less than t")
Repetition
To repeat a certain set of statements, we use the repetition structure.
There are generally two loop statements to implement the repetition structure:
The for loop
The while loop
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
Increase Code Readability
Increase Code Reusability
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any type of functionalities and properties to it as we require. By the following example, we can understand how to write a function in Python. In this way we can create Python function definition by using def keyword.
Python3
# A simple Python function
def fun():
print("Welcome to GFG")
Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions Python followed by parenthesis containing parameters of that particular function. Below is the example for calling def function Python.
Python3
# A simple Python function
def fun():
print("Welcome to GFG")
# Driver code to call a function
fun()
Output:
Welcome to GFG
Python Function with Parameters
If you have experience in C/C++ or Java then you must be thinking about the return type of the function and data type of arguments. That is possible in Python as well (specifically for Python 3.5 and above).
Python Function Syntax with Parameters
def function_name(parameter: data_type) -> return_type: """Docstring""" # body of the function return expression
Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp – For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops.
While all the ways provide similar basic functionality, they differ in their syntax and condition-checking time. In this article, we will look at Python loops and understand their working with the help of examples.
While Loop in Python
In Python, a while loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
output:
Hello Geek
Hello Geek
Hello Geek
For Loop in Python
For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is “for in” loop which is similar to foreach loop in other languages. Let us learn how to use for loops in Python for sequential traversals with examples.
n = 4
for i in range(0, n):
print(i)
output:
0
1
2
3
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
Table of Content
Create First Tkinter GUI Application
Tkinter Widget
Color and Font Option in Tkinter
Geometry Management
To create a Tkinter Python app, you follow these basic steps:
Import the tkinter module: This is done just like importing any other module in Python. Note that in Python 2.x, the module is named ‘Tkinter’, while in Python 3.x, it is named ‘tkinter’.
Create the main window (container): The main window serves as the container for all the GUI elements you’ll add later.
Add widgets to the main window: You can add any number of widgets like buttons, labels, entry fields, etc., to the main window to design the interface as desired.
Apply event triggers to the widgets: You can attach event triggers to the widgets to define how they respond to user interactions.
Tk()
To create a main window, tkinter offers a method ‘Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)’. To change the name of the window, you can change the className to the desired one. The basic code used to create the main window of the application is:
mainloop()
There is a method known by the name mainloop() is used when your application is ready to run. mainloop() is an infinite loop used to run the application, wait for an event to occur, and process the event as long as the window is not closed.
import tkinter
m = tkinter.Tk()
'''widgets are added here'''
m.mainloop()
•Process - an instance of a computer program that is being executed.
•process - 3 basic components:
An executable program.
The associated data needed by the program (variables, work space, buffers, etc.)
The execution context of the program (State of process)
•Thread - an entity within a process
–smallest unit of processing
•In simple words, a thread is a sequence of instructions within a program that can be executed independently of other code.
•For simplicity, you can assume that a thread is simply a subset of a process!
•A thread contains all this information in a Thread Control Block (TCB):
•Thread Identifier: Unique id (TID) is assigned to every new thread
•Stack pointer: Points to thread’s stack in the process. Stack contains the local variables under thread’s scope.
•Program counter: a register which stores the address of the instruction currently being executed by thread.
•Thread state: can be running, ready, waiting, start or done.
•Thread’s register set: registers assigned to thread for computations.
•Parent process Pointer: A pointer to the Process control block (PCB) of the process that the thread lives on.
Multithreading:
•Multithreading -is defined as the ability of a processor to execute multiple threads concurrently.
•Multiple threads can exist within one process where:
qEach thread contains its own register set and local variables (stored in stack).
qAll thread of a process share global variables (stored in heap) and the program code.
•threading API is used for spawning multiple threads in a program.
•The threading module exposes all the methods of the thread module and provides some additional methods −
–threading.activeCount() − Returns the number of thread objects that are active.
–threading.currentThread() − Returns the number of thread objects in the caller's thread control.
–threading.enumerate() − Returns a list of all thread objects that are currently active.
•The methods provided by the Thread class are as follows −
–run() − The run() method is the entry point for a thread.
–start() − The start() method starts a thread by calling the run method.
–join([time]) − The join() waits for threads to terminate.
–isAlive() − The isAlive() method checks whether a thread is still executing.
–getName() − The getName() method returns the name of a thread.
–setName() − The setName() method sets the name of a thread.
# Python program to illustrate the concept
# of threading
# importing the threading module
import threading
def print_cube(num):
"""function to print cube of given num"""
print("Cube: {}".format(num * num * num))
def print_square(num):
"""function to print square of given num"""
print("Square: {}".format(num * num))
if __name__ == "__main__":
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
# starting thread 1
t1.start()
# starting thread 2
t2.start()
# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
# both threads completely executed
print("Done!")
Output
Square: 100
Cube: 1000
Done!
Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style. It is a declarative type of programming style. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve”. It uses expressions instead of statements. An expression is evaluated to produce a value whereas a statement is executed to assign variables. Those functions have some special features discussed below.
Functional Programming is based on Lambda Calculus:
Lambda calculus is a framework developed by Alonzo Church to study computations with functions. It can be called as the smallest programming language in the world. It gives the definition of what is computable. Anything that can be computed by lambda calculus is computable. It is equivalent to Turing machine in its ability to compute. It provides a theoretical framework for describing functions and their evaluation. It forms the basis of almost all current functional programming languages.
Pure functions
Recursion
Referential transparency
Functions are First-Class and can be Higher-Order
Variables are Immutable
Advantages:
Pure functions are easier to understand because they don’t change any states and depend only on the input given to them. Whatever output they produce is the return value they give. Their function signature gives all the information about them i.e. their return type and their arguments.
The ability of functional programming languages to treat functions as values and pass them to functions as parameters make the code more readable and easily understandable.
Testing and debugging is easier. Since pure functions take only arguments and produce output, they don’t produce any changes don’t take input or produce some hidden output. They use immutable values, so it becomes easier to check some problems in programs written uses pure functions.
It is used to implement concurrency/parallelism because pure functions don’t change variables or any other data outside of it.
It adopts lazy evaluation which avoids repeated evaluation because the value is evaluated and stored only when it is needed.
Python is a popular programming language. It's used for many things like web development, data science and scientific computing. It's easy to learn and has many resources available. Taking a Python course can help you learn to program or get a job that uses Python.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics developed by Guido van Rossum. It was originally released in 1991. Designed to be easy as well as fun, the name "Python" is a nod to the British comedy group Monty Python.
What you'll learn
Install Python and write your first program
Describe the basics of the Python programming language
Use variables to store, retrieve and calculate information
Utilize core programming tools such as functions and loops
This course is part of the Python for Everybody Specialization
When you enroll in this course, you'll also be enrolled in this Specialization.
Learn new concepts from industry experts
Gain a foundational understanding of a subject or tool
Develop job-relevant skills with hands-on projects
Earn a shareable career certificate
When students complete Intro to Programming with Python, they will be able to: Build basic programs using fundamental programming constructs like variables, conditional logic, looping, and functions. Work with user input to create fun and interactive