CSE1012 Problem Solving and Programming
Session - 5
Dr. L.PAVITHRA
Assistant Professor (sr)
SCOPE
VIT University
1
Introduction to python
2
Need of programming Languages
• Computers can execute tasks very rapidly and assist
humans
• Programming languages – Helps for communication
between human and machines.
• They can handle a greater amount of input data.
• But they cannot design a strategy to solve problems for
you
3
Python – Why?
• Python has a simple syntax and very few keywords.
• Python programs are clear and easy to read and
Understand.
• It has Powerful programming features and highly portable
and extensible
• Python is a High Level Language.
• Companies and organizations that use Python include
YouTube, Google, Yahoo, and NASA.
• Python is well supported and freely available at
www.python.org.
4
Brief History of Python
• Invented in the Netherlands, early 90s by Guido van Rossum.
• Named after Monty Python.
• Open sourced from the beginning.
• Considered a scripting language, but is much more Scalable,
object oriented and functional from the beginning.
• It is a object oriented programming language. ! everything is
object.
• Genealogy:
– Setl (NYU, J.Schwartz et al. 1969-1980).
– ABC (Amsterdam, Meertens et al. 1980-).
– Python (Van Rossum et all. 1996-).
5
Time Line of Python
• Python born, name picked - Dec 1989.
• First public release (USENET) - Feb 1991
• python.org website - 1996 or 1997
• Python Software Foundation – 2001
• 2.0.1 released - 2001
• 3.0.1 released – 2009
• Current version: 3.10.7 and 2.7.18
6
IEEE Spectrum’s Top
Programming Languages 2022
7
Python….
• High-level language; other high-level languages you might have
heard of are C, C++, Perl, and Java.
• There are also low-level languages, sometimes referred to as
“machine languages” or “assembly languages.”
• Computers can only run programs written in low-level languages.
• So programs written in a high-level language have to be processed
before they can run.
8
Python….
• Two kinds of program translator to convert from high-
level languages into low-level languages:
– Interpreters
– Compilers.
• An interpreter processes the program by reading it line by
line
9
• Compiler translates completely a high level program to
low level it completely before the program starts running.
• High-level program is called source code
• Translated program is called the object code or the
executable.
10
Python….
• Python is considered an interpreted language because Python
programs are executed by an interpreter.
• Python Virtual Machine (PVM)
• Interpreter converts the byte code into machine code and sends that
machine code to the computer processor for execution.
• There are two ways to use the interpreter:
11
interactive mode and script mode.
Python….Interactive mode
• In interactive mode, you type Python programs and the
interpreter displays the result:
>>> 1 + 1
2
The shell prompt, >>>, is the prompt the interpreter uses to
indicate that it is ready.
• If you type 1 + 1, the interpreter replies 2.
12
Python…. Script Mode
• Can also store code in a file and use the interpreter to
execute the contents of the file, which is called a script.
• Python scripts have names that end with .py.
• Interactive mode is convenient for testing small pieces of
code because you can type and execute them immediately.
• But for anything more than a few lines, should save your
code as a script so you can modify and execute it in future.
13
Python….Script Mode …
File name : first.py
print(4+3)
print(4-3)
print(4>3)
print("hello World")
14
Who Uses Python Today?
Python is considered to be in the top 5 or top 10 most
widely used programming languages in the world today
Google makes extensive use of Python in its web
search systems.
YouTube video sharing service is largely written in
Python.
Dropbox storage service codes both its server and
desktop client software primarily in Python.
The Raspberry Pi single-board computer promotes
Python as its educational language. 15
EVE Online, by CCP Games, uses Python broadly.
BitTorrent peer-to-peer file sharing system began
uses Python
Industrial Light & Magic, Pixar, and others use
Python in the production of animated movies.
ESRI uses Python as an end-user customization
tool for its popular GIS mapping products
Google’s App Engine web development framework
uses Python
IronPort email server product uses more than 1
million lines of Python code to do its job.
Maya, provides a Python scripting API. 16
NSA uses Python for cryptography and intelligence
analysis.
iRobot uses Python to develop robotic devices.
One Laptop Per Child (OLPC) project built its user
interface and activity model in Python.
Netflix and Yelp have both documented the role of
Python in their software infrastructures.
Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm,
and IBM use Python for hardware testing.
JPMorgan Chase, UBS, Getco, and Citadel apply
Python to financial market forecasting.
NASA, Los Alamos, Fermilab, JPL, and others use
Python for scientific programming tasks. 17
What Can I Do with Python?
Systems Programming
GUIs
Internet Scripting
Component Integration
Database Programming
Rapid Prototyping
Numeric and Scientific Programming
And More: Gaming, Images, Data Mining, Robots, Excel...
18
What Are Python’s Technical
Strengths?
It’s Object-Oriented and Functional
It’s Free
It’s Portable
It’s Powerful
It’s Mixable
It’s Relatively Easy to Use
It’s Relatively Easy to Learn
19
Identifiers and keywords
20
What is an Identifier?
• An identifier is a sequence of one or more
characters used to name a given program element.
• In Python, an identifier may contain letters and
digits, but cannot begin with a digit.
• Special underscore character can also be used
• Example : line, salary, emp1, emp_salary, 1emp
21
Rules for Identifier
• Python is case sensitive, thus, Line is different from line.
• Identifiers may contain letters and digits, but cannot begin
with a digit.
• The underscore character, _, is also allowed to aid in the
readability of long identifier names. It should not be used
as the first character
• Spaces are not allowed as part of an identifier. Empl1
22
Identifier Naming
23
Keywords
• A keyword is an identifier that has pre-defined
meaning in a programming language.
• Therefore, keywords cannot be used as “regular”
identifiers. Doing so will result in a syntax error, as
demonstrated in the attempted assignment to keyword
and below,
24
Keywords in Python
25
Variables and Identifiers
• A variable is a name (identifier) that is associated
with a value.
• A simple description of a variable is “a name that
is assigned to a value,”
Variables are assigned values by use of the assignment
operator,
num = 10 # assigning value 10 to variable num\
num = num + 1
26
Comments
• Meant as documentation for anyone reading the code
• Single-line comments begin with the hash character ("#")
and are terminated by the end of line. \
• Python ignores all text that comes after # to end of line
• Comments spanning more than one line are achieved by
inserting a multi-line string (with """ as the delimiter one
each end) that is not used in assignment or otherwise
evaluated, but sits in between other statements.
• #This is also a comment in Python
• """ This is an example of a multiline comment that spans
multiple lines ... "“” 27
Literals
28
Literals
• A literal is a sequence of one or more characters
that stands for itself.
29
Numeric literal
• A numeric literal is a literal containing only the
digits 0–9, an optional sign character (1 or 2),
and a possible decimal point. (The letter e is also
used in exponential notation).
• If a numeric literal contains a decimal point, then it
denotes a floating-point value, or “float” (e.g.,
10.24); otherwise, it denotes an integer value
(e.g., 10).
• Commas are never used in numeric literals
30
Numeric Literals in Python
Since numeric literals without a provided sign character denote positive values,
an explicit positive sign character is rarely used.
31
32
String Literals
• String literals, or “strings,” represent a sequence
of characters,
'Hello' 'Smith, John' "Baltimore, Maryland 21210“
• In Python, string literals may be surrounded by a
matching pair of either single (') or
double (") quotes.
• >>> print('Welcome to Python!')
>>>Welcome to Python!
33
String Literal Values
34
Note
35
36
Control Characters
• Special characters that are not displayed on the screen.
Rather, they control the display of output
• Do not have a corresponding keyboard character
• Therefore, they are represented by a combination of
characters called an escape sequence.
• The backslash (\) serves as the escape character in
Python.
• For example, the escape sequence '\n', represents the
newline control character, used to begin a new screen line
37
38
Data Types
39
Data Types
• Python's data types are built in the core of the language
• They are easy to use and straightforward.
• Data types supported by Python
– Boolean values
– None
– Numbers
– Strings
– Tuples
– Lists
– Sets
40
Boolean values
• Primitive datatype having one of two values: True or
False
• some common values that are considered to be True or
False
41
Boolean values
print bool(True) True
print bool(False) False
print bool("text") True
print bool("") False
print bool(' ') True
print bool(0) False
print bool() False
print bool(3) True
print bool(None) False
42
None
• Special data type - None
• Basically, the data type means non existent, not
known or empty
• Can be used to check for emptiness
43
Numbers
Types of numbers supported by Python:
• Integers
• floating point numbers
• complex numbers
• Fractional numbers
44
Integers
• Integers have no fractional part in the number
• Integer type automatically provides extra
precision for large numbers like this when needed
(different in Python 2.X)
• >>> a = 10
• >>> b = a
45
Binary, Octal and Hex Literals
• 0b1, 0b10000, 0b11111111 # Binary literals: base
2, digits 0-1
• 0o1, 0o20, 0o377
• # Octal literals: base 8, digits 0-7
• 0x01, 0x10, 0xFF # Hex literals: base 16,
digits 0-9/A-F
• (1, 16, 255)
46
Conversion between different
bases
• Provides built-in functions that allow you to
convert integers to other bases’ digit strings
• oct(64), hex(64), bin(64)
• # Numbers=>digit strings ('0o100', '0x40',
'0b1000000')
• These literals can produce arbitrarily long integers
47
Numbers can be very long
• >>> X = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF
• >>> X 5192296858534827628530496329220095
• >>> oct(X)
'0o17777777777777777777777777777777777777‘
• >>> bin(X)
'0b11111111111111111111111111111111111111111
1111111111111111
• ...and so on... 11111‘
48
Floating Point Numbers
• Number with fractional part
• >>> 3.1415 * 2
• >>>6.283
49
Floating Point Numbers
50
Arithmetic overflow
• a condition that occurs when a calculated result is
too large in magnitude (size) to be represented,
>>>1.5e200 * 2.0e210
>>> inf
This results in the special value inf (“infi nity”)
rather than the arithmetically correct result
3.0e410, indicating that arithmetic overflow has
occurred.
51
Arithmetic underflow
• a condition that occurs when a calculated result is
too small in magnitude to be represented,
>>>1.0e-300 / 1.0e100
>>>0.0
• This results in 0.0 rather than the arithmetically
correct result 1.0e-400, indicating that arithmetic
underflow has occurred.
52
Arithmetic overflow occurs when a calculated result is too large in magnitude to be represented.
Arithmetic underflow occurs when a calculated result is too small in magnitude to be represented
53
Repeated Print
>>>print(‘a’*15)
# prints ‘a’ fifteen times
>>>print(‘\n’*15)
# prints new line character fifteen times
54
Complex Numbers
• A complex number consists of an ordered pair of
real floating point numbers denoted by a + bj, where
a is the real part and b is the imaginary part of the
complex number.
• complex(x) to convert x to a complex number with
real part x and imaginary part zero
• complex(x, y) to convert x and y to a complex
number with real part x and imaginary part y.
• x and y are numeric expressions
55
Complex Numbers
>>> 1j * 1J
(-1+0j)
>>> 2 + 1j * 3
(2+3j)
>>> (2 + 1j) * 3
(6+3j)
• A = 1+2j; B=3+2j
• # Mutpile statements can be given in same line
using semicolon
• C = A+B; print(C)
56
Complex Numbers
# prints real part of the number
• print(A.real)
# prints imaginary part of the number
• print(A.imag)
# Can do operations with part of complex number
• print(A.imag+3)
57
Input and output function
Input function : input
Basic_pay = input('Enter the Basic Pay: ')
Output function : print
print('Hello world!')
print(‘Net Salary', salary)
58
By Default…
• Input function reads all values as strings, to
convert then to integers and float, use the function
int() and float()
59
Type conversion…
Here, the entered number of credits, say '24', is converted to the equivalent integer
value, 24, before being assigned to variable num_credits. For input of the gpa, the
entered value, say '3.2', is converted to the equivalent floating-point value, 3.2. Note
that the program lines above could be combined as follows,
60
Assignment Statement
Statement Type
spam = 'Spam' Basic form
spam, ham = 'yum', 'YUM' Tuple assignment (positional)
[spam, ham] = ['yum', 'YUM'] List assignment (positional)
a, b, c, d = 'spam' Sequence assignment, generalized
a, *b = 'spam' Extended sequence unpacking
(Python 3.X)
spam = ham = 'lunch' Multiple-target assignment
spams += 42 Augmented assignment (equivalent
to spams = spams + 42)
61
Range
>>>a,b,c = range(1,4)
>>>a
1
>>>b
2
>>> S = "spam" >>> S += "SPAM" # Implied concatenation
>>> S
'spamSPAM'
62
Assignment is more powerful
in Python
>>> nudge = 1
>>> wink = 2
>>> nudge, wink = wink, nudge
# Tuples: swaps values
# Like T = nudge; nudge = wink; wink = T
>>> nudge, wink
(2, 1)
63
64