Python
Python
Introduction
N Manjunath Gowda
Asst. Professor
Department of Mechanical Engineering
University BDT College of Engineering, Davangere.
What is Machine Language?
1: MOV eax, 3
MOV ebx, 4
ADD eax, ebx, ecx
II. High-level programming language
High-level programming language (HLL) is designed for
developing user-friendly software programs and websites.
This programming language requires a compiler or interpreter
to translate the program into machine language (execute the
program).
The main advantage of a high-level language is that it is easy to
read, write, and maintain.
High-level programming language includes Python, Java,
JavaScript, PHP, C#, C++, Objective C, Cobol, Perl, Pascal, LISP,
FORTRAN, and Swift programming language.
PYTHON
CHARACTER
SET
Key
Words
Punctuators Identifiers
TOKENS
Operators Literals
Key word
Keyword
Keywords are also called as reserved words, these are having special meaning in
python language. The words are defined in the python interpreter hence these
cant be used as programming identifiers.
var = 1;
if(var==1):
print("odd")
else:
print("even")
Identifier
Identifier or Python Variables
Python variables are nothing but the reserved memory locations to store the
values. In other words, it is the name of the memory location where the data is
stored. And if once the variable is stored a separate space is allocated in the
memory.
Example:
a = 100
print(a)
a 100
Rules of Defining Variable
Exponent Form: It consists of two parts Mantissa and Exponent. for example 5.8
can be represented as 0.58 x 10-1 = 0.58E01. where mantissa part is 0.58 and E01 is
Strings
str (String)
Sequence of letters enclosed in quotes is called string or string literal or
constant.
Single Line Strings
Strings created using single quote or double quote, end in one line are called
single line strings.
Example: Item=“Computer”
Or Item= ‘Computer’
Multi Line Strings
A multiline string in Python begins and ends with either three single quotes or three
double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are
considered part of the string. Python’s indentation rules for blocks do not apply to lines
inside a multiline string.
Example:
Output
The following print() call would print identical text but doesn’t use a multiline
string:
Booleans
Boolean
Special Literal
Special Literal
Python supports literal collections also, such as tuple and lists ..etc
Operators
Operators
Operators are special symbols that perform operations on variables and values.
Arithmetic operators
Assignment Operators
Comparison Operators
Logical Operators
Bitwise Operators
Special Operators
Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
Output
Assignment Operators
Assignment operators are used to assign values to variables.
Output
a=5
b=6
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Here, we see that x1 and y1 are integers of the same values, so they are equal as
well as identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the
interpreter locates them separately in memory although they are equal.
Membership operators
In Python, in and not in are the membership operators. They are used to test
whether a value or variable is found in a sequence (string, list, tuple, set and
dictionary).
In a dictionary we can only test for presence of key, not the value.
Output
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similarly, 1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
Punctuators
Punctuators
Punctuators are also called as separators, They are used to organize the structures,
statements and expressions.
Brackets []
Parentheses ()
Braces {}
Comma ,
Semicolon ;
Colon :
Asterisk *
Ellipsis …
Equal Sign =
Pound Sign #
Comments
Comments are non executable statements in a program. In computer
programming, comments are hints that we use to make our code more
understandable.
Comments are completely ignored by the interpreter. They are meant for fellow
programmers.
Single-line Comment
A single-line comment starts and ends in the same line.
We use the # symbol to write a single-line comment.
Example:
Output
We can also use the single-line comment along with the code.
Multi-line Comment
Another way of doing this is to use triple quotes, either ''' or """
Use of Python Comment
1. Make Code Easier to Understand
If we write comments in our code, it will be easier for future reference.
Also, it will be easier for other developers to understand the code.
2. Using Comments for Debugging
If we get an error while running the program, we can comment the line of code
that causes the error instead of removing it. For example,
Syntax Errors
Logical Errors
Syntax Errors
A syntax error is one of the most basic types of error in programming. Whenever
we do not write the proper syntax of the python programming language (or any
other language) then the python interpreter or parser throws an error known as a
syntax error. The syntax error simply means that the python parser is unable to
understand a line of code.
number = 100
if number > 50
print("Number is greater than 50!")
File "test.py", line 3
if number > 50
^
SyntaxError: invalid syntax
number = 100
divided_by_zero = number / 0
print(divided_by_zero)
Traceback (most recent call last):
File "d:\test.py", line 2, in <module>
divided_by_zero = number / 0
ZeroDivisionError: division by zero
Zero Division Error is raised by the Python interpreter when we try to divide any number
by zero.
Dynamic Typing
Dynamic Typing
Dynamic typing means that the type of the variable is determined only during
runtime. A variable pointing to a value of certain type can be made to point to a
value/object of different type this is called Dynamic Typing.
x=10
Output will be
print(x)
10
x=“ Hello World”
Hello World
print(x)
x = ‘day’
y = x/2 Error! String can not be divided.
Functions
Function
A function is a block of code(reusable) that performs a specific task.
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
Function Header
The syntax to declare a function is:
Output
How it works?
When the function is called, the control of the program goes to the function
definition.
All codes inside the function are executed.
The control of the program jumps to the next statement after the function call.
Python Function Arguments
If we create a function with arguments, we need to pass the corresponding
values while calling them.
Example:
We can also call the function by mentioning the argument name as:
Function return Type This functions has both
input and output
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:
Output
Output
Advantages of modules
Reusability : Working with modules makes the code reusable.
Simplicity: Module focuses on a small proportion of the problem, rather than focusing on
the entire problem.
Scoping: A separate namespace is defined by a module that helps to avoid collisions
between identifiers.
Built-in modules
Python has a large number of built-in modules, which are used to make tasks easy and
more readable. These modules provide a wide range of functionality and are always
available for use without the need to install any additional packages.
A list of a few most frequently used built-in python modules is given below
math: This module is very useful to perform complex mathematical functions such as
trigonometric functions and logarithmic functions.
date: The date module can be used to work with date and time such as time, date, and
datetime.
os: Provides a way to interact with the underlying operating system, such as reading or
writing files, executing shell commands, and working with directories.
sys: Provides access to some variables used or maintained by the Python interpreter,
such as the command-line arguments passed to the script, the Python version, and the
location of the Python executable.
User-defined modules
User-defined python modules are the modules, which are created by the user to
simplify their project. These modules can contain functions, classes, variables, and
other code that you can reuse across multiple scripts.
Create a normal Import it in another
python file python file
Importing the whole module object using its original name
The first way is to use the import statement, using the syntax import module_name
>>> import math
We've just imported the math module. We can use the things within this module
by looking up attributes on the math module object.
For example, we can get the square root of a number by calling math.sqrt
>>> math.sqrt(25)
5.0
Or we can access the number π with math.pi
>>> math.pi
3.141592653589793
But we can't access just pi or sqrt (without that math. prefix). The reason is, when we import
a module using that import module_name syntax, we get just one thing:
If you wanted to just type pi instead of math.pi, you could use the from syntax for importing:
>>> pi
3.141592653589793
So now we have pi, but not sqrt (because we didn't import it).
If you want to import multiple things from a module using this from syntax,
you could put commas each thing you'd like to import:
>>> from math import pi, sqrt
>>> pi
3.141592653589793
>>> sqrt(25)
5.0
That from math import pi, sqrt line plucks out pi and sqrt from the math module, but nothing
else.
Importing specific things from a module, with as syntax
>>> sqrt(25)
5.0
>>> csqrt(25)
(5+0j)
Import the whole module and rename it
You can also use the as syntax when importing a whole module.
>>> import math as m
The variable m now points to the math module object which means we can't say math.pi
anymore:
>>> m.pi
3.141592653589793 >
>> m.sqrt(25)
5.0
from _module import * statement
Variable = Expression
A variable is initialized (or created) the first time a value is stored in it.
After that, you can use it in expressions with other variables and values.
When a variable is assigned a new value , the old value is forgotten, which
is why spam evaluated to 42 instead of 40 at the end of the example. This
is called overwriting the variable.
Python allows multiple assignments
x is bound to 21 and y
x, y = 10, 20 to 11 at the end of the
x, y = y+1, x+1 program
Output
Output
Output
Assigning different operation results to multiple variable
Output
Output
Local and Global Variables
Local and Global Variables
Variables that are created outside of the function are global variables.
Local variables are those which are defined inside a function and its scope limited to
that function only means local variables are accessible only inside the function. it
cannot be accessed anywhere outside the function.
Global Variables
Local Variable
Error
Global Variable
Global Variable
Local Variable
Error
Python Input Function
input()
The input() function takes input from the user and returns it.
Variable_to_hold_the_value = input(message)
input() function without prompt
Output
Output
The input() function always returns a string, even if the user enters a number.
Use the int() function to get the integer form of spam and then store this as the
new value in spam.
The int() function is also useful if you need to round a floating-point number down.
p = input(“Enter the value:”)
x = int(input(“Enter x value:”))
reads the value and converts it in to integer type data or value.
y=float(input(“Enter y value:”))
reads the value and converts it in to float type data or value.
Note:
Python makes this distinction because strings are text, while integers and
floats are both numbers.
Python Print Function
print()
The print() function prints the given object to the standard output device (screen)
or to the text stream file.
The general format or syntax of the input() is:
This program tries to open the python.txt in writing mode. If this file doesn't exist,
python.txt file is created and opened in writing mode.
Here, we have passed sourceFile file object to the file parameter. The string object
'Pretty cool, huh!' is printed to the python.txt file (check it in your system).
Finally, the file is closed using the close() method.
Python Length Function
len()
The len() function takes a single argument/s, which can be
•sequence - string, bytes, tuple, list, range OR,
•collection - dictionary, set, frozen set
Output
Python Type Casting
Type Casting (type conversion)
Conversion of value of one type to other
Examples
Break: A break statement in Python alters the flow of a loop by terminating it once a
specified condition is met.
Continue: The continue statement in Python is used to skip the remaining code inside a
loop for the current iteration only.
Pass: The pass statement in Python is used when a statement or a condition is required
to be present in the program, but we don’t want any command or code to execute. It’s
typically used as a placeholder for future code.
BREAK Statement
count=0 Output
while count<=7:
if count==5:
break
else:
print(count)
count+=1
print("ok bye!")
CONTINUE Statement
Output
var=10
while var>0:
var=var-1
if var==3:
continue
print(var)
print("Ok bye!")
PASS Statement
x=10
if x>10:
pass
Exception Handling
Errors that occur at runtime (after passing the syntax test) are called exceptions or
logical errors.
An exception is an unexpected event that occurs during program execution.
For example,
divide_by_zero = 7 / 0
The above code causes an exception as it is not possible to divide a number by 0.
def add(x,y):
return (x+y)
print(add(2,7))
print(add(5,10))
print(add(7,'a'))
print(add(12,2))
print('Execution done')
def add(x,y):
try:
return (x+y)
except TypeError:
return ("Invalid")
print(add(2,7))
print(add(5,10))
print(add(7,'a'))
print(add(12,2))
print('Execution done')
The try block lets you test a block of code for errors.
The except block lets you handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try- and
except blocks.