Sei sulla pagina 1di 38

Python

Introduction
Objectives
By the end of this course, you should be able to:
• Assess the importance of Python
• Get started with the Python environment
• Python interactive mode and scripting interface
• Understand variables, constructs and indentation
• List basic operations on numbers and strings
• Run a python script
What is Python?
• A very high level, object-oriented language
• Easy to read and program with
• Similar to Perl but with powerful typing and object-oriented features
• Scripting Language
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
About Python
• Invented in the Netherlands in the early ‘90s by Guido van Rossum.
• Name after ‘Monty Python’, a comedy group, depicting its ‘fun’
philosophy
• 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
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
Traditional Uses of Python
• Embedded Scripting
• Image processing
• Artificial intelligence
• GUI’s
• Database Programming
• Internet Scripting
• System Administration
• Automation
Uses of Python in Data Analytics
• Weather Forecasting
• Scientific analysis
• Ad targetting
• Risk Management Analysis
• Natural Language Processing and Generation
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+


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
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


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 executed at one go

• Demonstration of both of these modes follows:


Comments , Literals, Variables
• Any statement with a leading ‘#’ is treated as a comment
• Literal Constants : Any number or a string value
• Variable : A user defined container that can hold a literal value
a=10 # variable a contains 10
b=‘Hello’ # Storing a string ‘Hello’ in variable b
c=“World” # Stores a string ‘World’ in variable c
• Variable : A user defined container that can hold a literal value
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 ( _ )
Operations on numbers
• All basic arithmetic operations are supported
• Addition(+), subtraction(-), multiplication(*), Division(/)
• Modulo (%)
• Exponentiation (**)
• Integer division ( // )
• Logical Operators
• All 6 comparison operations are available(==, !=, <, <=, >, >=)
• To combine logical expressions, use : and not or
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
Demonstration
• Mathematical operations in the interactive python interface
• Simple integer calculation
• Calculations involving brackets and floats
Strings - Basics
•Strings are ordered blocks of text
•Written inside quotes ( both single and double quotes can be
used )
•Basic Operations with strings
•Concatenation: ‘hello’ + ‘world’ will result in ‘helloworld’
•Repetition: ‘hello’ * 3 = ‘hellohellohello’
•Indexing
•Indexes start at 0
•s[i] fetches character at index i
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
Demonstration
• Using string operations and methods in interactive interface
• concatenation
• repetition
• find
• count
Indentation & Blocks
• Indentation
• Leading whitespace to shift some line starts to the right of others
• Is used to determine grouping of statement in Python
• Defines a ‘statement block’
• Blocks
• Start with a statement ending with ‘:’
• All lines following it are indented forward
• De-indenting to the previous level closes the block
• Some editors, IDE’s automatically take care of indentation
• Repeat: there are no curly braces { } in python for defining blocks
Basic constructs
• Conditions
• if condition: statement
• if condition: block
• else
• elif
• Loops
• for
• while
• break
• continue
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)
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”)
Constructs : Conditionals
if a<10:
print(“hello”)
elif a<5:
print(“world”)
Constructs : Conditionals
A ternary usage of if statement

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


Constructs : Conditionals
Keywords related to conditional statements
if
else
elif
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
Constructs : Iterations
a=0
while a<10:
print(a)
a=a+1

This would display number 0 to 9


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)
Constructs : Iterations
for x in range(10):
print(x)

range function generate a sequence of number 0 to 9


Constructs : Iterations
range(10) # generates 0 to 9
range(3,10) # generates 3,4,5,6,7,8,9
So range function does not include the upper limiting value
range(3,10,2) # The third parameter is the stride or increment
# default stride was 1
# 3, 5 , 7 , 9
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”)
Taking input from the keyboard
x=input()
x=input(“Enter a value”)
Value entered would be read as a string.
If we want it to be used as a number we 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
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)
Running a python script
• Python code saved in file with .py extension
• On a shell prompt type: python myfile.py
• Edit, save, run, repeat
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
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.

Potrebbero piacerti anche