[go: up one dir, main page]

0% found this document useful (0 votes)
25 views46 pages

Mooc Seminar: Name Rajat Kushwaha St. Id 200211241 Section I'

The document discusses key aspects of Python including it being an interpreted, dynamically typed language with various built-in collection types. It covers basic data types, whitespace as a delimiter, comments, assignment, naming conventions, and sequence types like tuples, lists and strings.

Uploaded by

rajat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views46 pages

Mooc Seminar: Name Rajat Kushwaha St. Id 200211241 Section I'

The document discusses key aspects of Python including it being an interpreted, dynamically typed language with various built-in collection types. It covers basic data types, whitespace as a delimiter, comments, assignment, naming conventions, and sequence types like tuples, lists and strings.

Uploaded by

rajat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

MOOC SEMINAR

NameRAJAT KUSHWAHA
St. Id200211241
Section ‘I’

Submitted toMr.Rahul Chauhan


Python
 Interpreted language: work with an evaluator
for language expressions (like DrJava, but
more flexible)
 Dynamically typed: variables do not have a
predefined type
 Rich, built-in collection types:
 Lists
 Tuples
 Dictionaries (maps)
 Sets
 Concise
Why Python?
 Good example of scripting language
 “Pythonic” style is very concise
 Powerful but unobtrusive object system
 Every value is an object
 Powerful collection and iteration
abstractions
 Dynamic typing makes generics easy
Basic
Datatypes
 Integers (default for numbers)
z = 5 / 2 # Answer is 2, integer division.
 Floats
x = 3.456
 Strings
 Can use “” or ‘’ to specify.
“abc” ‘abc’ (Same thing.)
 Unmatched can occur within the string.
“matt’s”
 Use triple double-quotes for multi-line strings or strings than
contain both ‘ and “ inside of them:
“““a‘b“c”””
Whitespace
Whitespace is meaningful in Python: especially
indentation and placement of newlines.
 Use a newline to end a line of code.
 Use \ when must go to next line prematurely.
 No braces { } to mark blocks of code in
Python…
Use consistent indentation instead.
 The first line with less indentation is outside of the block.
 The first line with more indentation starts a nested block
 Often a colon appears at the start of a new block.
(E.g. for function and class definitions.)
Comments
 Start comments with # – the rest of line is ignored.
 Can include a “documentation string” as the first line of
any new function or class that you define.
 The development environment, debugger, and other tools
use it: it’s good style to include one.
def my_function(x, y):
“““This is the docstring. This
function does blah blah blah.”””
# The code would go here...
Assignmen
t Binding a variable in Python means setting a
name to hold a reference to some object.
 Assignment creates references, not copies (like Java)
 A variable is created the first time it appears on
the left side of an assignment expression:
x = 3
 An object is deleted (by the garbage collector)
once it becomes unreachable.
 Names in Python do not have an intrinsic
type.
Objects have types.
 Python determines the type of the reference
automatically based on what data is assigned to it.
Naming
Rules
 Names are case sensitive and cannot start with a number.
They can contain letters, numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
 There are some reserved words:
and, assert, break, class, continue, def, del,
elif, else, except, exec, finally, for, from,
global, if, import, in, is, lambda, not, or, pass,
print, raise, return, try, while
Sequence types:
Tuples, Lists, and Strings
Sequence Types
1. Tuple
 A simple immutable ordered sequence of items
 Immutable: a tuple cannot be modified once created....
 Items can be of mixed types, including collection types

2. Strings
 Immutable
 Conceptually very much like a tuple
 Regular strings use 8-bit characters. Unicode
strings use 2-byte characters. (All this
is changed in Python 3.)

3. List
 Mutable ordered sequence of items of mixed types
The ‘in’ Operator
 Boolean test whether a value is inside a collection
(often
called a container in Python:
>>> t = [1, 2, 4, 5]
>>> 3 in t
False
>>> 4 in t
True
>>> 4 not
in t
False
 For strings,
tests for
substrings
>>> a =
'abcde'
>>> 'c' in a
True
>>> 'cd' in
a
True
>>> 'ac' in a
False
The + Operator
 The + operator produces a new tuple, list, or string
whose
value is the concatenation of its arguments.
 Extends concatenation from strings to other types
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)

>>> [1, 2, 3] + [4, 5, 6]


[1, 2, 3, 4, 5, 6]

>>> “Hello” + “ ” + “World”


‘Hello World’
Mutability:
Tuples vs. Lists
Operations on Lists Only
1
>>> li = [1, 11, 3, 4, 5]

>>> li.append(‘a’) # Note the method syntax


>>> li
[1, 11, 3, 4, 5, ‘a’]

>>> li.insert(2, ‘i’)


>>>li
[1, 11, ‘i’, 3, 4, 5, ‘a’]
Tuples vs.
Lists
 Lists slower but more powerful than tuples.
 Lists can be modified, and they have lots of handy operations we
can perform on them.
 Tuples are immutable and have fewer features.

 To convert between tuples and lists use the list() and tuple()
functions:
li = list(tu)
tu = tuple(li)
Dictionaries: a mapping collection type
Dictionaries: Like maps in Java
 Dictionaries store a mapping between a set of keys
and a set of values.
 Keys can be any immutable type.
 Values can be any type
 Values and keys can be of different types in a single dictionary
 You can
 define
 modify
 view
 lookup
 delete
the key-value pairs in the dictionary.
Creating and accessing dictionaries

>>> d = {‘user’:‘bozo’, ‘pswd’:1234}

>>> d[‘user’]
‘bozo’

>>> d[‘pswd’]
1234

>>> d[‘bozo’]

Traceback
(innermost
last):
File
‘<interacti
ve input>’
line 1,
in ?
Updating Dictionaries
>>> d = {‘user’:‘bozo’, ‘pswd’:1234}

>>> d[‘user’] = ‘clown’


>>> d
{‘user’:‘clown’, ‘pswd’:1234}

 Keys must be unique.


 Assigning to an existing key replaces its value.

>>> d[‘id’] = 45
>>> d
{‘user’:‘clown’, ‘id’:45, ‘pswd’:1234}

 Dictionaries are unordered


 New entry might appear anywhere in the output.
 (Dictionaries work by hashing)
Removing dictionary entries
>>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34}

>>> del d[‘user’] # Remove one. Note that del is


# a function.
>>> d
{‘p’:1234, ‘i’:34}

>>> d.clear() # Remove all.


>>> d
{}
>>> a=[1,2]
>>> del a[1] # (del also works on lists)
>>> a
[1]
Useful Accessor Methods
>>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34}

>>> d.keys() # List of current keys


[‘user’, ‘p’, ‘i’]

>>> d.values() # List of current values.


[‘bozo’, 1234, 34]

>>> d.items() # List of item tuples.


[(‘user’,‘bozo’), (‘p’,1234), (‘i’,34)]
Boolean Expressions
Control Flow
if Statements (as expected)
if x == 3:
print "X equals 3."
elif x == 2:
print "X equals 2."
else:
print "X equals something else."
print "This is outside the ‘if’."

Note:
 Use of indentation for blocks
 Colon (:) after boolean expression
while Loops (as expected)
>>> x = 3
>>> while x < 5:
print x, "still in the loop"
x = x + 1
3 still in the loop
4 still in the loop
>>> x = 6
>>> while x < 5:
print x, "still in the loop"

>>>
break and continue
 You can use the keyword break inside a loop to
leave the while loop entirely.

 You can use the keyword continue inside a loop


to stop processing the current iteration of the
loop and immediately go on to the next one.
assert
 An assert statement will check to make sure that
something is true during the course of a program.
 If the condition if false, the program stops
 (more accurately: throws an exception)

assert(number_of_players < 5)

 Also found in Java; we just didn’t mention it!


For Loops
For loops and the range() function
 We often want to write a loop where the variables ranges
over some sequence of numbers. The range() function
returns a list of numbers from 0 up to but not including
the number we pass to it.

 range(5) returns [0,1,2,3,4]


 So we can say:

for x in range(5):
print x

 (There are several other forms of range() that


provide variants of this functionality…)
 xrange() returns an iterator that provides the same
functionality more efficiently
Generating Lists using
“List Comprehensions”
Nested List Comprehensions
 Since list comprehensions take a list as input and
produce a list as output, they are easily nested:
>>> li = [3, 2, 4, 1]
>>> [elem*2 for elem in
[item+1 for item in li] ]
[8, 6, 10, 4]

 The inner comprehension produces: [4, 3, 5, 2].


 So, the outer one produces: [8, 6, 10, 4].
For Loops / List
Comprehensions
 Python’s list comprehensions provide a natural
idiom that usually requires a for-loop in other
programming languages.
 As a result, Python code uses many fewer for-
loops

 Caveat! The keywords for and in also appear in


the syntax of list comprehensions, but this is a
totally different construction.
Functions in Python

(Methods later)
Defining Functions
Function definition begins with def Function name and its arguments.

def get_final_answer(filename):
"""Documentation String"""
line1
line2 Colon.
return total_counter
...

First line with less ‘return’ indicates the


indentation is considered to be value to be sent back to the caller.
outside of the function definition.

No declaration of types of arguments or result


Calling a
Function

>>> def myfun(x, y):


return x * y
>>> myfun(3, 4)
12
Functions without
returns
 All functions in Python have a return value
 even if no return line inside the code.
 Functions without a return return the special value
None.
 None is a special constant in the language.
 None is used like null in Java.
 None is also logically equivalent to False.
 The interpreter doesn’t print None
Function overloading?
No.
 There is no function overloading in Python.
 Unlike Java, a Python function is specified by its name alone
 The number, order, names, or types of its arguments cannot be
used to distinguish between two functions with the same name.
 Two different functions can’t have the same name, even if they
have different numbers of arguments.

 But operator overloading – overloading +, ==, -, etc. – is


possible using special methods on various classes (see later
slides)
Keyword Arguments
 Functions can be called with arguments out of order
 These arguments are specified in the call
 Keyword arguments can be used for a final subset of
the arguments.

>>> def myfun (a, b, c):


return a-b
>>> myfun(2, 1, 43)
1
>>> myfun(c=43, b=1, a=2)
1
>>> myfun(2, c=43, b=1)
1
Inheritance
Subclasses
 A class can extend the definition of another class
 Allows use (or extension ) of methods and attributes already
defined in the previous one.
 New class: subclass. Original: parent, ancestor or
superclass

 To define a subclass, put the name of the


superclass in parentheses after the subclass’s
name on the first line of the definition.

class ai_student(student):

 Python has no ‘extends’ keyword like Java.


 Multiple inheritance is supported.
Extendin
init
g
 Very similar to Java
 Commonly, the ancestor’s init
method
executedisin addition to new commands.
 Must be done explicitly
 You’ll often see something like this in the init
method of subclasses:
parentClass. init (self, x, y)

where parentClass is the name of the parent’s class.


Private Data and Methods
 Any attribute or method with two leading underscores in
its name (but none at the end) is private. It cannot be
accessed outside of that class.
 Note:
Names with two underscores at the beginning and the end are for
built-in methods or attributes for the class
 Note:
There is no ‘protected’ status in Python; so, subclasses would be
unable to access these private data either
String Operations
String Operations
 The string class provides a number of
methods for useful formatting operations:
>>> “hello”.upper()
‘HELLO’
 Check the Python documentation for
many other handy string
operations.
 Helpful hint: use <string>.strip()
to strip off final newlines from lines
read from files
String Formatting Operator:
%
 The operator % allows strings to be built out of many data
items in a “fill in the blanks” fashion.
 Allowscontrol of how the final string output will appear.
 For example, we could force a number to display with
a specific number of digits after the decimal point.

 Very similar to the sprintf command of C.


>>> x = “abc”
>>> y = 34
>>> “%s xyz %d” % (x, y)
‘abc xyz 34’

 The tuple following the % operator is used to fill in


the blanks in the original string marked with %s or
%d.
 Check Python documentation for details.
Built-In Members of Classes
 Classes contain many methods and attributes that are
included by Python even if you don’t define them explicitly.
 Most of these methods define automatic functionality triggered by
special operators or usage of that class.
 The built-in attributes define information that must be stored for
all
classes.
 All built-in members have double underscores around
their names: doc

You might also like