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

CST 445-Python For Engineers

Uploaded by

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

CST 445-Python For Engineers

Uploaded by

Hrudhya Haridas
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

CST 445-Python for

Engineers

Dr Manju K
INTRODUCTION
• Python was created by Guido Van Rossum in late 1980 when he was
working at CWI (Centrum Wiskunde & Informatica) which is a
National Research Institute for Mathematics and Computer Science in
Netherlands.

• Python got its name from a BBC comedy series from seventies-
“Monty Python's Flying Circus”.
Features which make Python popular
• It is a general purpose programming language which can be used for
both scientific and non scientific programming.
• It is a platform independent programming language.
• It is a very simple high level language with vast library of add-on
modules.
• The programs written in Python are easily readable and
understandable.
• It is easy to learn and use.
• Dynamically typed and garbage collected
• Supports procedural, object oriented and functional programming.
Running Python Program-IDLE,Interactive Shell,
Jupyter, How Python works
• Download the latest release of Python from
www.python.org depending on your OS Windows, Linux or Mac.
• IDLE( Integrated Development Environment).
Visit https://docs.python.org/3/library/idle.html to get complete
details of IDLE.
Working with IDLE
1. Open IDLE by clicking the application icon
2. Open File menu and click New File and type your first script ( Eg:
print("welcome to Python")
3. Save your file with .py extension ( Eg:test.py)
4. From the Run menu click the Run Module( or press F5-short
cut).This will run the script.
5. From the File menu choose Exit to quit from IDLE
How to Run Python Code Interactively
• To start a Python interactive session, just open a command-line or
terminal and then type in python, or python3 depending on your
Python installation, and then hit Enter.

• Jupyter Notebook is a web application that allows you to create and


share documents that contain:
• live code (e.g. Python code)
• visualizations
explanatory text (written in markdown syntax)
Identifiers in Python
• Identifiers are names used to identify variables, functions, classes,
modules, and other objects in Python.
• Rules for framing identifiers
a) Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore _.
Names like myClass, var_1 and print_this_to_screen, all are valid example.
b) An identifier cannot start with a digit.
1variable is invalid, but variable1 is a valid name
c) Keywords cannot be used as identifiers.
Eg: global = 1 is invalid
d) We cannot use special symbols like !, @, #, $, % etc. in our identifier.a@=0 is
invalid
e) An identifier can be of any length.
Variables
• Variables are containers for storing data values.
• Python has no command for declaring a variable.
• A variable is created the moment you first assign a value to it.
Examples:
x=5
y = "John“
……………
x=4 # x is of type int
x = "Sally" # x is now of type str
The data type of a variable can be obtained with the type() function
print(type(x))
<type 'str'>
Keywords

• Python has a set of keywords that are reserved words that cannot be
used as variable names, function names, or any other identifiers:
Basic Python Data Types-Numbers and Strings,Type
conversions
• Every value in Python has a datatype.
• Python data types are classes and variables are instances (objects) of
these classes.
Data types
Data types
• Python Numbers
Integers, floating point numbers and complex numbers fall
under Python numbers category. They are defined as int, float and
complex classes in Python.
type() function is used to determine the type of Python data type.
the isinstance() function is used to check if an object belongs to a
particular class.
Data Type
Python Strings
String is sequence of Unicode characters.
We can use single quotes or double quotes to represent strings.
Multi-line strings can be denoted using triple quotes, ''' or """.
Example:
Accessing elements of String
• In Python programming, individual characters of a String can be
accessed by using the method of Indexing.
• Negative Indexing allows negative address references to access
characters from the back of the String,
• e.g. -1 refers to the last character, -2 refers to the second last
character, and so on.
Data Type
• List Data Type
• Lists are just like arrays, declared in other languages which is an ordered
collection of data. It is very flexible as the items in a list do not need to be
of the same type.
• Tuple Data Type
• tuples are created by placing a sequence of values separated by a ‘comma’
with or without the use of parentheses for grouping the data sequence.
• Boolean Data Type
• The boolean data type is either True or False. In Python, boolean variables
are defined by the True and False keywords
• the keywords True and False must have an Upper Case first letter
Operators
• Operators are used to perform operations on variables and values.
• Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic Operators( Mathematical)
Comparison Operators
• Comparison operators are used to compare two values. They are also
called Relational operators.
Logical Operators
Identity Operators-Identity operators compare
the memory locations of two objects.
Bitwise operators
• Bitwise operator works on bits and performs bit-by-bit operation
Membership Operators
• Membership operators are used to test if a sequence is presented in
an object
Summary-Imp operators
Operator precedence and expression
evaluation
• Operator precedence in Python determines the order in which
operations are performed when an expression contains multiple
operators.
• Operators with higher precedence are evaluated before operators
with lower precedence.
• When operators have the same precedence, their associativity
determines the order of evaluation.
Precedence of Operators
• The precedence rule learned in algebra is applied during the evaluation of arithmetic
expression in Python.
• Exponentiation has the highest precedence and is evaluated first.
• Unary negation is evaluated next before multiplication and division
• Multiplication, division and mod operators are evaluated before addition and subtraction
• Addition and subtraction are evaluated before assignment
• Operations of equal precedence are left associative, so they are evaluated from left to
right.
• Exponentiation and assignment operations are right associative, so consecutive instances
of these are evaluated from right to left
• We can use parentheses to change the order of evaluation
• Parentheses have the highest precedence and can be used to force the evaluation order.
Mixed Mode Arithmetic and Type Conversion
• In Python, mixed mode arithmetic refers to operations involving
operands of different data types. When performing such operations,
Python automatically converts the operands to a common data type
before performing the operation. This process is known as type
conversion.
Output and Input functions- print() and input()
• print() function- to output data to the standard output device (screen)
• The actual syntax of the print() function is:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
• Here, objects is the value(s) to be printed.
The sep separator is used between the values. It defaults into a space
character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is
sys.stdout (screen).
• flush: Whether to forcibly flush the stream.
• >>>print(1, 2, 3, 4, sep='*’)
• 1*2*3*4
• >>>print(1, 2, 3, 4, sep='#', end='&')
• 1#2#3#4&
Output formatting
• >>> x = 5; y = 10
• >>> print('The value of x is {} and y is {}'.format(x,y))
• The value of x is 5 and y is 10
-----------------------------------------------------------------------------------------------------
• >>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning',
name = 'John'))
• Hello John, Goodmorning
-----------------------------------------------------------------------------------------------------
• >>> x = 12.3456789
• >>> print('The value of x is %6.2f' %x) # rounded to two decimal values
• The value of x is 12.35
Python input() function for reading data
• The syntax for input() is:
input([prompt])
>>> num = input('Enter a number: ‘)
Enter a number: 10
• >>> num
• '10'
• >>>type(num)
• <class 'str'>
Built-in Functions, Modules and Packages

• Built-in Functions
A function is a named sequence of statement(s) that performs a
computation.
It contains line of code(s) that are executed sequentially from top to
bottom by Python interpreter.
They are the most important building blocks for any software
development in Python.
Built in functions are the function(s) that are built into Python Standard
Library and can be accessed directly.
Functions usually have arguments and return a value.
Built-in functions
• Some built in functions are given below with examples. Refer python
documentation for more details.
https://docs.python.org/3.8/library/functions.html
Modules
When our program grows bigger, it is a good idea to break it into different
modules.
A module is a file containing Python functions, classes, and variables. A
module can also include runnable code. Python modules have a filename
and end with the extension .py.
• We use modules to break down large programs into small manageable and
organized files. Furthermore, modules provide re usability of code.
• Definitions inside a module can be imported to another module or the
interactive interpreter in Python. We use the import keyword to do this.
• Packages
A package is a collection of modules organized in directories that
include a special file called __init__.py. The __init__.py file can be
empty or execute initialization code for the package. Packages allow for
a hierarchical structuring of the module namespace.
Each package in Python is a directory which MUST contain a special file
called __init__.py. This file can be empty, and it indicates that the
directory it contains is a Python package, so it can be imported the
same way a module can be imported.
Creating a Package
Directory Structure:
mypackage/
• __init__.py
• module1.py
• module2.py

• module1.py:
• def foo():
• return "foo from module1"

module2.py:
• def bar():
• return "bar from module2"

__init__.py:
• from .module1 import foo
• from .module2 import bar
Comments in the program
• Single-Line Comments in Python
In Python, we use the hash (#) symbol to start writing a comment.It extends up to the newline
character. Comments are for programmers to better understand a program. Python Interpreter
ignores comments.
• Multi-Line Comments in Python
We can have comments that extend up to multiple lines. One way is to use the hash(#) symbol at
the beginning of each line. For example:
#This is a long comment
#and it extends
#to multiple lines

• Another way of doing this is to use triple quotes, either ''' or """.
Simple programs
Program Format and Structure
• It is always better to structure your Python program as follows:

Start with an introductory comment stating the author's name, the purpose of the
program and other relevant information. This information should be in the form of
comment or document string
• Then include statements that do the following
Import any modules needed by the program
Initialize important variables, suitably commented
Prompt the user for input data and save the input data in variables
Process the input to produce the results
Display the results
What are syntax errors in Python?
• Python syntax errors happen when the Python interpreter is unable
to recognize the structure of statements in code.
• Syntax errors occur when you have a typo or other mistake in your
code that causes it to be invalid syntax.
• Some tips for avoiding syntax errors:
• Double-check your code for typos or other mistakes before running it.
• Use a code editor that supports syntax highlighting to help you catch syntax
errors.
• Read the error message carefully to determine the location of the error.
Syntax errors in Python
• Indentation Errors in Python
Here are a few rules to keep in mind when it comes to indentation in
Python:
• Use four spaces for each level of indentation.
• Don't mix tabs and spaces for indentation.
• Make sure your indentation is consistent throughout your code.
Python relies on indentation (whitespace at the beginning of a line) to
define scope in the code. Other programming languages often use
curly-brackets for this purpose.
Control Statements
• if-else
Conditional statements give us this ability to check conditions and
change the behavior of the program accordingly.
The condition usually uses comparisons and arithmetic expressions
with variables. These expressions are evaluated to the Boolean values
True or False.
The statements for the decision making are called conditional
statements, alternatively they are also known as conditional
expressions or conditional constructs.
Working of Nested -If
Looping Statements
Python programming offers two kinds of loop, the for loop and the while
loop.
while loop
• The while loop in Python is used to iterate over a block of code as long as
the test expression (condition) is true.
• We generally use this loop when we don't know the number of times to
iterate beforehand.
Syntax of while Loop in Python
while test_expression:
Body of while
Example
count = 0
while count < 5:
print(count)
count += 1
Example:

#Sum of numbers from 1 to 10


i=1
sum=0
while i<=10:
sum=sum+i
i=i+1
print("Sum=",sum)
For Loop

• The for loop is one of the looping statements in Python that is used to
iterate over a sequence of elements. This sequence can be a list,
tuple, string, or any other object that can be iterated.

list = ['PrepBytes', 'CollegeDekho', 'Ed-Tech']


for index in list:
print(index)
Nested Loops

• A nested loop is a loop within another loop. It is used when we want


to iterate over a sequence of elements that contains multiple levels of
nesting.
matrix = [[1, 2, 3] , [4, 5, 6] , [7, 8, 9]]
for row in matrix:
for element in row:
print(element)
Loop Control Statements

Loop control statements are used to alter the normal flow of the looping
Statements in Python. There are three types of loop control statements in
Python, which are, break, continue, and pass.
• The break statement is used to terminate the loop prematurely in Python.
It is used when we want to exit the loop before it has completed all of its
iterations.
• In Python, the continue statement is used to skip the current iteration of
the loop. It is used when we want to skip a certain element in the sequence
and continue with the next iteration of the loop.
• The pass statement is used as a placeholder in Python. It is used when we
want to write empty code blocks and want to come back and fill them in
later.
Example: break
fruits = ['apple', 'banana', 'cherry’]
for fruit in fruits:
if fruit == 'banana’:
break
print(fruit)
Example:continue
fruits = ['apple', 'banana', 'cherry’]
for fruit in fruits:
if fruit == 'banana’:
continue
print(fruit)

You might also like