Sunteți pe pagina 1din 43

Python

Programming
Language
Python Overview
Python is a high level scripting language with object
oriented features and it is a interpreted language.

Python programs can be written using any text editor


and should have the extension .py.

Python programs starts with #!/usr/bin/python at first


line.

Python programs can be run from a command prompt


by typing python file.py.

There are no braces { } or semicolons ; in python.


Instead of braces, blocks are identified by having the
indentation.
Hello World
•Open a terminal window and type “python”
•If on Windows open a Python IDE like IDLE
•At the prompt type „hello world!‟

>>> 'hello world!'


'hello world!'
Python Interpreter
•Python is an interpreted language
•The interpreter provides an interactive environment to
play with the language
•Results of expressions are printed on the screen

>>> 3 + 7
10
>>> 3 < 15
True
>>> 'print me'
'print me'
>>> print 'print me'
print me
>>>
print Statement
•Elements separated by commas print with a space
between them

•A comma at the end of the statement (print „hello‟,) will not


print a newline character

>>> print 'hello'


hello
>>> print 'hello', 'there'
hello there
Documentation
The „#‟ starts a line comment

>>> 'this will print'


'this will print'
>>> #'this will not'
>>>
Variables
• Variables in Python follow the standard nomenclature of an
alphanumeric name beginning in a letter or underscore. Variable
names are case sensitive.

• Are not declared, just assigned

• Is created when you assign it a value for first time

• Are references to objects

• Type information is with the object, not the reference

• Everything in Python is an object


Variables
Variable Scope: Most variables in Python are local in scope to their own
function or class. For instance if you define a = 1 within a function,
then a will be available within that entire function but will be undefined in
the main program that calls the function. Variables defined within the main
program are accessible to the main program but not within functions
called by the main program.

Global Variables: Global variables, however, can be declared with


the global keyword.
a=1
b=2
def Sum():
global a, b
b=a+b
Sum()
print(b)
Everything is an object
• Everything means everything, including functions and
classes (more on this later!)
• Data type is a property of the object and not of the
variable

>>> x = 7
>>> x
7
>>> x = 'hello'
>>> x
'hello'
>>>
Statements and Expressions
print: Output strings, integers, or any other datatype.

The assignment statement: Assigns a value to a variable.

input: Allow the user to input numbers or booleans.


WARNING: input accepts your input as a command and thus can
be unsafe.

raw_input: Allow the user to input strings. If you want a number,


you can use the int or float functions to convert from a string.

import: Import a module into Python. Can be used as import


math and all functions in math can then be called
by math.sin(1.57) etc or alternatively from math import sin and
then the sine function can be called with sin(1.57).
Statements and Expressions
print: Output strings, integers, or any other datatype.
Some Examples
The assignment statement: Assigns a value to a variable.
a=b=5 #The assignment statement
input: Allow the user to input numbers or booleans.
WARNING:
b += 1 input accepts#post-increment
your input as a command and thus can
be unsafe.
c = "test“ # Assigning a string
raw_input: Allow the user to input strings. If you want a number,
youimport
can use the int or float#Import
os,math functions
thetoosconvert frommodules
and math a string.
from math import * #Imports all functions from
import: Import a module into Python.
the math Can be used as import
module
math and all functions in math can then be called
by math.sin(1.57) etc or alternatively from math import sin and
then the sine function can be called with sin(1.57).
Operators
Arithmatic : +, -, *, /, and % (modulus)
Comparison : ==, !=, <, >, <=, >=
Logical : and, or, not
Exponentiation : **
Execution : os.system('ls -l‘) #Requires import os
STRINGS
String Operators:
Strings can be specified using single quotes or double quotes.
Concatenation is done with the + operator.
Converting to numbers is done with the casting operations:
x = 1 + float(10.5) # $x=11.5, float
x = 4 - int("3") # $x=1, int
You can convert to a string with the str casting function: s = str(3.5)
name = „Lee‟
age = “ „s age is “
print name + age + str(24)

Comparing Strings:
Strings can be compared with the standard operators listed
==, !=, <, >, <=, and >=.
STRINGS
• + is overloaded to do concatenation

>>> x = 'hello'
>>> x = x + ' there'
>>> x
'hello there'
STRINGS
• Can use single or double quotes, and three double quotes for a
multi-line string

>>> 'I am a string'


'I am a string'

>>> "So am I!"


'So am I!'

>>> s = """And me too!


though I am much longer
than the others :)"""
'And me too!\nthough I am much longer\nthan the others :)„

>>> print s
And me too!
though I am much longer
than the others :)„
STRINGS
Strings in Python can be subscripted just like an array: s[4] = ‘4'.

>>> s = '012345'
>>> s[3]
'3'
>>> s[1:4]
'123'
>>> s[2:]
'2345'
>>> s[:4]
'0123'
STRINGS
• len(String) – returns the number of characters in the
String

• str(Object) – returns a String representation of the Object

>>> s = „012345‟
>>> len(s)
6
>>> str(10.3)
'10.3'
LISTS
• Arrays in basic Python are actually lists that can contain
mixed datatypes.
• Creating lists: A list can be created by defining it with [ ].
A numbered list can also be created with the range
function which takes start and stop values and an
increment.

>>> x = [1,'hello', (3 + 2j)] list = [2, 4, 7, 9]


>>> x
[1, 'hello', (3+2j)] list2 = [3, "test", True, 7.4]
>>> x[2]
(3+2j) a = range(5) #a = [0,1,2,3,4]
>>> x[0:2]
[1, 'hello„]
LISTS : Modifying Content
• x[i] = a re-assigns the ith element to the value a
• Since x and y point to the same list object, both are
changed
• The method append also modifies the list
>>> x = [1,2,3]
>>> y = x
>>> x[1] = 15
>>> x
[1, 15, 3]
>>> y
[1, 15, 3]
>>> x.append(12)
>>> y
[1, 15, 3, 12]
LISTS : Modifying Content
• The method append modifies >>> x = [1,2,3]
the list and returns None >>> y = x
• List addition (+) returns a new >>> z = x.append(12)
list >>> z == None
True
>>> y
[1, 2, 3, 12]
>>> x = x + [9,10]
>>> x
[1, 2, 3, 12, 9, 10]
>>> y
[1, 2, 3, 12]
>>>
INPUTS
• The raw_input(string) method returns a line of user
input as a string
• The parameter is used as a prompt
• The string can be converted by using the conversion
methods int(string), float(string), etc.
INPUTS
print "What's your name?"
name = raw_input("> ")

print "What year were you born?"


birthyear = int(raw_input("> "))

print "Hi %s! You are %d years old!" % (name, 2017 - birthyear)

~: python input.py
What's your name?
> Michael
What year were you born?
>1980
Hi Michael! You are 31 years old!
FILES

FILE INPUT

inflobj = open(„data‟, „r‟) Open the file „data‟ for input

S = inflobj.read() Read whole file into one String

Reads N bytes
S = inflobj.read(N)
(N >= 1)

L = inflobj.readlines() Returns a list of line strings


FILES

FILE OUTPUT

outflobj = open(„data‟, „w‟) Open the file „data‟ for writing

outflobj.write(S) Writes the string S to file

Writes each of the strings in list


outflobj.writelines(L)
L to file

outflobj.close() Closes the file


Booleans
• 0 and None are false
• Everything else is true
• True and False are aliases for 1 and 0 respectively
• Note that when None is returned the interpreter does not print anything

>>> True and False


False
>>> False or True
True
>>> 7 and 14
14
>>> None and 2
>>> None or 2
2
No Braces
• Python uses indentation instead of braces to determine the
scope of expressions

• All lines must be indented the same amount to be part of the


scope (or indented more if part of an inner scope)

• This forces the programmer to use proper indentation since


the indenting is part of the program!
Conditional Statements
If Statements

import math
x = 30
if x < 30 :
print “FALSE”
elif x > 30 :
print “FALSE”
else :
print “TRUE”
Control Statements
While Loops

x=1
while x < 10 :
print x
x=x+1
Control Statements
for Loops

for x in [1,7,13,2] : for x in range(5) :


print x print x
Control Statements

break Jumps out of the closest enclosing


loop

continue Jumps to the top of the closest


enclosing loop

pass Does nothing, empty statement


placeholder
FUNCTIONS

def max(x,y) :
if x < y :
return x
else :
return y
Functions are first class objects
• Can be assigned to a variable
• Can be passed as a parameter
• Can be returned from a function
• Functions are treated like any other variable in
Python, the def statement simply assigns a
function to a variable
Function names are like any variable
>>> x = 10
>>> x
10
• Functions are objects >>> def x () :
• The same reference ... print 'hello'
rules hold for them as >>> x
for other objects <function x at 0x619f0>
>>> x()
hello
>>> x = 'blah'
>>> x
'blah'
Functions as Parameters

def foo(f, a) : >>> from funcasparam import *


return f(a) >>> foo(bar, 3)
9
def bar(x) :
return x * x

funcasparam.py Note that the function foo takes two


parameters and applies the first as a
function with the second as its
parameter
Higher-Order Functions
map(func,seq) – for all i, applies func(seq[i]) and returns the
corresponding sequence of the calculated results.

>>> from highorder import *


def double(x): >>> lst = range(10)
return 2*x >>> lst
[0,1,2,3,4,5,6,7,8,9]
highorder.py >>> map(double,lst)
[0,2,4,6,8,10,12,14,16,18]
Higher-Order Functions

filter(boolfunc,seq) – returns a sequence containing all those items


in seq for which boolfunc is True.

>>> from highorder import *


def even(x): >>> lst = range(10)
return ((x%2 == 0) >>> lst
[0,1,2,3,4,5,6,7,8,9]
highorder.py >>> filter(even,lst)
[0,2,4,6,8]
Higher-Order Functions

reduce(func,seq) – applies func to the items of seq, from left to


right, two-at-time, to reduce the seq to a single value.

>>> from highorder import *


def plus(x,y): >>> lst = [‘h’,’e’,’l’,’l’,’o’]
return (x + y) >>> reduce(plus,lst)
‘hello’
highorder.py
Functions Inside Functions
• Since they are like any other object, you can have
functions inside functions

def foo (x,y) : >>> from funcinfunc import *


def bar (z) : >>> foo(2,3)
return z * 2 7
return bar(x) + y

funcinfunc.py
Functions Returning Functions
def foo (x) :
def bar(y) :
return x + y ~: python funcreturnfunc.py
return bar <function bar at 0x612b0>
# main 5
f = foo(3)
print f
print f(2)

funcreturnfunc.py
Parameters: Defaults
• Parameters can be
>>> def foo(x = 3) :
assigned default ... print x
values ...
• They are overridden if >>> foo()
a parameter is given 3
>>> foo(10)
for them 10
• The type of the default >>> foo('hello')
doesn’t limit the type hello
of a parameter
Parameters: Named
• Call by name >>> def foo (a,b,c) :
• Any positional ... print a, b, c
arguments must ...
come before >>> foo(c = 10, a = 2, b = 14)
2 14 10
named ones in a
>>> foo(3, c = 2, b = 19)
call 3 19 2
Anonymous Functions
• A lambda
expression returns a
>>> f = lambda x,y : x + y
function object >>> f(2,3)
• The body can only 5
be a simple >>> lst = ['one', lambda x : x * x, 3]
expression, not >>> lst[1](4)
complex statements 16
THANK YOU

S-ar putea să vă placă și