0% found this document useful (0 votes)
11 views59 pages

Allunits

The document provides an introduction to Python programming, covering its features, installation procedures, and basic concepts such as variables, functions, and control structures. It outlines the Python shell, integrated development environments (IDEs), and common operators, along with examples of conditional statements and functions. Additionally, it discusses user-defined functions, recursion, and the scope of variables in Python.

Uploaded by

21varsha.shri.m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views59 pages

Allunits

The document provides an introduction to Python programming, covering its features, installation procedures, and basic concepts such as variables, functions, and control structures. It outlines the Python shell, integrated development environments (IDEs), and common operators, along with examples of conditional statements and functions. Additionally, it discusses user-defined functions, recursion, and the scope of variables in Python.

Uploaded by

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

Python Programming — AIML Branch

UNIT 1: Introduction to Python

Agenda

● Features of Python
● Python Installation Procedure
● Python Shell
● IDE
● Variables
● Common Functions with Numbers
● Logical Operators
● Strings and Printing
Introduction
● Python was released under a GPL-compatible license (combining with others).
● Python Software Foundation (PSF) holds copyright of Python. ● Guido
Van Rossum was inventor.
● Python was released at Centrum Wiskunde and Informatica (CWI) in
Netherlands as a successor of ABC Lang.
● Python was named after a popular comedy show called “Monty Python’s
Flying Circus” — not by Python snake…
Features of Python

● Python is a High-level object-oriented programming lang.


● Easy-to-use open source Lang.
● Interpreter-based Lang.
● Has large in-built std libraries and supports multiple paradigms such as:
○ Event-driven
○ Functional Programming
○ Object-oriented
○ Database applications
○ Web-based programming
○ Data science
● It is Extensible Lang.
● It is Platform independent Lang.
● It borrows most of constructs from a variety of other langs.
Python Installation Procedure
(Can be done in Windows, Linux, MacOS, IBM AS/400, iOS, Solaris…etc)

(Windows):

1. Go to “https://www.python.org/downloads”.—------ To download installer


2. Click o “Download”.------- To get “.exe” file
3. Start Installation:
a. Check “Add Python 3.11 to PATH”. —----- To execute script from any path
b. Click “Customize Installation”.--------To choose installation folder or features
i. Click “Next”.—----- To allow default settings in that screen
ii. Check “Add Install for all Users”.--------Allow any users of local machine to execute
iii. Make shorter path—---e.g. C:\python311
iv. Click “Install”.
To check:
1. Go to “Command Prompt” in menu.
2. Enter “python”.
Need to get “>>>” if successfully installed.

(Ubuntu):------present by default
To check its default presence:
1. Go to “Terminal”.
2. Type “$which python3”.
Need to get “Path” if successfully installed.
--------------e.g. “/usr/local/bin/python3”
Ubuntu OS
Terminal
To check by default
If Absent:
1. Go to “Terminal”.
2. Type “$sudo apt-get update”.
3. Type “$sudo apt-get install python 3.8”.

To check:
1. Go to “Terminal”.
2. Type “python”.
Need to get “>>>” if successfully installed.
Python Shell

● Also called Python Interactive Shell.


● It is used to execute a single python command.
● It works by waiting the command from user and display the results by
executing asa it receive the command.

To open (Windows):
1. Go to “Command Prompt” in menu.
2. Enter “python”.
If this appears “>>>” then shell activated.
IDE — Integrated Development Environment
(IDLE, Jupyter Notebook, Atom, Thonny, Pycharm, ….)

● IDE is an editor that allows to write, test, and debug the code in easy way.
● Basic TEXT editor can be used to edit. But, it fails to support automated
service:
○ Code completion
○ Highlighting code error
○ Resource management
○ …….
● IDE supports along with above three:
○ Language translator
○ Creating binary executables
○ Debugging tools
Variables
● One can define variables, assign values to them, and do algebra.
● Python interpreter returns:

Rules of Identifiers:
● The first character has to be a small or a capital letter or ‘_’ (underscore).
● The characters ‘$’ and ‘?’ cannot be used in an Identifier.
● The Identifier should not begin or end with a pair of underscores. In fact
these are reserved for specific use.
● Keywords needed to be avoided as Identifiers.

Note:
Identifiers are case sensitive; a and A are different variables.
The set of keywords in Python:
Note:
Avoiding their use directly or in combinations is a healthy programming
practice.
Operators in Python: Algebraic operators are listed in order of ascending priorities:
Useful role in
interactive sessions
Common Functions with Numbers

● Python has a number of built-in functions each function accepts the


specified arguments, executes the routines concerned and returns the result
(if and as desired).
● Here we introduce a few of the built-in functions useful directly in the
calculator type of work.
Different

possibilities and constraints of pow() function execution


Note:
int() doesn’t rounding off.
Additional functions are introduced
Basic Operators Priority:

In any algebraic chain ‘**’—if present—will be evaluated first; then ‘%’ and so on. ‘+’
operation is the last one to be carried out.
Note:

Since the division always returns a floating point number the final result (algebra involving a mixture of integers and floating
point numbers) yields a floating number.

Logical Operators
● Operates bit-wise on integers.
Strings and Printing

● A string is a type of ‘object’ in Python.


● Any character sequence can form a string.
● Strings can be useful in taking output as printouts and in presenting any
entity in/from Python.
Note:
In Python the operator ‘+’ is used in the sense of combining two entities but not restricted to mean the addition
of two numbers alone.
Here the white space—‘ ’—a string of single character has been interposed between ‘good’ and ‘day’; the
three strings—s1(‘good’), the white space string ‘ ’, and s2 (‘day’) have been combined using the ‘+’ operator to form the
string s4 (‘good day’).
● Entities in Python (like strings) can be output/displayed by invoking the print()
function.
UNIT 2: Basics Program Structure

Agenda

● Formatted Output
● Control Structure Statements
● Functions
● User Defined functions
● Errors and Exceptions
Formatted Output

● There are several ways to present the output of a program on screen or


written into a file for future use.
● There are several ways to format output that enhance a human-readable
form.
Formatted print():
In Python, the print() function is used to print message or values onto the
screen.

● It accepts an arbitrary number of input objects as arguments (not necessary


same type) and prints a string representation of the object’s value. ● If input
arguments are not a string representation of object’s value, then it evaluate
each expression and convert into string.
Control Structures Statement
● The execution of statements sequentially irrespective of what input value
given by user is called Sequential Execution.
● But, this has high latency, low throughput and do not support concurrency
and interactive with user.
● But, the computer application required interactive with user.

e.g.: Online Bank Application (based on user input from


password)
● Python supports control statements that control flow of program execution.
e.g.:

The program behaves differently based on percentage input…


● Python supports Four types of Conditional/Decision Control Statements:
○ “if” statement
○ “if else” statements
○ “if-elif” ladder
○ nested “if” statement
One-Way Selection Statement: “if” Statement

The if statement is the simplest control statement type among


“if” statements, it also referred as One-Way Selection Statement.

● The general format of one way selection statement is:


○ The if statement contains “if” keyword, followed by condition (Boolean
expression).
○ The end of condition is indicated by colon.
○ The set of statements that are indented with “if” keyword are called “if block”.
Questions: One-Way Selection Statement is often used
e.g.: to restrict block of statements being
interpreted by interpreter, if a condition is not
right.

● If age is greater than 65, print “Pension Benefits is available”.


● If name is in list [“Meena”, “Rahul”, “Venkat”, “Swetha”], print “Students of UVCE!”. ● If
atleast one of the Boolean variables north, south, east, and west is True, print “I can
escape”.
● If person name is virat, print “Virat Kohli is best batsman in the world”.
Two-Way Selection Statement: “if-else” Statement
Most frequently used conditional statement.
● The One-Way Selection Statement perform one action when condition
evaluate to True and it does not perform action when condition evaluate to
False, it just skip statements.
● This statement allows programmer perform two task.
● The general format:
If <condition>:

<Indented instruction of “if” block>


else <condition>:
<Indented instruction of “else”
block>
<non-Indented instruction>
e.g.:

01).
02).
Questions:
● If year is divisible by 4, print “Leap Year!!!...” ; otherwise print “not a Leap Year”. ●
If ticket is equal to lottery, print “You Won!!!...” ; otherwise print “Better Luck next
time…”.
Multi-Way Selection Statement: “if-elif” ladder
To execute multiple block of statement
based on multiple
conditions if-elif statement is used.
● The general format:
If <condition>:

<Indented instruction of “if” block>


elif <condition>:
<Indented instruction of “elif” block>
else:
<Indented instruction of “else”
block>
Iteration Structures:

In Python, iterative statements are called Looping or


Repetitive statements. These statements are used to execute a part of the
program as long as condition is True.

e.g.: To print a sequence of numbers from 1


to 100 inclusive.

The for loop is iterative statement

Without loop or iterative statements of print() statement.


The iterative statement help in traversing through strings, lists,
Printing numbers from 1 to 100 is tedious, cumbersome and dictionaries, and tuples.
time-consuming (also space complexity) task due to repetitions
Iteration using “for” statement:

● The general format:

For <variable> in <sequence>:

<Indented instruction block>

<non-Indented instruction>

Here, the sequence may be a List,


Tuple, Set, and string.
e.g.:
Nesting of Control Flow Statements:

Like other languages, it is possible to nest different the


control flow statements in a program.

e.g.:

The use of “if” and “for” loop statement.


The “for” statement with function range():
Instead of iterating over all elements of sequence,
sometimes it is necessary to iterate over a sequence in a given range.
● The for loop statement cannot iterate over sequence when list of elements in
sequence is not explicitly specified.
● It is possible to accomplish this behavior with new version for statement,
Python provide built-in function “range()”, the function is used together with for
loop to traverse over a sequence of numbers in a given range.
● The “range()” function iterate over sequence that have start at non-starting
element and end before last element of sequences.
● The general format:
○ range(start, end)
e.g.: 1).

Functions

● Mostly, programming and running programs follow definite patterns. ● A


program is often run repeatedly with different sets of data that too on
different occasions/days.
● So, programs have to be stored and re-run.
● Sometimes, a program calls for a modification and a rerun in the modified
form.
● Some situations call for the use of a code segment repeatedly in a program. ●
All these are facilitated in Python through the use of ‘functions’ and ‘modules’.
Functions:

Functions are entities which accept one or more arguments as


inputs, execute a specific code block, and return the result of execution of the
specified code block to the parent.

e.g.:

Form a Python function to return the harmonic mean of all


the numbers in the interval [100, 200] which are divisible by a.
Get the harmonic mean for a = 9.
a = 9 (default value)

Another example:

Do the coding for a function that returns a 1=p to the desired accuracy. Run it for a = 50
and p = 4. The accuracy in the computed value has to be better than 0.2%.
By referring figure we can conclude:

● The function defined can have as many arguments as desired. ● If any


argument is assigned a value in the function definition it will be the default
value of the argument in the function evaluation.
● If a value is specified for any argument during the function call the default
value will be overrun and the specified value used in the program run. ●
root_1 has been called with a specific set of values for the arguments [5]—
different from the default values specified in [1]; the result is in [6]. ● When a
function is called the argument list order is not a rigid constraint. (5 unchanged, 7
changed—-- specify parameters as well)
Note:

If function need not return anything specific it is indicated by only a


“return”. The interpreter will complete execution of the function and return to the
main program.
a). Lambda Function:

● Many situations call for the use of single line functions. ● The
keyword ‘lambda’ facilitates this in a compact form. ● It defines
an anonymous function of the specified arguments.
Note:

situations.

The simpler (and more compact) implementation using


lambda is more convenient in many
b). Recursion:

● Some routines require a code sequence to be repeatedly executed with a


successively increasing/decreasing parameter set.
● Such recursive routines can be coded compactly by the program calling
itself.

e.g.:

Write a Python program to compute (1/n!) and execute it for


n = 3.
Note:

● A main program can be composed of a number of smaller programs— if


necessary repeatedly used.
● Such ‘calls within calls’ can be done as many times as required.
● The arguments used in a function definition can be of any type without
restrictions as long as they are meaningfully used within the function.

e.g.:

Obtain the sum of the cube roots of all the integers from 3
to 8 (inclusive).
Nested Functions:

● One function can have other functions defined within it.


● If necessary such a daughter function can be returned for use outside.
e.g.:

snn(x) in [1] is defined as a function which computes sin(x) using the


series

Nested Scope

● Any object in its environment in Python (like a variable, a function and c.) can
be read for its value using proper references.
● The value can be altered and reassigned in the same environment when
possible.
● Declaring an object as ‘global’ or ‘nonlocal’ makes it possible to change the
scope of access of the object for reading or reassigning in different ways.
Note:
● When ff1 is called Python
searches for a1 within ff1 first; if
not available here the scope of
search is widened to the
immediate outer domain.
● If a1 is not available there either,
the search continues in the next
outer domain and so on.
Note:

● If a1 were not available


after all such
possibilities are
exhausted, an error is
returned and
execution terminated.
● The process of
search for
availability of
any object in this manner is automatic.
● As many entities as desired can be declared as global in this manner.

User Defined functions


● Let us understand and execute commonly used built-in functions in Python.

● Python provide several built-in functions to perform a specific task. ● All these
built-in functions accept zero or more input arguments and returns a result, it is
easy to call these functions using single line statement by function name and
pass required arguments to function.
● Python allow user to define their own function to accomplish the specific task.
● User-defined function contains a set of instructions grouped together under a
single name to perform a specified task.
● Like built-in functions, user-defined function accept zero or more number of
input arguments from user and return result.
General Format:

Note:
Python does not allow calling a function before it is defined.
Note:
The print statement can print the value or message but it cannot return value.
Example:

Type Error
Another Example:
In Python, Function Definitions are just like other statements.
Comments in Python: (‘#’ Symbol)

● The easy way to increase the readability of program is by using comments at


appropriate places in the program.
● Comments are inline explanation that help to understand function definition,
variable and control statements.
● The purpose of writing a comment in program is:
○ Developers must know what their own code is, to perform all the time and order of execution. ○
User of program or other developer skim through program code and understand flow of entire
program and what it does.
○ The comment in program facilitates the understanding of the program, including variables.

● The comments are necessary therefore, comments should be short, sweet,


and to the point.
● Comments should not make it difficult to read the program. ● Python does not
allow developer or user to write comments that spread over multiple lines.
● To do multi-line comments in Python, after each line comment, add a new
hash mark and continue comment from there.

You might also like