0% found this document useful (0 votes)
18 views

Python Thops

Uploaded by

Siva Krishna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Python Thops

Uploaded by

Siva Krishna
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

PYTHON_THOPS

PYTHON

Python is a popular general-purpose programming language.


Python is a simple, general purpose, high level, powerful and very
popular programming language.
Guido Van Rossum is known as the founder of Python programming.
(1991)
Python is simple and easy to learn and provides lots of high-level
data structures.
Python programming language (latest Python 3) is being used in
web development, Machine Learning applications, along with all
cutting-edge technology in Software Industry.
Python language is being used by almost all tech-giant companies
like – Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc.

The biggest strength of Python is huge collection of standard


library which can be used for the following:

Machine Learning
Artificial Intelligence
Data Science
GUI Applications (like Kivy, Tkinter, PyQt etc. )
Web frameworks like Django (used by YouTube, Instagram, Dropbox)
Image processing (like OpenCV, Pillow)
Web scraping (like Scrapy, BeautifulSoup, Selenium)
Test frameworks
Multimedia
Scientific computing
Computer Vision or Image Processing Applications.
Text processing and many more..
:
Desktop & Mobile Applications
Web Applications

Why Learn Python?

Easy to use and Learn


Expressive Language
Interpreted Language
Object-Oriented Language
Open Source Language
Extensible
Integrated
Embeddable
Dynamic Memory Allocation

Java vs Python Program

Unlike the other programming languages, Python provides the


facility to execute the code using few lines. For example - Suppose
we want to print the "Hello World" program in Java; it will take three
lines to print it.

Java Program

1. public class HelloWorld


2. {
3. public static void main(String[] args)
4. {
5. System.out.println("Hello World");
6. }
7. }

Python Program
:
On the other hand, we can do this using one statement in Python.

print("Hello World")

Both programs will print the same result, but it takes only one
statement without using a semicolon or curly braces in Python.

Python print() Function


Here, The print() function displays the given object to the standard
output device (screen) or to the text stream file.

Unlike the other programming languages, Python print() function is


most unique and versatile function.

The syntax of print() function is given below.

· print(*objects, sep=” “, end='\n')

Let's explain its parameters one by one.

objects - An object is nothing but a statement that to be printed. The


* sign represents that there can be multiple statements.
sep - The sep parameter separates the print values. Default values is
“ “.
end - The end is printed at last in the statement. Default values is
“\n“.

Sample Program

1. a = 10

2. print("a =", a) # Two objects are passed in print() function

O/p :- a = 10
:
==================================================
============

Identifiers
Python Identifier is the name we give to a variable, function, class,
module or other object to identify it during the execution of the
program.
That means whenever we want to give an entity a name, that's called
identifier.
Sometimes variable and identifier are often misunderstood as same
but they are not.

Python Variable
Variable is a name that is used to refer to memory location. Python
variable is also known as an identifier and used to hold value.
Python Variable is a container that stores values.
Python is “dynamically typed” language. Unlike other programming
languages, We do not need to declare variables before using them or
declare their type.
Python has no command for declaring a variable.
A variable is created the moment we first assign a value to it. This
means that when you create a variable you reserve some space in
the memory.
The equal sign (=) is used to assign values to variables.

Example
x=4 # x is of type int

x = "Sally" # x is now of type str


:
print(x)

Note :
An Example of a Variable in Python is a representational name that
serves as a pointer to an object. Once an object is assigned to a
variable, it can be referred to by that name.
The value stored in a variable can be changed during program
execution.
A Variables in Python is only a name given to a memory location, all
the operations done on the variable effects that memory location.

# valid variable name


thops = 1
Thops = 2
Th_o_ps = 5
_thops = 6
thops_ = 7
_THOPS_ = 8
print(thops, Thops, Th_o_ps)
:
print(_thops, thops_, _THOPS_)
Output:
125
678
Keywords
Keywords are reserved words that have special meaning to the
Python Interpreter.
Keywords can not be used as a variable name, function name, or any
other identifier.
Keywords reserved with defined meanings and functions that we can
only apply for those functions.
You'll never need to import any keyword into your program because
they're permanently present.

Here's a list of all keywords in Python Programming

The above keywords may get altered in different versions of Python.


Some extra might get added or some might be removed. You can
always get the list of keywords in your current version by typing the
following in the prompt.

>>> import keyword


:
>>> print(keyword.kwlist)

Output :

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',


'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

An EXPRESSION is a combination of operators and operands that is


interpreted to produce some other value.

OPERATORS: These are the special symbols. Eg- + , * , /, etc.

OPERAND: It is the value on which the operator is applied.

Example

x = 15 + 1.3

here, = + are operators and x, 15 & 1.3 are operands

Operators
The operator is a symbol that performs a certain operation between
two operands.

Types of Python Operators

Here's a list of different types of Python operators that we will learn


in this tutorial.

1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
:
5. Bitwise Operators
6. Special Operators

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations


like addition, subtraction, multiplication,etc.

Sample Program

Comparison Operators

Comparison operators compare two values/variables and return a


boolean result: True or False.
:
Sample Program

Logical Operators

Logical operators are used to check whether an expression is True or


False. They are used in decision-making.

Sample Program

Assignment Operators

Assignment operators are used to assign values to variables.


:
Sample Program

Special Operators
:
Bitwise Operators

Datatypes
Datatype is a classification that specifies the Python interpreter how
the programmer intends to use the data (what type of value a
variable has and what type of operations can be applied without
causing an error.

Data types specify the different sizes and values that can be stored
in the variable.

Python is “dynamically typed” language. Unlike other programming


languages, We do not need to declare variables before using them or
declare their type.
Python has no command for declaring a variable.
A variable is created the moment we first assign a value to it. This
means that when you create a variable you reserve some space in
:
the memory.
The equal sign (=) is used to assign values to variables.

Type Casting
The conversion of one data type into the other data type is known as
type casting in python or type conversion in python.

There may be times when you want to specify a type on to a variable.


This can be done with casting. Python is an object-orientated
language, and as such it uses classes to define data types, including
its primitive types.

Python supports a wide variety of functions or methods like: int(),


float(), str(), ord(), hex(), oct(), tuple(), set(), list(), dict(), etc. for the
type casting in python.

There are two types of type conversion in Python.

Implicit Conversion - automatic type conversion


Explicit Conversion - manual type conversion

Python Implicit Type Conversion

Python automatically converts one data type to another. This is


known as implicit type conversion.
:
Example 1: Converting integer to float

Let's see an example where Python promotes the conversion of the


lower data type (integer) to the higher data type (float) to avoid data
loss.

In the above example, we have created two variables:


integer_number and float_number of int and float type respectively.

Then we added these two variables and stored the result in


new_number.

As we can see new_number has value 124.23 and is of the float data
type.

It is because Python always converts smaller data types to larger


data types to avoid the loss of data.

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object


to required data type.

We use the built-in functions like int(), float(), str(), etc to perform
explicit type conversion.
:
This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.

Example 2: Addition of string and integer Using Explicit Conversion

In the above example, we have created two variables: num_string


and num_integer with str and int type values respectively. Notice the
code,

num_string = int(num_string)

Here, we have used int() to perform explicit type conversion of


num_string to integer type.

After converting num_string to an integer value, Python is able to


add these two variables.

Finally, we got the num_sum value i.e 35 and data type to be int.

In Type Casting, loss of data may occur as we enforce the object to a


specific data type.

=================================================
======

Programming Exercise

Write a Python program that accepts an integer (n) and computes


the value of n+nn+nnn.

Sample value of n is 5

Expected Result : 615


:
Write a Python program to calculate the difference between a given
number and 17. If the number is greater than 17, return twice the
absolute difference.

Sample value of n is 20

Expected Result : 6

Sample value of n is 5

Expected Result : 12

Write a Python program to calculate the area of Square

Sample value of side is 10

Expected Result : The area of square with side 10 cm is 100 cm2

Sample value of n is 5

Expected Result : The area of square with side 6 cm is 36 cm2

Write a Python program to calculate the area of Rectangle

Sample values of length & width are 20 & 10

Expected Result : The area of rectangle with length 20 cm and width


10 cm is 200 cm2
:
Sample values of length & width are 10 & 5

Expected Result : The area of rectangle with length 10 cm and width


5 cm is 50 cm2

Write a Python program to find greatest among two numbers


Write a Python program to find greatest among three numbers
Write a Python program to find second greatest among three
numbers

Control Statements
In Python, control flow starts from first line & eventually transfers line
by line.

Control statements are used to control the flow of execution of the


program. They allow you to execute different parts of the program
based on certain conditions.

There are three main types of control statements in Python:

Decision Making statements: allow you to execute a block of code


only if a certain condition is true.

The conditional statements (also known as decision control


structures) such as if, if else, switch, etc.

Decision-Making Statements are used to evaluate one or more


conditions and make the decision whether to execute a set of
statements or not.

The type of control flow statements is as follows:

The if statement
:
The if-else statement

The nested-if statement


:
The if-elif-else ladder

Loops: allow you to execute a block of code repeatedly, usually until


a certain condition is met.

Loops are classified into two types

1. Conditional Loop
:
Loop is a mechanism that executes same set of statements until a
specific condition is met.

2. Traversal Loop
Traversing in Data Structure means systematically visiting every
element of given Sequence. Accessing an element of data structure
means visiting every element at least once.

A "For" Loop is used to repeat a specific block of code a known


number of times.
:
Jump statements: allow you to execute a different block of code
based on the value of a variable.

Continue
Python Continue statement is a loop control statement that forces to
execute the next iteration of the loop while skipping the rest of the
code inside the loop for the current iteration only, i.e. when the
continue statement is executed in the loop, the code inside the loop
following the continue statement will be skipped for the current
iteration and the next iteration of the loop will begin.

a
:
Break
break statement is put inside the loop body (generally after if
condition). It terminates the current loop, i.e., the loop in which it
appears, and resumes execution at the next statement immediately
after the end of that loop. If the break statement is inside a nested
loop, the break will terminate the innermost loop.
:
range()
The Python range() function returns a sequence of numbers, in a
given range. The most common use of it is to iterate sequences on a
sequence of numbers using Python loops.

Syntax:

range(start, stop, step)

Parameter :=

start: [ optional ] start value of the sequence ( default value : 0 )

stop: next value after the end value of the sequence

step: [ optional ] integer value, denoting the difference between any


two numbers in the sequence ( default value : 1)

Return : Returns an object that represents a sequence of numbers

Nested Loop
A nested loop is a loop inside another loop. Although all kinds of
loops can be nested, the most common nested loop involves for
loops. These loops are particularly useful when displaying
multidimensional data. When using these loops, the first iteration of
the first loop will initialize, followed by the second loop.
:
PATTERNS

Pattern programs are patterns/designs/symbols consisting of


numbers, alphabets or symbols in a particular form. These kinds of
pattern are solved using looping structures.
:
:
Strings
A String is a data structure in Python that represents a sequence of
characters surrounded by single quotes, double quotes, or triple
quotes.

The computer does not understand the characters; internally, it


stores manipulated character as the combination of the 0's and 1's.

Each character is encoded in the ASCII or Unicode character. So we


can say that Python strings are also called the collection of Unicode
characters.

Assigning a string to a variable is done with the variable name


followed by an equal sign and the string:

You can display a string literal with the print() function


:
We can access the characters in a string in three ways.

1. Indexing: One way is to treat strings as a list and use index


values. For example,

2. Negative Indexing: Similar to a list, Python allows negative


indexing for its strings. For example,

3. Slicing: Access a range of characters in a string by using the


slicing operator colon :. For example,

String is an immutable data type, meaning that once you have


created a string, you cannot change it.

Strings are used widely in many different applications, such as


storing and manipulating text data, representing names, addresses,
and other types of data that can be represented as text.
:
Note: All string methods return new values. They do not change the
original string.

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
Returns the number of times a specified value occurs in a
count()
string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
Searches the string for a specified value and returns the
find()
position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
Searches the string for a specified value and returns the
index()
position of where it was found
Returns True if all characters in the string are
isalnum()
alphanumeric
Returns True if all characters in the string are in the
isalpha()
alphabet
Returns True if all characters in the string are ascii
isascii()
characters
isdecimal() Returns True if all characters in the string are decimals
:
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
Returns True if all characters in the string are
isspace()
whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
Returns a string where a specified value is replaced with
replace()
a specified value
Searches the string for a specified value and returns the
rfind()
last position of where it was found
Searches the string for a specified value and returns the
rindex()
last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
Splits the string at the specified separator, and returns a
rsplit()
list
rstrip() Returns a right trim version of the string
Splits the string at the specified separator, and returns a
split()
list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
:
strip() Returns a trimmed version of the string
Swaps cases, lower case becomes upper case and vice
swapcase()
versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
Fills the string with a specified number of 0 values at the
zfill()
beginning

List
A list (built-in datatype/data structure) is a collection of different
kinds of values or items.

Lists are just like dynamically sized arrays, declared in other


languages (vector in C++ and ArrayList in Java).

Since Python lists are mutable, we can change their elements after
forming. The comma (,) and the square brackets [enclose the List's
:
items] serve as separators.

List Declaration

Accessing elements from List

Accessing elements from 2D List

The characteristics of the List are as follows:

The lists are in order.

The list element can be accessed via the index.

The mutable type of List is

The rundowns are changeable sorts.

The number of various elements can be stored in a list.

The indexing procedure is carried out similarly to string processing.


The slice operator [] can be used to get to the List's components.

List Indexing and Slicing

The index ranges from 0 to length -1. The 0th index is where the
List's first element is stored; the 1st index is where the second
element is stored, and so on.
:
Python lets you use negative indexing as well. The negative indices
are counted from the right. The index -1 represents the final element
on the List's right side, followed by the index -2 for the next member
on the left, and so on, until the last element on the left is reached.

List Methods in Python


S.no Method Description
Used for appending and adding elements to the end of
1 append()
the List.
2 copy() It returns a shallow copy of a list
This method is used for removing all items from the
3 clear()
list.
4 count() These methods count the elements
5 extend() Adds each element of the iterable to the end of the List
6 index() Returns the lowest index where the element appears.
7 insert() Inserts a given element at a given index in a list.
Removes and returns the last value from the List or the
:
8 pop() given index value.

9 remove() Removes a given object from the List.


10 reverse() Reverses objects of the List in place.
Sort a List in ascending, descending, or user-defined
11 sort()
order
12 min() Calculates the minimum of all the elements of the List
13 max() Calculates the maximum of all the elements of the List

Dictionary
A Dictionary holds key:value pair. Key:Value is provided in the
dictionary to make it more optimized.

A dictionary is a collection which is ordered*, changeable and do not


allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and


earlier, dictionaries are unordered.

Dictionaries are written with curly brackets ({}), including key-value


pairs separated by commas (,).

Table of Python Dictionary Methods


Functions
:
Name Descriptions

clear() Removes all items from the dictionary


copy() Returns a shallow copy of the dictionary
fromkeys() Creates a dictionary from the given sequence
get() Returns the value for the given key
items() Return the list with all dictionary keys with values
Returns a view object that displays a list of all the keys in
keys()
the dictionary in order of insertion
pop() Returns and removes the element with the given key
popitem() Returns and removes the key-value pair from the dictionary
Returns the value of a key if the key is in the dictionary else
setdefault()
inserts the key with a value to the dictionary
Updates the dictionary with the elements from another
values()
dictionary
update() Returns a list of all the values available in a given dictionary

Functions
A collection of related assertions that carry out a mathematical,
analytical, or evaluative operation is known as a function.

Functions:

· A python function is a block of code or a set of statements


that performs a specific task.
:
· The block of code is assigned with a unique identifier (name).
It acts as a reference variable.

· The data is to put commonly repeatedly done tasks together


and make a function . So that, instead of writing the code again and
again for different inputs we can use the function call to reuse the
code over and over again.

· “def” key word is used to create a function.

· Advantage :

1. The main advantage of function is reusability

2. Less lines of code

3. Easy to debug or modify

Syn:

def function_name (parameters): àheader/ declaration

key word Function signature

# all statements ----------à body of the


function/implementation

return expression ----------àfunction return

Functions are classified into 2 types:

1. Predefined functions
:
2. User defined functions

Pre-defined functions:

These are some standard functions already defined in python that


are available to use.

There are many modules in python that provides built in functions.

EX: len(), sum(), sorted(), reversed(), min(), max()

User-defined functions:

The functions which are defined by the user (programmer) are called
user-defined functions.

We can add any type of personality or properties to a function as we


required.

There ae 2 steps in functions:

1. Function definition

2. Function calling

Function calling:

· The control goes to the function if we call the function manually


by using the name of the function followed by paranthesis ()
containing parameters.

· The values which are passed in the function call are called actual
parameters.
:
· The values which are assigned to variables in the function
definition are called formal parameters.

Note: A function can return a data as a result.

· When the function is called, the control of the program goes to


the function definition.

· All codes in function are executed.

· After execution of function the control of the program jumps to


the next statements after the function call.

· A function is defined once and can be called many times.

Return:

Transfer control to the called statement.


:
:
Local variable:

· The variables that are declared inside the functions are called
local variables. It is defined within a local scope

· We can access a local variable inside the function but not from
out side

Global Variable:
:
· The variables that are created outside the function are called
global variables.

· A global variable can be accessed from any part of the


program including within functions.

· If there a local variable as well as global variable with the same


name

1)accessing variable inside the function gives the local variable

2)accessing variable outside the function gives the global variable


value.

3)local variables are not accessible from main code or other


functions.

· We can declare a global variable inside a function by using the


key word “GLOBAL”.

Programs for home work by using functions :

1. Even

2. Perfect

3. Palindrome

4. Armstrong

5. Strong/special

6. Fibonacci series
:
***** Sum of individual digits of every element in the list
:
**** Printing even numbers in the given list

Map:

Map function works as an iterator and returns a result after applying


the function to every element of the given iterable (sequence).

Syn:

map(fun, iter)

parameters 1) fun--- it is the function to which map passes each


element of given iterable.

2) iter: it is iterable which is to be mapped


:
Note: map function returns the map object as a result.

Further the map object can be converted to list, tuple etc by suing
list() , tuple() constructors etc.

Fibonacci series (not recommended):

Fibonacci series:
:
LAMBDA:

Filter:

The filter method filters the given sequence (blocks unwanted


elements and allows wanted elements) with the help of a function
that tests each element in the sequence to be true or not.

Syn:

Filter (fun, iter)

Here fun means the function that tests each element of a sequence
is true or not.

Iter: it is the sequence which needs to be filtered

The filter function returns an iterator that is already filtered.

Lambda:
:
· Lambda is a special type of function which is a anonymous
(nameless) single line function.

· In functions we use def key word to define a function similarly


we use lambda key word to define a lambda function.

· Lambda function can take any number of parameters


(separated by comma) but can have only one expression which is
evaluated and return by default.

Syn: lambda arguments : expression

Lambda arg_1, arg_2,…… arg_n : expression

Modules:

· In python modules are simply files with “.py” extension


containing python code that can be imported inside another python
program

· We can consider a module to be the same as a code library or


a file that contains a set of functions that you want to include in your
python application.

· So. It is considered a best production level projects in data


science is to split large python code blocks into modules containing
upto 300-400 lines of code.

Components in module:

· Definitions and implementation of classes variables.

· Function that can be used inside another program .


:
· The file ends with “.py” is called a module file.

· By using “import” key word we can import the module


:
· If we are importing total module we need to mention the
module name for accessing a function or a variable or a class.

Ex: import Arith

Res= Arith.add(4,6)

print(Res)

print(Arith.a)

· If we are importing particular method or by using * we need


not to mention module name.

Ex: import Arith *

Res= add(4,6)

print(Res)

print(a)
:
Ex: import Arith add, sub

Res= add(4,6)

print(Res)

print(a)

O/P: 5 4 3 2 1 0 -1 -2 -3..........
:
*** WAP to print factors of n in reverse order using recursion
:
**** Fibonacci series using recursion

**** sum of natural numbers using recursions

****count of digits of a given number


:
***sum of digits of a given number

*** factorial of a given number

****power of any number using recursion


:
*****count of factors of a given number using recursion

****Sum of factors of a given number

*****Prime another logic


:
*****Prime number using recursion and while else

****perfect number using recursion


:
A function calling itself is called a recursive function and this process
is called recursion.

Advantages:

· It looks simple and effective.

· Reduces unnecessary calling of function.

· It helps you to break down the big problems into smaller ones.

· The main advantage of recursion is very useful in solving the


data structure problem and it reduces the length of code.

Dis-Advantages:

· It is challenging to debug.

· Recursive functions are slower than non-recursive function.

· It is less efficient in terms of space and time complexity.

NESTED LISTS:
:
List comprehensions:

**without using map

***Without using filter:

Python Exceptions List


:
Here is the complete list of Python in-built exceptions.

Name of the
Sr.No. Description of the Exception
Exception
All exceptions of Python have a base
1 Exception
class.
If the next() method returns null for an
2 StopIteration
iterator, this exception is raised.
The sys.exit() procedure raises this
3 SystemExit
value.
Excluding the StopIteration and
4 StandardError SystemExit, this is the base class for all
Python built-in exceptions.
All mathematical computation errors
5 ArithmeticError
belong to this base class.
This exception is raised when a
6 OverflowError computation surpasses the numeric data
type's maximum limit.
If a floating-point operation fails, this
7 FloatingPointError
exception is raised.
For all numeric data types, its value is
8 ZeroDivisionError raised whenever a number is attempted
to be divided by zero.
If the Assert statement fails, this
9 AssertionError
exception is raised.
This exception is raised if a variable
10 AttributeError
reference or assigning a value fails.
When the endpoint of the file is
approached, and the interpreter didn't
11 EOFError get any input value by raw_input() or
input() functions, this exception is
raised.
This exception is raised if using the
12 ImportError
import keyword to import a module fails.
If the user interrupts the execution of a
:
13 KeyboardInterrupt program, generally by hitting Ctrl+C, this
exception is raised.
LookupErrorBase is the base class for all
14 LookupError
search errors.
This exception is raised when the index
15 IndexError
attempted to be accessed is not found.
When the given key is not found in the
16 KeyError dictionary to be found in, this exception
is raised.
This exception is raised when a variable
17 NameError isn't located in either local or global
namespace.
This exception is raised when we try to
access a local variable inside a function,
18 UnboundLocalError
and the variable has not been assigned
any value.
All exceptions that arise beyond the
19 EnvironmentError Python environment have this base
class.
If an input or output action fails, like
when using the print command or the
20 IOError
open() function to access a file that does
not exist, this exception is raised.
This exception is raised whenever a
22 SyntaxError
syntax error occurs in our program.
This exception was raised when we
23 IndentationError
made an improper indentation.
This exception is raised when the
sys.exit() method is used to terminate
24 SystemExit the Python interpreter. The parser exits if
the situation is not addressed within the
code.
This exception is raised whenever a data
25 TypeError type-incompatible action or function is
tried to be executed.
This exception is raised if the parameters
:
for a built-in method for a particular data
26 ValueError
type are of the correct type but have
been given the wrong values.
This exception is raised when an error
27 RuntimeError that occurred during the program's
execution cannot be classified.
If an abstract function that the user must
28 NotImplementedError define in an inherited class is not
defined, this exception is raised.

Certainly, let's break down the Python code you provided step by
step.

Core Functions:

factorial(r: int) -> int

This function calculates the factorial of a given integer r.


It initializes a variable fact to 1.
Then, it iterates from 1 to r (inclusive), multiplying fact by each
number in the range.
Finally, it returns the calculated factorial fact.
:
isStrong(n: int) -> bool

This function checks if a given number n is a strong number.


A strong number is one where the sum of the factorials of its digits
equals the original number itself.
It stores the original number in temp.
It initializes a sum variable to 0.
It enters a while loop that continues as long as n is greater than 0.
Inside the loop:

It extracts the last digit of n using r = n % 10.


It removes the last digit from n using n = n // 10.
It calculates the factorial of the extracted digit r and adds it to sum.

After the loop, it compares if sum is equal to the original number


temp.
It returns True if they are equal (indicating a strong number) and
False otherwise.

strong_numbers(arr: list) -> None

This function takes a list of numbers arr as input.


It iterates through each element ele in the list.
For each ele, it calls the isStrong function to check if it's a strong
number.
If isStrong(ele) returns True, it prints the element ele without a
newline (using end="").

Main Code Execution:

1. Input:

It reads an integer ln from the user, representing the length of the


input list.
:
It reads a space-separated string of numbers from the user and
stores it in arr.
It converts each element in arr from a string to an integer.

2. Function Call:

It calls the strong_numbers(arr) function to process the input list and


print any strong numbers found within it.

In essence:

The code identifies and prints strong numbers from a given list of
integers. It leverages the factorial function to calculate factorials of
digits and the isStrong function to determine if a number is strong.
:

You might also like