KEMBAR78
Introduction | PDF | Data Type | Integer (Computer Science)
0% found this document useful (0 votes)
40 views49 pages

Introduction

The document discusses various programming languages and then provides an overview of Python including running Python code, data types, input/output, control flow, functions, and uses of Python in scientific computing. It then demonstrates Hello World in Python, describes the Python interpreter, variables, objects, numbers, strings, string methods, formatting, and lists.

Uploaded by

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

Introduction

The document discusses various programming languages and then provides an overview of Python including running Python code, data types, input/output, control flow, functions, and uses of Python in scientific computing. It then demonstrates Hello World in Python, describes the Python interpreter, variables, objects, numbers, strings, string methods, formatting, and lists.

Uploaded by

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

Which of these languages do you know?

• C or C++
• Java
• Perl
• Scheme
• Fortran
• Python
• Matlab
Presentation Overview

• Running Python and Output


• Data Types
• Input and File I/O
• Control Flow
• Functions
• Then, Why Python in Scientific Computation?
• Binary distributions Scientific Python
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 Overview

From Learning Python, 2nd Edition:

• Programs are composed of modules


• Modules contain statements
• Statements contain expressions
• Expressions create and process objects
The Python Interpreter

•Python is an interpreted >>> 3 + 7


language 10
•The interpreter provides an >>> 3 < 15
interactive environment to True
play with the language >>> 'print me'
'print me'
•Results of expressions are >>> print 'print me'
printed on the screen print me
>>>
The print Statement

•Elements separated by
commas print with a space
>>> print 'hello'
between them
hello
•A comma at the end of the
>>> print 'hello', 'there'
statement (print ‘hello’,) will
hello there
not print a newline character
Documentation

The ‘#’ starts a line comment

>>> 'this will print'


'this will print'
>>> #'this will not'
>>>
Variables
• Are not declared, just assigned
• The variable is created the first time you assign it
a value
• Are references to objects
• Type information is with the object, not the
reference
• Everything in Python is an object
Everything is an object

• Everything means
>>> x = 7
everything, including
>>> x
functions and classes 7
(more on this later!) >>> x = 'hello'
• Data type is a property >>> x
of the object and not of 'hello'
>>>
the variable
Numbers: Integers
• Integer – the equivalent of
a C long >>> 132224
• Long Integer – an 132224
unbounded integer value. >>> 132323 ** 2
17509376329L
>>>
Numbers: Floating Point
• int(x) converts x to an >>> 1.23232
integer 1.2323200000000001
>>> print 1.23232
• float(x) converts x to a 1.23232
floating point >>> 1.3E7
• The interpreter shows 13000000.0
>>> int(2.0)
a lot of digits
2
>>> float(2)
2.0
Numbers: Complex
• Built into Python
• Same operations are >>> x = 3 + 2j
supported as integer and >>> y = -1j
>>> x + y
float
(3+1j)
>>> x * y
(2-3j)
Numbers are immutable
x 4.5
>>> x = 4.5
>>> y = x y
>>> y += 3
x 4.5
>>> x
4.5 y 7.5
>>> y
7.5
String Literals

• Strings are immutable


• There is no char type like >>> x = 'hello'
in C++ or Java >>> x = x + ' there'
>>> x
• + is overloaded to do 'hello there'
concatenation
String Literals: Many Kinds
• 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 :)
String Literals contd…
• When don’t want characters prefaced by \ to be
interpreted as special characters,
>>> print('C:\some\name') # here \n means
newline!
C:\some
ame

>>> print(r'C:\some\name') # note the r before the quote C:\


some\name
• Strings can be concatenated (glued together) with
the + operator, and repeated with *:
>>> # 6 times ‘k', followed by ‘kiran‘
>>> 5 * 'k '+'kiran'
'k k k k k kiran'
String Literals contd…
• Two or more string literals next to each other are
automatically concatenated.
>>> 'Orchid' 'Solapur'
'OrchidSolapur'
• This only works with two literals though, not with
variables or expressions:
>>> college='orchid '
>>> college 'Solapur'
SyntaxError: invalid syntax
• To concatenate variables or a variable and a literal, use +:
>>> college+'Solapur'
'orchidSolapur'
• Strings can be indexed with positive and negative
indexes:
>>> college[4] >>> college[-4]
'i' 'c'
String Literals contd…
• slicing is also supported on strings
>>> college[0:4]
'orch'
• the start is always included, and the end always excluded
which makes sure that s[:i] + s[i:] is always equal to s:
>>> college[:3]+college[3:]
'orchid'
• an omitted first index defaults to zero, an omitted second
index defaults to the size of the string being sliced.
>>> college[:5]
'orchi‘

>>> college[2:]
'chid‘

>>> college[:-3]
'orc'
String Methods
1. str.capitalize() 12. A) keyword.iskeyword(s)
2. str.casefold() B) keyword.kwlist
3. str.center(width[, fillchar]) 13. Str.islower()
4. str.count(sub[, start[, end]]) 14. str.isnumeric()
5. str.endswith(suffix[, start[, end]]) 15. str.isspace()
6. str.find(sub[, start[, end]]) 16. str.istitle()
7. str.index(sub[, start[, end]]) 17. str.isupper()
8. str.isalnum() 18. str.join(iterable)
9. str.isalpha() 19. str.ljust(width[, fillchar])
10. str.isdecimal() 20. str.lower()
11. str.isdigit() 21. str.lstrip([chars])
12. str.isidentifier() 22. str.partition(sep)
String Methods
23. str.replace(old, new[, count]) 35. str.zfill(width)
24. str.rfind(sub[, start[, end]]) 36. str(x) Converts object x to a string
25. str.rindex(sub[, start[, end]]) representation.
26. str.rjust(width[, fillchar]) 37. len(str)
27. str.rpartition(sep)
28. str.rsplit(sep=None, maxsplit=-1)
29. str.rstrip([chars])
30. str.split(sep=None, maxsplit=-1)
31. str.startswith(prefix[, start[, end]])
32. str.swapcase()
33. str.title()
34. str.upper()
String Formatting
• Similar to C’s printf
• <formatted string> % <elements to insert>
• Can usually just use %s for everything, it will
convert the object to its String representation.
>>> "One, %d, three" % 2
'One, 2, three'
>>> "%d, two, %s" % (1,3)
'1, two, 3'
>>> "%s two %s" % (1, 'three')
'1 two three'
>>>
Data Types
Python has five standard data types
• Numbers:
 Integer (int & bool)
 Float
 Complex
• String
• List
• Tuple
• Dictionary
Numeric operators and functions for
integer
Integer conversion functions
Collection data types: Lists
• Ordered collection of data
>>> x = [1,'hello', (3 + 2j)]
• Data can be of different types >>> x
• Lists are mutable [1, 'hello', (3+2j)]
• Issues with shared references >>> x[2]
and mutability (3+2j)
• Same subset operations as >>> x[0:2]
Strings [1, 'hello']
• Lists can be compared using the
standard comparison
operators(<, <=, ==, !=, >=, >)
Lists: Modifying Content
• x[i] = a reassigns the >>> x = [1,2,3]
ith element to the value >>> y = x
a >>> x[1] = 15
>>> x
• Since x and y point to [1, 15, 3]
the same list object, >>> y
both are changed [1, 15, 3]

>>> x.append(12)
• The method append >>> y
also modifies the list [1, 15, 3, 12]
Lists: Modifying Contents
>>> x = [1,2,3]
• The method >>> y = x
append modifies >>> z = x.append(12)
the list and returns >>> z == None
None True
• List addition (+) >>> y
returns a new list [1, 2, 3, 12]
>>> x = x + [9,10]
>>> x
[1, 2, 3, 12, 9, 10]
>>> y
[1, 2, 3, 12]
>>>
Lists can be created in
following ways:
• By calling a function list()
 An empty list is created by not passing any argument
 with a list argument it returns a shallow copy of the
argument
 with any other argument it attempts to convert the given
object to a list
• without using the list() function
 An empty list is created using empty brackets, []
 A list of one or more items can be created by using a
comma separated sequence of items inside bracket
Some important methods for list
are:
• The method len returns the
>>> list1 = [1,2,3,4]
number of items in the list
>>> len(list1)
4
• Lists can be nested and can >>> list1=[1,2,3,4]
create list containing other >>> list2=[7,8,9]
lists >>> list3=[list1,list2]
>>> list3
[[1, 2, 3, 4], [7, 8, 9]]

>>> list3[0]
[1, 2, 3, 4]
>>> list3[0][2]
3
Methods for list are:
Tuples
• Tuples are immutable
versions of lists
• One strange point is the >>> x = (1,2,3)
format to make a tuple with >>> x[1:]
(2, 3)
one element:
>>> y = (2,)
‘,’ is needed to differentiate >>> y
from the mathematical (2,)
expression (2) >>>
Tuple can be created in two
fashion:
• By calling tuple()
• By including elements in “( )” with commas

>>> t1=tuple() >>> t2=()


>>> t1 >>> t2
() ()
>>> type(t1) >>> type(t2)
<class 'tuple'> <class 'tuple'>
• Tuples support the same slicing and striding
syntax as strings
Tuple supports two methods:
• t.count(x): which returns the number of times
object x occurs in tuple t.
• t.index(x): which returns the index position of
the leftmost occurrence of object x in tuple t or
raises a ValueError exception if there is no x in the
tuple.
Tuple can be used with:
• + (concatenation) >>> t1=("Orchid","Engg")
>>>t2=("Solapur","Maharashtra")
>>> t1+t2
('Orchid', 'Engg', 'Solapur', 'Maharashtra‘)
• * (replication) >>> t1*3
('Orchid', 'Engg', 'Orchid', 'Engg', 'Orchid', 'Engg')

>>> t1[1]
• [] (slice) 'Engg‘
>>> eyes = ("brown", "hazel", "amber", "green",
"blue", "gray")
>>> colors = (hair, eyes)
>>> colors[1][3:-1]
('green', 'blue‘)
• with in and not in >>> "Engg" in t1
True
to test for
>>> "Solapur" not in t2
membership. False
>>> "Solapur" not in t1
True
Tuples can be compared with:
• Tuples can be >>> t1=(2,4,6,8)
compared using >>> t2=(1,3,5,7)
>>> t3=(2,4,6,8)
the standard >>> t1==t3
comparison True
>>> t1>=t2
operators (<, <=,
True
==, !=, >=, >), >>> t1>=t3
with the True
>>> t1!=t2
comparisons
True
being applied >>> t1!=t3
item by item False
Tuples can be used with += and *= :
• The += and *= >>> t1=("a","b","c","d")
>>> id(t1)
augmented assignment 50625392
operators can be used
>>> t2=("e","f","g","h")
even though tuples are >>> id(t2)
immutable—behind the 50625488
scenes Python creates a
>>> t1
new tuple to hold the ('a', 'b', 'c', 'd')
result and sets the left- >>> t2
('e', 'f', 'g', 'h')
hand object reference to
refer to it;the same >>> t1+=t2
>>> id(t1)
technique is used when 50346544
these operatorsare >>> t1
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
applied to strings.
Dictionaries
• A dictionary is an unordered collection of zero or more key–
value pairs whose keys are object references that refer to
hashable objects, and whose values are object references
referring to objects of any type
• Dictionaries are mutable
• but since they are unordered they have no notion of index
position and so cannot be sliced or strided.

>>> d = {1 : 'hello', 'two' : 42, 'blah' : [1,2,3]}


>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['blah']
[1, 2, 3]
Dictionaries cntd…
• Here are some examples to illustrate the various syntaxes—
they all produce the same dictionary:
>>> d1 = dict({"id": 1948, "name": "Washer", "size": 3})
>>> d1
{'id': 1948, 'name': 'Washer', 'size': 3}
>>> d2 = dict(id=1948, name="Washer", size=3)
>>> d2
{'id': 1948, 'name': 'Washer', 'size': 3}
>>> d3 = dict([("id", 1948), ("name", "Washer"), ("size", 3)])
>>> d3
{'id': 1948, 'name': 'Washer', 'size': 3}
>>> d4 = dict(zip(("id", "name", "size"), (1948, "Washer", 3)))
>>> d4
{'id': 1948, 'name': 'Washer', 'size': 3}
>>> d5 = {"id": 1948, "name": "Washer", "size": 3}
>>> d5
{'id': 1948, 'name': 'Washer', 'size': 3}
Dictionaries: Add/Modify
• Entries can be changed by assigning to that entry
>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['two'] = 99
>>> d
{1: 'hello', 'two': 99, 'blah': [1, 2, 3]}
• Assigning to a key that does not exist adds an entry
>>> d[7] = 'new entry'
>>> d
{1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]}
Dictionaries: Deleting Elements
• The del method deletes an element from a dictionary

>>> d
{1: 'hello', 2: 'there', 10: 'world'}
>>> del(d[2])
>>> d
{1: 'hello', 10: 'world'}
Dictionaries: Methods
Copying Dictionaries and Lists
• The built-in list >>> l1 = [1] >>> d = {1 : 10}
function will >>> l2 = list(l1) >>> d2 = d.copy()
copy a list >>> l1[0] = 22 >>> d[1] = 22
>>> l1 >>> d
• The dictionary [22] {1: 22}
has a method >>> l2 >>> d2
called copy [1] {1: 10}
Data Type Summary

• Lists, Tuples, and Dictionaries can store any type


(including other lists, tuples, and dictionaries!)
• Only lists and dictionaries are mutable
• All variables are references
Data Type Summary

• Integers: 2323, 3234L


• Floating Point: 32.3, 3.1E2
• Complex: 3 + 2j, 1j
• Lists: l = [ 1,2,3]
• Tuples: t = (1,2,3)
• Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}
Sets
• A set type is a collection data type that supports the membership operator
(in), the size function (len()), and is iterable.
• A set is an unordered collection of zero or more object references that refer
to hashable objects.
• Sets can be created using set( ),
• E.g.
s=set("Hello")
>>> s
{'e', 'o', 'l', 'H‘}

>>> s1=set(["Python","c++","C","Python","Java"])
>>> s1
{'C', 'c++', 'Python', 'Java'}

>>> cities = set(("Delhi", "Bangalore", "Chennai", "Delhi", "Kolkata", "Chennai"))


>>> cities
{'Bangalore', 'Chennai', 'Delhi', 'Kolkata'}
Sets contd…
• Python provides two built-in set types:
a) the mutable set type
b) the immutable frozenset

>>> x = set(["Perl", "Python", >>> x = frozenset(["Perl", "Python",


"Java"]) "Java"])
>>> x >>> x
{'Java', 'Perl', 'Python'} frozenset({'Java', 'Perl', 'Python'})

x.remove("Perl") >>> x.add("C")


>>> x Traceback (most recent call last):
{'Java', 'Python'} File "<pyshell#40>", line 1, in
<module>
x.add("Perl") x.add("C")
>>> x AttributeError: 'frozenset' object has
{'Java', 'Perl', 'Python'} no attribute 'add'
Sets: Methods

* This method and its operator (if it has one) can also be used with frozensets.
Some solved examples for methods of sets
>>> s1=set(["Hello","World","Welcome","to","Python"])
>>> s1
{'World', 'Hello', 'Python', 'to', 'Welcome'}
>>> s2=s1.copy()
>>> s2
{'World', 'Hello', 'Python', 'to', 'Welcome'}

>>> s1.difference(s2)
set()

>>> s3=set(["Hello","Orchid","Welcome","to","Python"])
>>> s3
{'Orchid', 'Hello', 'Python', 'to', 'Welcome'}
>>> s1.difference(s3)
{'World'}
>>> s3.difference(s1)
{'Orchid'}
Some solved examples for methods of sets
>>> s1.difference_update(s3)
>>> s1
{'Wold'}
>>> s3
{'Orchid', 'Hello', 'Python', 'to', 'Welcome'}

>>> s3.discard("Hello")
>>> s3
{'Orchid', 'Python', 'to', 'Welcome'}

>>> s2=set(['Orchid', 'Python', 'to', 'Welcome','Hello'])


>>> s2
{'Orchid', 'Hello', 'Python', 'to', 'Welcome'}

>>> s2.intersection(s3)
{'Orchid', 'Welcome', 'Python', 'to‘}

You might also like