0% found this document useful (0 votes)
8 views121 pages

Backend App

Python is a high-level, versatile programming language created by Guido van Rossum in 1991, known for its simplicity and ease of learning. It supports various programming paradigms and is widely used in web development, data science, artificial intelligence, and more. Python is open-source, has a rich set of libraries and frameworks, and is popular among developers for its powerful features and high demand in the job market.

Uploaded by

nethynethy11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views121 pages

Backend App

Python is a high-level, versatile programming language created by Guido van Rossum in 1991, known for its simplicity and ease of learning. It supports various programming paradigms and is widely used in web development, data science, artificial intelligence, and more. Python is open-source, has a rich set of libraries and frameworks, and is popular among developers for its powerful features and high demand in the job market.

Uploaded by

nethynethy11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 121

N N

INTRODUCE PYTHON LANGUAGE


Python is a widely used high-level
programming language for general-purpose
programming, created by Guido van Rossum
and first released in 1991.
It supports Object Oriented programming
approach to develop applications.
It is simple and easy to learn and provides lots
of high-level data structures.
The various area python used for:
web development (server-side),
 software development,
mathematics,
 Artificial intelligent,
Data science,
Mobile application,
Desktop application .
Characteristics of python
• Easy to Code: Python is very easy to code as compared to
other popular languages like Java and C++.
• Easy to Read: Being a high-level language, Python code is
quite like English. Looking at it, you can tell what the code
is supposed to do.
• Free and Open-Source
Firstly, Python is freely available. You can download it from
the Python Official Website.
Secondly, it is open-source. This means that its source code
is available to the public. You can download it, change it, use
it, and distribute it
cont
 Python can be used on a server to create web
applications.
 Python can be used along side software to create
workflows.
 Python can connect to database systems. It can also
read and modify files
 Python can be used to handle big data and perform
complex mathematics.
 Python can be used for rapid prototyping, or for
production-ready software development.
Why we learn python

There are many reason which makes python as top


choice of any programmer
 The python is open source means that it’s available
free of cost
 Python is simple and so easy to learn
 Python is versatile and can be used to create many
different things
 Python has powerful development libraries include
AI,ML
 Python is much demand and ensure high salary
Python Syntax compared to other
programming languages
• Python is an interpreted and dynamically
typed language, whereas Java is a compiled
and statically typed language.
pupublic class PythonandJava {
public static void main(String[] args)
{
System.out.println("Python and Java!");
}
}

print("Python and Java !")


Python Basic Syntax

• There is no use of curly braces or semicolon in Python


programming language. It is English-like language. But
Python uses the indentation to define a block of
code(:).
• def func():
• statement 1
• statement 2
• …………………
• …………………
• statement N
installing Python and Pycharm
1. Installing Python
Step 1) To download and install Python visit
the official website of Python
http://www.python.org/downloads/ and then
choose the version you want.
cont
• Step 2) Once the download is complete, run
the exe for install Python. Now click on
Lu 1.2 describe python editor IDE and
framework
• IDE: is software application that helps a
programmer to develop software code
efficiently
It incraese developer productivity by
combinning capabilities such as testing and
packaging in easy-to-use application
It contain a compiler and interpreter both
Example:pycharm,wing,spyder,eclipse pydev,idle
pycharm
• PyCharm was developed by the Jet Brains, and it is a cross-platform
Integrated Development Environment (IDE) specially designed for python.
It is the most widely used IDE and available in both paid version and free
open-source as well. It saves ample time by taking care of routine tasks.
• It is a complete python IDE that is loaded with a rich set of features like
auto code completion, quick project navigation, fast error checking and
correction, remote development support, database accessibility, etc.
Features
• Smart code navigation
• Errors Highlighting
• Powerful debugger
• Supports Python web development frameworks, i.e., Angular JS, Javascript
Python framework
What is Framework ?
is collection of programs that you can use to
develop your own application.
Is set of pre-written code libraries designed to
be used by developer
Examples of python framework:
Django,cherrypy,turbo gears…….
cont
Python has wide range of libraries and frameworks widely
used in various fields such as machine learning, artificial
intelligence, web applications, etc. We define some
popular frameworks and libraries of Python as follows
• Web development (Server-side) - Django Flask,
Pyramid, CherryPy
• GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
• Machine Learning - TensorFlow, PyTorch, Scikit-learn,
Matplotlib, Scipy, etc.
• Mathematics - Numpy, Pandas, etc.
python editors
Text editor or editor :Is the software program
that enable the user to create and to edit text
files
Examples:sublime text,vim visual studio code
Coding and programming strategies
• Collect data from individual.
• Analyze and interpreting data .
• Choosing appropriate
tools(language ,IDE,framework and editor).
• Implementing solution.
• Presenting and testing prototype to the
system user and get new input.
• Handling over the solution with client.
Python print() Function

• The print() function displays the given object to the


standard output device (screen) or to the text stream file.
• Example - 1: Return a value
print("Welcome to javaTpoint.")
a = 10
# Two objects are passed in print() function
print("a =", a)
b=a
# Three objects are passed in print function
print('a =', a, '= b')
output
• Welcome to javaTpoint.
• a = 10
• a = 10 = b
Standard data types

• A variable can hold different types of values. For example, a


person's name must be stored as a string whereas its id
must be stored as an integer.
• Python provides various standard data types that define the
storage method on each of them. The data types defined in
Python are given below.
• Numbers
• Sequence Type
• Boolean
• Set
• Dictionary
PYTHON DATA TYPES
Python supports three types of numeric
data.
• Int - Integer value can be any length such as integers
10, 2, 29, -20, -150 etc. Python has no restriction on
the length of an integer. Its value belongs to int
• Float - Float is used to store floating-point numbers
like 1.9, 9.902, 15.2, etc. It is accurate upto 15
decimal points.
• complex - A complex number contains an ordered
pair, i.e., x + iy where x and y denote the real and
imaginary parts, respectively. The complex numbers
like 2.14j, 2.0 + 2.3j, etc.
Numbers

• Number stores numeric values. The integer, float, and complex values
belong to a Python Numbers data-type. Python provides the type() function
to know the data-type of the variable. Similarly, the isinstance() function is
used to check an object belongs to a particular class.
• a=5
• print("The type of a", type(a))

• b = 40.5
• print("The type of b", type(b))

• c = 1+3j
• print("The type of c", type(c))
• print(" c is a complex number", isinstance(1+3j,complex))
Sequence Type

• The string can be defined as the sequence of


characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes
to define a string.
• String handling in Python is a straightforward task
since Python provides built-in functions and
operators to perform operations in the string.
• In the case of string handling, the operator + is used
to concatenate two strings as the operation "hello"+"
python" returns "hello python".
STRING EXAMPLES
• str = "string using double quotes"
• print(str)
• s = '''''A multiline
• string'''
• print(s)
Accessing string in python
• str = 'Hello student!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5] )# Prints characters starting from 3rd
to 5th
print(str[2:] ) # Prints string starting from 3rd
character
print (str * 2 )# Prints string two times
print (str + "TEST") # Prints concatenated string
Python Lists

• Lists are used to store multiple items in a single variable.


• Python Lists are similar to arrays in C. However, the list can contain
data of different types. The items stored in the list are separated with
a comma (,) and enclosed within square brackets [].
• We can use slice [:] operators to access the data of the list. The
concatenation operator (+) and repetition operator (*) works with the
list in the same way as they were working with the strings.
• The values stored in a list can be accessed using the slice operator ([ ]
and [:]) with indexes starting at 0 in the beginning of the list and
working their way to end -1. The plus (+) sign is the list concatenation
operator, and the asterisk (*) is the repetition operator.
• thislist = ["apple", "banana", "cherry"]
print(thislist)
Cont,
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
list2 = [123, 'john']

print (list) # Prints complete list


print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (list2 * 2) # Prints list two times
print (list + list2) # Prints concatenated lists
Python Tuple Data Type

• Python tuple is another sequence data type that is


similar to a list. A Python tuple consists of a number
of values separated by commas. Unlike lists, however,
tuples are enclosed within parentheses
• The main differences between lists and tuples are:
Lists are enclosed in brackets ( [ ] ) and their elements
and size can be changed, while tuples are enclosed in
parentheses ( ( ) ) and cannot be updated. Tuples can
be thought of as read-only lists.
Cont,
• tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
• tuple1 = (123, 'john')

• print (tuple) # Prints the complete tuple


• print (tuple[0]) # Prints first element of the tuple
• print (tuple[1:3]) # Prints elements of the tuple starting from
2nd till 3rd
• print (tuple[2:]) # Prints elements of the tuple starting from
3rd element
• print (tuple2 * 2) # Prints the contents of the tuple twice
• print (tuple + tuple2)# Prints concatenated tuples
Python range
• Python range() is an in-built function in Python which returns a
sequence of numbers starting from 0 and increments to 1 until it
reaches a specified number.
• We use range() function with for and while loop to generate a
sequence of numbers. Following is the syntax of the function:
• range(start, stop, step)
• descr
• start: Integer number to specify starting position, (Its optional,
Default: 0)
• stop: Integer number to specify starting position (It's mandatory)
• step: Integer number to specify increment, (Its optional, Default:
1)
Examples

• Following is a program which uses for loop to


print number from 0 to 20
for a in range(20):
print(a)
Now let's modify above program to print the
number starting from 1 instead of 0:
for i in range(1, 20):
print(i)
Python dictionaries
• Dictionaries are used to store data values in
key:value pairs.
• They work like associative arrays. A dictionary
key can be almost any Python type, but are
usually numbers or strings. Values, on the other
hand, can be any arbitrary Python object.
• Dictionaries are enclosed by curly braces ({ })
and values can be assigned and accessed using
square braces ([]).
examples
• dict = {}
• dict['one'] = "This is one"
• dict[2] = "This is two"

• tinydict = {'name': 'john','code':6734, 'dept': 'sales‘}


• print("\nDictionary with the use of Mixed Keys: ")
• print (dict['one']) # Prints value for 'one' key
• print (dict[2]) # Prints value for 2 key
• print (tinydict) # Prints complete dictionary
• print (tinydict.keys()) # Prints all the keys
• print (tinydict.values()) # Prints all the values
Python Boolean Data Types

• Python boolean type is one of built-in data


types which represents one of the two values
either True or False. Python bool() function
allows you to evaluate the value of any
expression and returns either True or False
based on the expression.
Python Set
• Python Set is the unordered collection of the
data type. It is iterable, mutable(can modify
after creation), and has unique elements.
The set is created by using a built-in
function set(), or a sequence of elements is
passed in the curly braces and separated by the
comma.
Examples of set
• # Creating Empty set
• set1 = set()

• set2 = {'James', 2, 3,'Python'}

• #Printing Set value
• print(set2)

• # Adding element to the set

• set2.add(10)
• print(set2)

• #Removing element from the set
• set2.remove(2)
• print(set2)
operators
The operator is a symbol that performs a certain operation
between two operands, according to one definition.
The different operators that Python offers are listed here.
1. Arithmetic operators
2. Comparison operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic operators

• It includes the exponent (**) operator as well


as the + (addition), - (subtraction), *
(multiplication), / (divide), % (reminder),
and // (floor division) operators.
Operator Description
Cont,
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20

- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value results negative. For
example, if a = 20, b = 5 => a - b = 15

/ (divide) It returns the quotient after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a/b = 2.0

* (Multiplication) It is used to multiply one operand with the other. For example, if a = 20, b =
4 => a * b = 80
% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0

** (Exponent) As it calculates the first operand's power to the second operand, it is an


exponent operator.
Comparison operator
Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

<= The condition is met if the first operand is smaller than or equal to the second operand.

>= The condition is met if the first operand is greater than or equal to the second operand.

> If the first operand is greater than the second operand, then the condition becomes true.

< If the first operand is less than the second operand, then the condition becomes true.
Assignment Operators
Operator Description
= It assigns the value of the right expression to the left operand.
+= By multiplying the value of the right operand by the value of the left operand, the left operand
receives a changed value. For example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b
and therefore, a = 30.

-= It decreases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to
a = a- b and therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right operand and assigns the
modified value back to then the left operand. For example, if a = 10, b = 20 => a* = b will be
equal to a = a* b and therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand and assigns the
reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal to
a = a % b and therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.
Bitwise Operators

• The two operands' values are processed bit by


bit by the bitwise operators. Consider the case
below.
• For example,

Cont,
Operator Description

& (binary and) A 1 is copied to the result if both bits in two operands at the same location are 1. If not, 0 is
copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be 1.

^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.

~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next bit will be 1,
and vice versa.

<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of the value of the
left operand.

>> (right shift) The left operand is moved right by the number of bits present in the right operand.
Logical Operators
Operator Description

and The condition will also be true if the expression is true. If the two
expressions a and b are the same, then a and b must both be
true.

or The condition will be true if one of the phrases is true. If a and b


are the two expressions, then an or b must be true if and is true
and b is false.

not If an expression a is true, then not (a) will be false and vice
versa.
Membership Operators

• The membership of a value inside a Python


data structure can be verified using Python
membership operators. The result is true if the
value is in the data structure; otherwise, it
returns false.
Operator Description

in If the first operand cannot be found in the second operand, it is


evaluated to be true (list, tuple, or dictionary).

not in If the first operand is not present in the second operand, the
evaluation is true (list, tuple, or dictionary).
examples
1.fruits = ["apple", "banana", "cherry", "date"]
if "grape" not in fruits:
print("No, 'grape' is not in the list.")
2. sentence = "Hello, World!“
if "o" in sentence:
print("Yes, 'o' is in the string.")
Identity Operators

Operator Description

is If the references on both sides point to the same object, it is


determined to be true.

is not If the references on both sides do not point at the same


object, it is determined to be true.
1.4: Python algorithms
• Algorithm is a step-by-step procedure, which
defines a set of instructions to be executed in
a certain order to get the desired output.
Algorithms are generally created independent
of underlying languages, i.e. an algorithm can
be implemented in more than one
programming language.
Characteristics of an Algorithm
 Unambiguous − Algorithm should be clear and unambiguous.
Each of its steps (or phases), and their inputs/outputs should be
clear and must lead to only one meaning.
 Input − An algorithm should have 0 or more well-defined inputs.
 Output − An algorithm should have 1 or more well-defined
outputs, and should match the desired output.
 Finiteness − Algorithms must terminate after a finite number of
steps.
 Feasibility − Should be done or achieved, with the available
resources.
 Independent − An algorithm should have step-by-step directions,
which should be independent of any programming code.
How to Write an Algorithm?
• Problem − Design an algorithm to add two numbers and display the
result
• step 1 − START
step 2 − declare three integers a, b & c
step 3 − define values of a & b
step 4 − add values of a & b
step 5 − store output of step 4 to c
step 6 − print c
step 7 − STOP
We write algorithms in a step-by-step manner, but it is not always the
case. Algorithm writing is a process and is executed after the problem
domain is well-defined. That is, we should know the problem domain, for
which we are designing a solution.
Cont,
• step 1 − START ADD
• step 2 − get values of a & b
• step 3 − c ← a + b
• step 4 − display c
• step 5 − STOP
LEARNING UNIT 2: APPLY OBJECTS,
METHODS AND FLOW CONTROLS

• Like other general-purpose programming


languages, Python is also an object-oriented
language since its beginning. It allows us to
develop applications using an Object-Oriented
approach. In Python, we can easily create and
use classes and objects.
• The object is related to real-word entities such
as book, house, pencil, etc. The oops concept
focuses on writing the reusable code.
Cont,
• Major principles of object-oriented programming
system are given below.
• Class
• Object
• Method
• Inheritance
• Polymorphism
• Data Abstraction
• Encapsulation
Python Classes/Objects
• Python is an object oriented programming
language. Almost everything in Python is an
object, with its properties and methods. A
Class is like an object constructor, or a
"blueprint" for creating objects.
• Create a Class
To create a class, use the keyword class:
class
• The class can be defined as a collection of objects. It is a
logical entity that has some specific attributes and methods.
For example: if you have an employee class, then it should
contain an attribute and method, i.e. an email, id, name,
age,sex, salary, etc.
• Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
object
• the object is an entity that has state and behavior. It may be any
real-world object like the mouse, keyboard, chair, table, pen, etc.
• Also, you can find intangible objects such as bank accounts and
transactions.
• All of these objects share the two common key characteristics:
• State
• Behavior
• For example, a bank account has the state that consists of:
• Account number
• Balance
• A bank account also has the following behaviors:
• Deposit
• Withdraw
• An object holds its state in variables that are often referred to
Ctn,
• To understand the meaning of classes we have to
understand the built-in __init__() function
• All classes have a function called __init__(), which
is always executed when the class is being initiated.
Use the __init__() function to assign values to
object properties, or other operations that are
necessary to do when the object is being created:
• When we define a class, it needs to create an object
to allocate the memory. Consider the following
The self Parameter and init function
• The self parameter is a reference to the current instance of
the class, and is used to access variables that belongs to the
class.
• __init__ is one of the reserved methods in Python. In object
oriented programming, it is known as a constructor.
• The __init__ method can be called when an object is created
from the class, and access is required to initialize the
attributes of the class.
examples
• class Person:
• def __init__(self, first_name, last_name, age, address):
• self.first_name = first_name
• self.last_name = last_name
• self.age = age
• self.address = address
• p1 = Person("kubwimana", "job" , 36 , "GIKONKO")

• print(p1.first_name + p1.last_name)
• print(p1.age)
• print(p1.address)
Method

• By definition, a method is a function that is bound to


an instance of a class.
• Objects can also contain methods. Methods in objects
are functions that belong to the object.
• Syntax
• Class className:
def method_name():
…………….
method body
………………..
Example of using method in python
• class Person:
• def __init__(self, name1, lname , age):
• self.name1 = name1
• self.age = age
• self.lname = lname
• #method definition
• def myfunc(self):
• print("Hello my name is " + self.name1 + self.lname)
• #object of class
• p1 = Person("John","kubwimana", 36)
• #function calling
• p1.myfunc()
Delete Object Properties
• You can delete properties on objects by using the del keyword:
• Example
• Delete the p1 object: del p1
• The pass Statement .
• Use the pass keyword when you do not want to add any other
properties or methods to the class.

• class definitions cannot be empty, but if you for some reason have
a class definition with no content, put in the pass statement to
avoid getting an error.
• Example class Person:
pass
Python Inheritance

• Inheritance allows us to define a class that inherits all the methods


and properties from another class.
• Parent class is the class being inherited from, also called base class.
• Child class is the class that inherits from another class, also called
derived class
• Inheritance provides code reusability to the program because we
can use an existing class to create a new class instead of creating it
from scratch.
• In python, a derived class can inherit base class by just
mentioning the base in the bracket after the derived class name.
Consider the following syntax to inherit a base class into the
derived class.
Syntax of inheritance

<class - suite>
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Inheritance examples
• class Animal:
• def speak(self):
• print("Animal Speaking")
• #child class Dog inherits the base class Animal
• class Dog(Animal):
• def bark(self):
• print("dog barking")
• #object definition
• obj = Dog()
• obj.bark()
• obj.speak()
Use the super() Function
• Python also has a super() function that will make the
child class inherit all the methods and properties from
its parent:
• Example class Student(Person):
def __init__(self, fname, lname):

super().__init__(fname, lname)
By using the super() function, you do not have to use
the name of the parent element, it will automatically
inherit the methods and properties from its parent.
Python Multiple inheritance

Python provides us the flexibility to inherit multiple base classes in the child
class
Syntax

• class Base1:
• <class-suite>

• class Base2:
• <class-suite>
• .
• .
• .
• class BaseN:
• <class-suite>

• class Derived(Base1, Base2, ...... BaseN):
• <class-suite>
Examples:
• class Calculation1:
• def Summation(self,a,b):
• return a+b;
• class Calculation2:
• def Multiplication(self,a,b):
• return a*b;
• class Calculation3:
• def difference(self,a,b) :
• return a-b;
• class Derived(Calculation1,Calculation2,Calculation3):
• def Divide(self,a,b):
• return a/b;
• d = Derived()
• print(d.Summation(12,20))
• print(d.Multiplication(10,20))
• print(d.Divide(30,20))
• print(d.difference(45,25))
The issubclass(sub,sup) method

• he issubclass(sub, sup) method is used to check the relationships between the


specified classes. It returns true if the first class is the subclass of the second class,
and false otherwise.
• class Calculation1:
• def Summation(self,a,b):
• return a+b;
• class Calculation2:
• def Multiplication(self,a,b):
• return a*b;
• class Derived(Calculation1,Calculation2):
• def Divide(self,a,b):
• return a/b;
• d = Derived()
• print(isinstance(d,Derived))
• Output:true
LO 2.2:Implement python function,flow
controls, loops and files
• Python Functions
• A function is a block of code that performs a specific
task.
• 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:
Types of function

• There are two types of function in Python


programming:
• Standard library functions - These are built-in
functions in Python that are available to use.
• User-defined functions - We can create our
own functions based on our requirements.
Python Function Declaration

• The syntax to declare a function is:


def function_name(arguments):
# function body
return
Here,
• def - keyword used to declare a function
• function_name - any name given to the function
• arguments - any value passed to function
• return (optional) - returns value from a function
Example:
def greet():
print('Hello World!')
Calling a Function in Python
• def my_function():
• print("Hello from a function")
• # To call a function, use the function name followed by parenthesis:
my_function()
• Print ("Hello from a function calling")
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.
• The following example has a function with one argument (fname).
When the function is called, we pass along a first name, which is
used inside the function to print the full name:
• Example
def my_function(fname):
print(fname + " Refsnes")

my_function(“kubwimana")
my_function(“Tuyisenge")
my_function(“Dusenge")
This function expects 2 arguments, and gets
2 arguments:
• def my_function(fname, lname):
• print(fname + " " + lname)

• my_function(“kubwimana", “jean")
This function expects 2 arguments, but gets only 1: you
get error message
• def my_function(fname, lname):
print(fname + " " + lname)

my_function(“david")
If the number of arguments is unknown,
add a * before the parameter name:
If the number of arguments is unknown, add
a * before the parameter name:
• def my_function(*names):
• print("The youngest child is " + names[0])
• my_function("Emil", "Tobias", "Linus","sam")
Python Library Functions

• In Python, standard library functions are the built-in


functions that can be used directly in our program.
For example,
• print() - prints the string inside the quotation marks
• sqrt() - returns the square root of a number
• pow() - returns the power of a number
• These library functions are defined inside the module.
And, to use them we must include the module inside
our program.
• For example, sqrt() is defined inside the math module.
Example 4: Python Library Function
import math
# sqrt computes the square root
square_root = math.sqrt(25)
print("Square Root of 25 is",square_root)
# pow() comptes the power i.e. 23
power = pow(2, 3)
print("2 to the power 3 is",power)
• Output
Square Root of 25 is 5.0
2to the power 3 is 8
Ctn,
# function that adds two numbers
def add_numbers(num1, num2):
sum = num1 + num2
return sum

# calling function with two values


result = add_numbers(5, 4)
print('Sum: ', result)

# function that adds two numbers

def multiplyNum(num1):
return num1 * 8
result = multiplyNum(8)
print(result)
Python flow controls
• control flow is the order in which the program’s code
executes.
• The control flow of a Python program is regulated by
conditional statements, loops, and function calls.
• Python has three types of control structures:

Sequential - default mode


Selection - used for decisions and branching
Repetition - used for looping, i.e., repeating a piece of
code multiple times.
1. 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.
• ## This is a Sequential statement
a=20
b=10
c=a-b
print("Subtraction is : “,c)
Selection/Decision control statements
• The selection statement allows a program to
test several conditions and execute
instructions based on which condition is true.
• Some Decision Control Statements are:
• Simple if
• if-else
• nested if
• if-elif-else
Simple if
• Simple if: If statements are control flow
statements that help us to run a particular
code, but only when a certain condition is met
or satisfied. A simple if only has one condition
to check.
• example
• n = 10
• if n % 2 == 0:
• print("n is an even number")
if-else:
• The if-else statement evaluates the condition and will
execute the body of if if the test condition is True, but
if the condition is False, then the body of else is
executed.
• Example:
n=5
if n % 2 == 0:
print("n is even")
else:
print("n is odd")
Nested if:
• nested if: Nested if statements are an if statement inside another if statement.
• a=5
• b = 10
• c = 15
• if a > b:
• if a > c:
• print("a value is big")
• else:
• print("c value is big")
• elif b > c:
• print("b value is big")
• else:
• print("c is big")
(swicth) or if-elif-else:
• if-elif-else: The if-elif-else statement is used to
conditionally execute a statement or a block of statements.
• x = 15
• y = 112
• if x == y:
• print("Both are Equal")
• elif x > y:
• print("x is greater than y")
• else:
• print("x is smaller than y")
Implement Switch Statements with
the match and case Keywords in

• To write switch statements with the structural pattern


matching feature, you can use the syntax below:
• match term:
• case pattern-1:
• action-1
• case pattern-2:
• action-2
• case pattern-3:
• action-3 case _:
• action-default
It is a program that prints what you can become when
you learn various programming languages:
• lang = input("What's the programming language you want to learn? ")

• match lang:
• case "JavaScript":
• print("You can become a web developer.")

• case "Python":
• print("You can become a Data Scientist")

• case "PHP":
• print("You can become a backend developer")

• case "Solidity":
• print("You can become a Blockchain developer")

• case "Java":
• print("You can become a mobile app developer")
• case _:
• print("The language doesn't matter, what matters is solving problems.")
Python loops
What Are Python Loops?
• loop is a sequence of instruction s that is
continually repeated until a certain condition
is reached.
• In Python, statements are executed in a
sequential manner i.e. if our code is made up
of several lines of code, then execution will
start at the first line, followed by the second,
and so on.
Sr.No. Name of the loop Loop Type & Description

1 While loop Repeats a statement or group of statements while a given


condition is TRUE. It tests the condition before executing
the loop body.

It will keep executing the desired set of code statements


until that condition is no longer True.

2 For loop This type of loop executes a code


block multiple times and
abbreviates the code that
manages the loop variable.

3 Nested We can iterate a loop inside


loops another loop.
Given below is a flowchart that illustrates
how a loop statement works.
Python Loop Control Statements
• Loop control statements are used to change
the flow of execution. These can be used if
you wish to skip an iteration or stop the
execution. The three types of loop control
statements in python are break statement,
continue statement, and pass
While Loops

• The Python while loop iteration of a code block is executed as


long as the given condition, i.e., conditional_expression, is
true.
• The while loop statement repeatedly executes a code block
while a particular condition is true
• If we don't know how many times we'll execute the iteration
ahead of time, we can write an indefinite loop(endless loop).
• Syntax of Python While Loop
• while conditional_expression:
• Code block of while
It first checks the condition, executes the conditional code if it is TRUE, and checks
the condition again. Program control exits the loop if the condition is FALSE.
Example 1: Print the text “Hello, World!” 5 times.
• count = 1
• # condition: Run loop till count is less than 10
• while count < 10:
• print(count)
• count = count + 1
In this example, we want a user to enter any number
between 100 and 500. We will keep asking the user to
enter a correct input until he/she enters the number
within a given range

• number = int(input('Enter any number between 100 and 500 '))


# number greater than 100 and less than 500
while number < 100 or number > 500:
print('Incorrect number, Please enter correct number:')
number = int(input('Enter a Number between 100 and 500 '))
else:
print("Given Number is correct", number)
For loop
• A for loop is used for iterating over a sequence
(that is either a list, a tuple, a dictionary, a set, or a
string).
• This is less like the for keyword in other
programming languages, and works more like an
iterator method as found in other object-
orientated programming languages.
• With the for loop we can execute a set of
statements, once for each item in a list, tuple, set
etc.
examples
• Print each fruit in a fruit list:
• fruits = ["apple", “orange", "cherry
", "banana", " Pineapple“]
for x in fruits:
print(x)
The break Statement

• With the break statement we can stop the loop


before it has looped through all the items:
• fruits = ["apple", “orange", "cherry ", "banana", "
Pineapple“]
for x in fruits:
print(x)
if x == "banana":
break
The continue Statement

• With the continue statement we can stop the


current iteration of the loop, and continue with the
next:
• Do not print banana:
• fruits = ["apple", “orange", "cherry ", "banana", "
Pineapple“]
for x in fruits:
if x == "banana":
continue
print(x)
The range() Function
• To loop through a set of code a specified
number of times, we can use
the range() function,
• The range() function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and stops
before a specified number.
Nested loop
• a loop inside a loop is known as a nested loop. The outer loop can
contain more than one inner loop. There is no limitation on the chaining
of loops.
• In the nested loop, the number of iterations will be equal to the number
of iterations in the outer loop multiplied by the iterations in the inner
loop.
• Syntax of using a nested for loop in Python
• # outer for loop
• for element in sequence
• # inner for loop
• for element in sequence:
• body of inner for loop
• body of outer for loop
Star
• rows = 5
• # outer loop
• for i in range(1, rows + 1):
• # inner loop
• for j in range(1, i + 1):
• print("*", end=" ")
• print('')
Example 2

• Example 2: Printing multiplication table using Python nested for loops

• # Running outer loop from 2 to 3


• for i in range(2, 4):
• # Printing inside the outer loop
• # Running inner loop from 1 to 10
• for j in range(1, 11):

• # Printing inside the inner loop
• print(i, "*", j, "=", i*j)
• # Printing inside the outer loop
• print()
The functions in Python that allow you to
read and write to files:
• read() : This function reads the entire file and returns a string
• readline() : This function reads lines from that file and returns as a
string. It fetch the line n, if it is been called nth time.
• readlines() : This function returns a list where each element is single
line of that file.
• readlines() : This function returns a list where each element is single
line of that file.
• write() : This function writes a fixed sequence of characters to a file.
• writelines() : This function writes a list of string.
• append() : This function append string to the file instead of
overwriting the file
Description of files(create file)
• Create a New File
• To create a new file in Python, use the open() method, with one of the following
parameters:
• Syntax of Python open file function
• file_object = open("filename", "mode")Here,
• filename: gives name of the file that the file object has opened.
• mode: attribute of a file object tells you which mode a file was opened in.
• "x" - Create - will create a file, returns an error if the file exist
• "a" - Append - will create a file if the specified file does not exist
• "w" - Write - will create a file if the specified file does not exist
• Create a file called "myfile.txt":
• f = open("myfile.txt", "x")
• Create a new file if it does not exist:
• f = open("myfile.txt", "w")
CTN,
• Example
• Open the file "demofile2.txt" and append content to the file:
• f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())
CTN,
• To read a text file in Python, load the file by using
the open() function:
f = open("<file name>")
• The mode defaults to read text ('rt'). Therefore, the
following method is equivalent to the default:
• f = open("<file name>", "rt")
• Add + to open a file in read and write mode:
• f = open("<file name>", "r+") # Textual read and
writef = open("<file name>", "rt+") # Same as above
Write Mode
• Write mode creates a file for writing content and places the pointer at the start. If
the file exists, write truncates (clears) any existing information.
Warning: Write mode deletes existing content immediately. Check if a file exists
before overwriting information by accident.
• To open a file for writing information, use:
• f = open("<file name>", "w")
• The default mode is text, so the following line is equivalent to the default:
• f = open("<file name>", "wt")
• To write in binary mode, open the file with:
• f = open("<file name>", "wb")
• Add + to allow reading the file:
• f = open("<file name>", "w+") # Textual write and read
• f = open("<file name>", "wt+") # Same as above
• f = open("<file name>", "wb+") # Binary write and read
Append Mode
Append mode adds information to an existing file,
placing the pointer at the end. If a file does not exist,
append mode creates the file.
• Use one of the following lines to open a file in
append mode:
• f = open("<file name>", "a") # Text append
• f = open("<file name>", "at") # Same as above
• f = open("<file name>", "ab") # Binary append
Python Delete File

• You can delete files using the Python os.remove(),


os.rmdir(), and shutil.rmtree() method. These
methods remove a file, a directory, and a folder with
all of its files, respectively.
• How to Delete a File in Python Using os.remove()
• The Python os.remove() method deletes a file from
your operating system. os.remove() only deletes a
single file. It cannot delete a directory.
• To delete a file, you must import the OS module, and
run its os.remove() function:
EXAMPLE
• Remove the file "demofile.txt":
• import os
os.remove("demofile.txt")
• Check if File exist:
• To avoid getting an error, you might want to check if the
file exists before you try to delete it:
• import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist try again")
Rename File in Python
• Python rename() file is a method used to rename a file or a directory
in Python programming. The Python rename() file method can be
declared by passing two arguments named src (Source) and dst
(Destination).
• The path is the location of the file on the disk.
An absolute path contains the complete directory list required to
locate the file.
A relative path contains the current directory and then the file name.
• Decide a new nameSave an old name and a new name in two separate
variables.
old_name = 'details.txt'
new_name = 'new_details.txt'
• Use rename() method of an OS moduleUse the os.rename() method
to rename a file in a folder. Pass both the old name and a new name to
the os.rename(old_name, new_name) function to rename a file.
Delete Folder
• To delete an entire folder, use the os.rmdir() method:
• Remove the folder "myfolder":
• Import os
os.rmdir("myfolder")

You might also like