Python Thops
Python Thops
PYTHON
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
Java Program
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.
Sample Program
1. a = 10
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
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.
Output :
Example
x = 15 + 1.3
Operators
The operator is a symbol that performs a certain operation between
two operands.
1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
:
5. Bitwise Operators
6. Special Operators
Arithmetic Operators
Sample Program
Comparison Operators
Logical Operators
Sample Program
Assignment Operators
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.
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.
As we can see new_number has value 124.23 and is of the float 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.
num_string = int(num_string)
Finally, we got the num_sum value i.e 35 and data type to be int.
=================================================
======
Programming Exercise
Sample value of n is 5
Sample value of n is 20
Expected Result : 6
Sample value of n is 5
Expected Result : 12
Sample value of n is 5
Control Statements
In Python, control flow starts from first line & eventually transfers line
by line.
The if statement
:
The if-else statement
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.
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:
Parameter :=
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
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.
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
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.
Dictionary
A Dictionary holds key:value pair. Key:Value is provided in the
dictionary to make it more optimized.
Functions
A collection of related assertions that carry out a mathematical,
analytical, or evaluative operation is known as a function.
Functions:
· Advantage :
Syn:
1. Predefined functions
:
2. User defined functions
Pre-defined functions:
User-defined functions:
The functions which are defined by the user (programmer) are called
user-defined functions.
1. Function definition
2. Function calling
Function calling:
· 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.
Return:
· 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.
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:
Syn:
map(fun, iter)
Further the map object can be converted to list, tuple etc by suing
list() , tuple() constructors etc.
Fibonacci series:
:
LAMBDA:
Filter:
Syn:
Here fun means the function that tests each element of a sequence
is true or not.
Lambda:
:
· Lambda is a special type of function which is a anonymous
(nameless) single line function.
Modules:
Components in module:
Res= Arith.add(4,6)
print(Res)
print(Arith.a)
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
Advantages:
· It helps you to break down the big problems into smaller ones.
Dis-Advantages:
· It is challenging to debug.
NESTED LISTS:
:
List comprehensions:
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:
1. Input:
2. Function Call:
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.
: