Вы находитесь на странице: 1из 35

Python

Python Types
Objectives
This session is about Python types:
• Basic Python Literals
• Numbers
• Strings
• More complex Python types
• Tuples
• Sets
• Lists
• Dictionaries
Numbers
• Integers – normal vs long
• Floats – 16 digits of precision
• Other numeric types include hexdecimal, octal, complex numbers

Operators and functions for numbers will work on all the above
Numbers : Assignments
a=10
a=b=c=20
a,b,c=10,20,30 # a=10 b=20 c=30
a,b,c=10,5.3,20 # Incorrect!

Assignment creates a variable of the type of RHS expression


Reassigning a variable simply creates a new variable
Numbers : Operators
+ - * /
% : Modulo division to get remainder : 5%2 gives 1
** : Power : 5**3 gives 125
// : Integer division to get quotient : 5//2 gives 2
a+=5 : implies a=a+5 ( We can combine with any operator as above )
parenthesis can be used to combine expressions
Precedence of operators is maintained in expressions
The result is of the most complex type across all operands
-a implies a unary operator. So if a was 5, then -a would be -5
Numbers : Functions
int( ) function can convert a literal into an integer value
a=int(5.3) # results in 5
a=int(“23”) # results in 23
a=int(“0x41”,16) # results in 65. Second parameter is base
# by default base is 10
a=int(“0100”,2) # results in 4. Binary string to integer.
Numbers : Functions
float( ) function can convert a literal into a float value
a=float(2) # results in 2.0
a=float(“2”) # results in 2.0
a=float(“2.3”) # results in 2.3
Numbers : Functions
chr( ) : Returns ascii character, chr(65) gives ‘A’
ord( ) : Returns ascii value, ord(‘A’) gives 65
abs( ) : Returns the absolute value, abs(-5) gives 5
Numbers : Functions
divmod() function returns the quotient as well as the remainder of division

q,r=divmod(5,3)

q becomes 1
r becomes 3

Functions in python can return multiple values in form of a sequence and the
returned values can be captured as above. The same can be implemented in
user defined functions as well.
Numbers : Functions
round( ) rounds off a float number to the digits needed.
a=round(4.3333,2) # returns 4.33
a=round(4.33) # returns 4
a=round(4.33,0) # returns 4.0

NOTE: Rounding is down to the nearest even value in case of midpoint


a=round(3.5) # returns 4
a=round(4.5) # returns 4, as 5 is not even
Strings
We have already been introduced to string literals.
a=“hello”
b=‘world’
c=“””hello
world”””

Triple quoted string can be a multi-line string


Both single or double quotes mean the same
Strings : Operators
+ : Used for concatenating strings
* : Used for replicating strings
in : To check for existence for example :
if “e” in “hello”:
print(“found”)
To iterate through the string for example :
for ch in “hello”:
print(ch)
Strings : Functions
There are several functions that work on strings such as :
len(“hello”) # returns the total number of characters in string
ord(“A”) # returns the ascii value of the character
Strings : Methods
s=“hello world”
x=s.count(‘o’) # gives us the total count of ‘o’ in the string
y=“This is his coat”.count(‘is’) # counts repetitions of string ‘is’
z=s.count(‘o’,2,5) # counts occurrences between index 2 and 5
a=s.capitalize() # will capitalize first character of the string
s.upper() s.lower() # returns the upper/lower converted string
s.lstrip() s.rstrip() s.strip() # strips white spaces

Note: The string methods would return a new string rather than modifying
the current one
Strings : Methods
Testing conditions in a string
s.startswith(“he”)
s.endswith(“run”)
s.isalnum(), s.isalpha(), s.isdigit(), s.isupper(), s.islower(), s.isspace()
Sequences
len( ) # gives the total number of elements in a sequence
in # can be used to check for existence of a value in the sequence
not in
[] # can be used to access an element or a slice of a sequence
# most sequences allow this operator
in # used to iterate through the sequence using for statement
Sequences - Example
A string is an ordered immutable sequence
s=“Hello”
len(s) # gives the total elements in the sequence/string
if ‘e’ in s: # use of in operator to check for existence
s[1] # accesses character ‘e’, indexes start from 0
s[1:4] # gives a slice of the sequence ‘ell’
for c in s: # iterates one character at a time from s into c
s[1]=‘c’ # not allowed, as string is immutable
Sequences
• Sequences are collection of items
• Sequence items can be of any python type
• Sequences may be ordered or unordered
• Ordered sequences maintain order of elements
• Unordered sequences do not guarantee order of elements
• Sequences may be mutable or immutable
• Mutable sequences allow elements to be modified
• Immutable sequences do not allow elements to be modified
Slices in detail
• A slice is a part of a sequence, returned as a new sequence
• The original sequence remains unchanged
• The [ ] brackets are used as a slice operator
b=a[1] # b is a single element slice of a
b=a[2:5] # slice is a[2],a[3] and a[4]
b=a[2:7:2] # slice is a[2], a[4], a[6] the index gap is 2 for elements
a[start,end,stride]
slice starts from the index start, does not include the index end, and stride is
the gap after which the elements are selected. By default stride is 1
Slices in detail
• Negative index implies from the end of the sequence
• Index -1 refers to the last element
• Index -2 refers to the second last element and so on

s=‘ABCDEF’
print(s[-2]) # would print ‘E’
print(s[2:-2]) # prints ‘CD’ as the ending index is not included
Slices in detail
• Negative stride implies traversing backwards
• The start index and end index should be logically correct
s=‘ABCDEF’
print(s[-1:0:-1])

This would start from the last element ( due to -1 index )


Will traverse backwards ( due to stride as -1 )
Will not include element 0 ( as end index is not included )
Slices in detail
s=‘ABCDEF’
a=s[::] # makes a copy of s
b=s[::-1] # makes a reverse copy of s
Tuples
• Tuples are ordered immutable sequences
a=10,20,30,40
a=(10,20,30,40)

In both the above, a tuple is assigned to the variable a


a[0] is 10
a[0]=12 is not allowed since a tuple is immutable
len(a) gives us 4, the total elements in the tuple
We can use slicing and use ‘in’ to check for existence or iterate a tuple
Tuples
• Tuples can be added to get a new tuple
a=(10,20,30,40)
b=(15,16)
c=a+b
print(c)

This would print :


(10,20,30,40,15,16)
Sets
• Sets are unordered immutable sequences of UNIQUE elements
a={ 10,20,30,40 }
b={ 20,50,60 }
c=set() # makes an empty set
If a duplicate element was provided during assignment, it would be discarded
automatically

The in operator can be used to check for existence of an element


The len() function can be used to find total elements in a set
Sets are NOT iterable
Set Operations
a={ 10,20,30,40 }
b={ 20,50,60 }

c=a-b # What is in a but not in b


c=a&b # What is in a and b , Intersection
c=a|b # What is in a or b , Union
c=a^b # What is only in a or only in b, but not in both, exclusive or

-- DEMONSTRATION
Lists
• Lists are ordered mutable sequences
• Lists can be compared to heterogeneous arrays
• Lists can be increased or decreased dynamically

a=[ 10, 20, “John” ]


a[0] # gives us 10
a[2] # gives us “John”
a[1]=30 # updates element at index 1 ( mutable )
Lists Operations
A=[] # Creates an empty list
A=[10,”Alpha”, 5.3 ,20 ] # Creates a list with mixed type elements
A=[10,20,[2,3],30] # Element at index 2 is a list ( nesting )
A[1] # Gives 20
A[2][1] # Gives 3
len(A) # Gives 4 ( nested list is one element )
B=A*3 # Replicates A 3 times
A[2:4] # Slicing
Lists Operations
if 10 in A: # check for existence of 10 in List
for e in A: # Iterates all elements of A
A.append(24) # Adds 24 as last element of A
A.extend( [1,5,9] ) # Appends a list at end of A
A.insert(2,”Hello”) # “Hello” inserted as index 2, shifting the elements
A.count(20) # counts occurrence of literal 20 in List
A.remove(10) # removes first occurrence of literal from the list
x=A.pop(2) # removes and returns element at index 2
Lists Operations
A.sort() # Sorts the list
A.reverse() # Reverses the list
del A[x] # deletes the index location and shifts elements up
del A[x:y] # deletes a slice from the List and shifts accordingly
A[x:y]=[1,100,2] # replaces a slice, adjusting indexes automatically

-- DEMONSTRATION
Lists building by comprehension
A=[ x for x in range(2,10,2) ]

The iteration results are used to populate the list A


This is a very powerful feature
A lot more would be explored in this context
Lists & Strings
s=“Hello”
a=list(s) # a=[‘H’,’e’,’l’,’l’,’o’]
a[4]=‘p’ # a=[‘H’,’e’,’l’,’l’,’p’] as list is mutable
b=‘’.join(a) # join combines elements of a as a string
b=‘-’.join(a) # string before join, is used as separator
# b=“H-e-l-l-o”
c=b.split(‘-’) # splits string b on character ‘-’ resulting in a list
# default splitting character is white space
Programming exercises
• make string from an input string with words in reverse order.
"A CAT RAN" => "RAN CAT A“

• Get a list of words with their count in a sentence. The words should be
in sorted order alphabetically. Words should not be repeated. Assume
space as a separator for words.

-- DEMONSTRATION
Lab Exercises
• Input a sentence and display the longest word
• Input a sentence and input a word. We have to find out how many times
the word occurred in the sentence.
• Display all the words that are contained in a sentence. Words that come
multiple times should be displayed only once.
• We wish to display only those words from the sentence that do not occur in
a set of excluded words ( like : this, and, is, not etc. ). The set of excuded
words would be maintained in your code, and the sentence is input from
the keyboard. We have to display all words that do not exist in this set, and
we have to take care that multiple occurring words are displayed only once.
• Display the density of each word in a long sentence. The displayed words
should not exist in the set of excluded words. However to calculate the
density, we would use the total number of words contained in the
sentence.
Thank you

Вам также может понравиться