Download as ppsx, pdf, or txt
Download as ppsx, pdf, or txt
You are on page 1of 54

Chapter 1:

Introduction to Python

© NIIT Slide 1 of 38
Objectives
By the end of this session, you should be able to:
• Assess the importance of Python
• Get started with the Python environment
• Understand Python interactive mode and scripting interface
• Understand variables, constructs and indentation
• List basic operations on numbers and strings
• Run a python script

© NIIT Slide 2 of 38
What is Python?
• A very high level, interpreted , interactive and object-oriented
language
• Easy to read and program with
• Similar to Perl but with powerful typing and object-oriented features
• Scripting Language

© NIIT Slide 3 of 38
• Python is Interactive: You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
• Python is Interpreted: Python is processed at runtime by the
interpreter. You do not need to compile your program before
executing it. This is similar to PERL and PHP.
• Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
• Python is a Beginner's Language: Python is a great language for the
beginner level programmers and supports the development of a wide
range of applications from simple text processing to WWW browsers
to games.

© NIIT Slide 4 of 38
History
• Python 1.x was released in November 1994.
• Python 2.x was released In 2000,
• Python 2.7.11 is the latest edition of Python 2.
• Python 3.x was released in 2008.
• Python 3 is not backward compatible

© NIIT Slide 5 of 38
Key Features
• Python focusses on readability, coherence, simplicity
• Python code is usually very compact
• Python code is portable across OS platforms
• Huge collection of libraries available for use by developers

© NIIT Slide 6 of 38
About Python
• Python was developed by Guido van Rossum in the late eighties
and early nineties at the National Research Institute for Mathematics
and Computer Science in the Netherlands.
• The language is named after the BBC show “Monty Python’s Flying
Circus”.
• Open source and interpreted language
• Considered a ‘scripting’ language, but is much more than that
• Scalable, object-oriented and functional
• Used by Google, increasingly popular
• Python knowledge is on high trending currently
© NIIT Slide 7 of 38
Users of Python
• YouTube: Originally written in Python and mysql
• Yahoo!: Yahoo acquired Four11, whose address and mapping lookup
services are implemented in Python
• Yahoo! Maps: Uses Python
• DropBox: A cloud based file hosting service runs on Python
• Google: Many components of the Google spider and search engine are
written in Python

© NIIT Slide 8 of 38
Traditional Uses of Python
• Embedded Scripting
• Image processing
• Artificial intelligence
• GUI’s
• Database Programming
• Internet Scripting
• System Administration
• Automation

© NIIT Slide 9 of 38
Uses of Python in Data Analytics
• Weather Forecasting
• Scientific analysis
• Ad targetting
• Risk Management Analysis
• Natural Language Processing and Generation

© NIIT Slide 10 of 38
Python 2 or Python 3?
• We would be using Python 3.5+

• Library support is more for Python 2.7 as it has been around longer
• The future is going to be Python 3+
• Development and porting of libraries is an ongoing process

• There are several key syntactic changes so advisable to be with 3.5+

© NIIT Slide 11 of 38
How to get Python?
• Comes pre-installed on most Unix systems, including Linux and Mac OS
X
• Check your python version by issuing the following command

python --version
Python 3.5.2

© NIIT Slide 12 of 38
Python Download and Installation
• Python may be downloaded from the following URL
https://www.python.org/downloads/

• You can choose the version and operating system.


• Version 3.4 onwards is recommended.

© NIIT Slide 13 of 38
Using Python
• Python can be used in interactive or scripting mode.
 Interactive mode allows one to quickly interact with Python on a
command line interface.
 Scripting mode allows to store several commands and constructs to
be saved as a program and then execute at one go.

© NIIT Slide 14 of 38
Demo Time

© NIIT Slide 15 of 38
Python identifiers
• Identifiers are names for entities
 variables
 functions
 classes
 objects
• Identifiers have the following rules
 Starts with [a-zA-Z_]
 Following character could also include digits [0-9]
 case-sensitive: Hello, hello and HELLO are three separate identifiers
 Only special character allowed is the underscore ( _ )
© NIIT Slide 16 of 38
Reserve Words

© NIIT Slide 17 of 38
Lines and Indentation

• Python does not use braces({}) to indicate blocks of code for class and
function definitions or flow control.
• Blocks of code are denoted by line indentation, which is rigidly
enforced.
• The number of spaces in the indentation is variable, but all statements
within the block must be indented the same amount.

© NIIT Slide 18 of 38
Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.

• Single line comment : use # before comment statement


• Multi line comment : enclose statements between triple quotes
• Eg.
“””
..…..
…….
“””
© NIIT Slide 19 of 38
Python Variables

• Variables are containers for storing data values.


• Unlike other programming languages, Python has no command for
declaring a variable.
• A variable is created the moment you first assign a value to it.
• Python allows you to assign values to multiple variables in one line
Example
x = 5
y = "John"

© NIIT Slide 20 of 38
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
© NIIT Slide 21 of 38
Python Arithmetic Operators

Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponentiation
// Floor division

© NIIT Slide 22 of 38
Python Assignment Operators
Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3
© NIIT
x = x << 3 Slide 23 of 38
Python Comparison Operators

Operator Name Example

== Equal x == y

!= Not equal x != y

>  Greater than x>y

<  Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

© NIIT Slide 24 of 38
Python Logical Operators

Operator Description Example

and  Returns True if both statements are x < 5 and  x < 10


true

or Returns True if one of the x < 5 or x < 4


statements is true

not Reverse the result, returns False if not(x < 5 and x < 10)
the result is true

© NIIT Slide 25 of 38
Python Identity Operators
Operator Description Example

is  Returns true if both variables x is y


are the same object

is not Returns true if both variables x is not y


are not the same object

© NIIT Slide 26 of 38
Python Membership Operators

Operator Description Example

in  Returns True if a sequence with the specified x in y


value is present in the object

not in Returns True if a sequence with the specified x not in y


value is not present in the object

© NIIT Slide 27 of 38
Python Bitwise Operators

Operator Name Description

&  AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

 ^ XOR Sets each bit to 1 if only one of two bits is 1

~  NOT Inverts all the bits

<<  Zero fill left Shift left by pushing zeros in from the right and let the
shift leftmost bits fall off
>>  Signed right Shift right by pushing copies of the leftmost bit in from the
shift left, and let the rightmost bits fall off
© NIIT Slide 28 of 38
Precedence
• In expressions having multiple operators, Python uses the PEMDAS precedence
resolution order:
 Parentheses
 Exponentiation
 Multiplication
 Division
 Addition
 Subtraction
• Python supports mixed type math. The final answer will be of the most complex type.
© NIIT Slide 29 of 38
Demo Time
© NIIT Slide 30 of 38
Data Types
Python has six standard data types −
• Numbers
• String
• Set
• List
• Tuple
• Dictionary
© NIIT Slide 31 of 38
Numbers
Python supports four different numerical types −
• int (signed integers)
• long (long integers, they can also be represented in
octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
• Boolean(True or False)

© NIIT Slide 32 of 38
int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECB 32.3+e18 .876j


FBAEl

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j

© NIIT Slide 33 of 38
String
• Strings in Python are identified as a contiguous set of characters represented in
the quotation marks. Python allows for either pairs of single or double quotes.
• Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes
starting at 0 in the beginning of the string and working their way from -1 at the
end.
• The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
• eg.
>>>name=“Munish”
>>>language=“Python”

© NIIT Slide 34 of 38
Some builtin string methods
• .capitalize()
 python -> Python
• .count(str, begin=0, end=len(str))
 Count number of occurrences of substring str inside this string
• .find(str, begin=0, end=len(str))
 Find first occurrence of str in string

© NIIT Slide 35 of 38
Demonstration
• Using string operations and methods in interactive interface
 concatenation
 repetition
 find
 count

© NIIT Slide 36 of 38
Boolean

Flag=True
Status=False

© NIIT Slide 37 of 38
Basic constructs
• Conditions
 if condition: statement
 if condition: block
 else
 elif
• Loops
 for
 while

© NIIT Slide 38 of 38
Constructs : Conditionals
if <condition> : statement or a block

if a<10 : print(“a is less than 10”)

if b<a :
print(“less”)
print(“value of a is ” ,a)
print(“value of b is ” ,b)

© NIIT Slide 39 of 38
Constructs : Conditionals
if a<10 : print(“a is less than 10”)
else : print(“a is not less than 10”)

if b<a :
print(“less”)
print(“value of a is ” ,a)
print(“value of b is ” ,b)
else :
print(“Was not less”)

© NIIT Slide 40 of 38
Constructs : Conditionals
if a<10 :
print(“hello”)
elif a<5 :
print(“world”)

© NIIT Slide 41 of 38
Constructs : Conditionals
A ternary usage of if statement

print(“hello”) if a<10 else print(“world”)

© NIIT Slide 42 of 38
Constructs : Conditionals
Keywords related to conditional statements
if
else
elif

© NIIT Slide 43 of 38
Constructs : Iterations
while <condition>:
block

All the statements of the block are executed if the condition is true.
At end of the block the condition is re-evaluated.
If condition is still true, then the block is repeated.

© NIIT Slide 44 of 38
Constructs : Iterations
a=0
while a<10:
print(a)
a=a+1

This would display number 0 to 9.

© NIIT Slide 45 of 38
Constructs : Iterations
for <variable> in <iterable>:
block

The for loop iterates over an iterable, assigning subsequence elements


of the sequence to the variable and then executing the block.

ctr=0
for x in “hello world”: # String is an iterable sequence of characters
if x == “o” : ctr=ctr+1
print(ctr)
© NIIT Slide 46 of 38
Constructs : Iterations
for x in range(10):
print(x)

The range function generates a sequence of number 0 to 9.

© NIIT Slide 47 of 38
Constructs : Iterations
range(10) # generates 0 to 9
range(3, 10) # generates 3, 4, 5, 6, 7, 8, 9
So the range function does not include the upper limiting value.
range(3, 10, 2) # The third parameter is the stride or increment
# default stride is 1
# 3, 5, 7, 9

© NIIT Slide 48 of 38
Constructs : Iterations
• break statement terminates a loop.
• continue statement re-evaluates condition and restarts the block if true.
• else block in loops gets executed if the loop never got started.
a=10
while a<10:
print(a)
a=a+1
else:
print(“while loop never got started”)
© NIIT Slide 49 of 38
Taking input from the keyboard
x=input()
x=input(“Enter a value”)

Value entered would be read as a string.


If you want it to be used as a number you can convert it.

x=input(“Enter a value”)
y=int(x) # converts to integer
or
x=int(input(“Enter a value”)) # gets a number into x
© NIIT Slide 50 of 38
Getting down to programming
• Writing a python script
• Executing a python script
• Debugging

• Displaying results – the print function


 print(a)
 print(“This is the result ”,a)
 print(a, b, c)

© NIIT Slide 51 of 38
Running a python script
• Python code saved in file with .py extension
• On a shell prompt type: python myfile.py
• Edit, save, run, repeat

© NIIT Slide 52 of 38
Sample programs to try
• Count digits in a number
• Find out how many times a particular digit occurs in a number
• Display the Fibonacci series up to a max limit
• Display first n numbers of a Fibonacci series
• Calculate the factorial of a number n
• A program that generates all prime numbers between x and y

© NIIT Slide 53 of 38
Lab Exercises
1. Generate the first 10 even numbers.
2. Input a number and check if it is prime or not.
3. Input 10 numbers and display the smallest and largest of them.
4. Input 10 numbers and display the sum and average.
Explore the internet and find out how to display a floating number to required
decimal places.
5. Input a number and calculate its factorial.

Additionally try out the questions discussed in the lecture session as


same or alternative methods.

© NIIT Slide 54 of 38

You might also like