Professional Documents
Culture Documents
Day 3 Machine Learning
Day 3 Machine Learning
Day 3
Python - Decision Making
Decision making is anticipation of conditions
occurring while execution of the program and
specifying actions taken according to the
conditions.
Syntax
if expression:
statement(s)
Syntax
The syntax of the if...else statement is −
if expression:
statement(s)
else:
statement(s)
Python IF...ELSE Statements
The elif Statement
The elif statement allows you to check multiple expressions for
TRUE and execute a block of code as soon as one of the conditions
evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike
else, for which there can be at most one statement, there can be an
arbitrary number of elif statements following an if.
syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Python Nested IF statements
There may be a situation when you want to check for another condition
after a condition resolves to true. In such a situation, you can use the
nested if construct.
In a nested if construct, you can have an if...elif...else construct inside
another if...elif...else construct.
Syntax
The syntax of the nested if...elif...else construct may be −
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
String Manipulation
Python String Manipulation
String literals in python are surrounded by either single quotation
marks, or double quotation marks.
'hello' is the same as "hello"
Strings can be output to screen using the print function. For
example: print("hello").
Example
Backslash Hexadecimal
notation character Description
\n 0x0a Newline
Octal notation,
\nnn where n is in the
range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
String Special Operators
Example
Operator Description a=“Hello” and b = “Python”
Concatenation - Adds values on
+ either side of the operator a + b will give HelloPython
Example
print para_str
Unicode String
Normal strings in Python are stored internally as 8-bit
ASCII, while Unicode strings are stored as 16-bit
Unicode.
This allows for a more varied set of characters, including
special characters from most languages in the world. I'll
restrict my treatment of Unicode strings to the following
−
center(width, fillchar)
Returns a space-padded string with the original string centered to a total of width columns.
decode(encoding='UTF-8',errors='strict')
Decodes the string using the codec registered for encoding. encoding defaults to the default
string encoding.
encode(encoding='UTF-8',errors='strict')
Returns encoded string version of string; on error, default is to raise a ValueError unless errors
is given with 'ignore' or 'replace'.
expandtabs(tabsize=8)
Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
isalpha()
Returns true if string has at least 1 character and all characters are alphabetic and false
otherwise.
isdigit()
Returns true if string contains only digits and false otherwise.
Built-in String Methods
islower()
Returns true if string has at least 1 cased character and all cased characters are in lowercase
and false otherwise.
isnumeric()
Returns true if a unicode string contains only numeric characters and false otherwise.
isspace()
Returns true if string contains only whitespace characters and false otherwise.
istitle()
Returns true if string is properly "titlecased" and false otherwise.
isupper()
Returns true if string has at least one cased character and all cased characters are in
uppercase and false otherwise.
join(seq)
Merges (concatenates) the string representations of elements in sequence seq into a string,
with separator string.
len(string)
Returns the length of the string
Built-in String Methods
ljust(width[, fillchar])
Returns a space-padded string with the original string left-justified to a total
of width columns.
lower()
Converts all uppercase letters in string to lowercase.
lstrip()
Removes all leading whitespace in string.
maketrans()
Returns a translation table to be used in translate function.
max(str)
Returns the max alphabetical character from the string str.
min(str)
Returns the min alphabetical character from the string str.
replace(old, new [, max])
Replaces all occurrences of old in string with new or at most max occurrences
if max given.
Built-in String Methods
rfind(str, beg=0,end=len(string))
Same as find(), but search backwards in string.
rindex( str, beg=0, end=len(string))
Same as index(), but search backwards in string.
rjust(width,[, fillchar])
Returns a space-padded string with the original string right-justified to a total of width columns.
rstrip()
Removes all trailing whitespace of string.
split(str="", num=string.count(str))
Splits string according to delimiter str (space if not provided) and returns list of substrings; split
into at most num substrings if given.
splitlines( num=string.count('\n'))
Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.
startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if starting index beg and ending index end are
given) starts with substring str; returns true if so and false otherwise.
Built-in String Methods
strip([chars])
Performs both lstrip() and rstrip() on string.
swapcase()
Inverts case for all letters in string.
title()
Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are
lowercase.
translate(table, deletechars="")
Translates string according to translation table str(256 chars), removing those in the del string.
upper()
Converts lowercase letters in string to uppercase.
zfill (width)
Returns original string leftpadded with zeros to a total of width characters; intended for
numbers, zfill() retains any sign given (less one zero).
isdecimal()
Returns true if a unicode string contains only decimal characters and false otherwise.
Python Collection
You can loop through the list items by using a for loop:
append() Method
The append() method appends an element to the end of the
list.
insert() Method
The insert() method inserts the specified value at the
specified position.
fruits.insert(1, "orange")
List Methods
extend() Method
The extend() method adds the specified list elements (or any iterable)
to the end of the current list.
Add the elements of cars to the fruits list:
fruits = ['apple', 'banana', 'cherry']
fruits.extend(cars)
pop() Method
The pop() method removes the element at the specified
position.
fruits.pop(1)
remove() Method
The remove() method removes the first occurrence of the
element with the specified value.
fruits.remove("banana")
List Methods
clear() Method
The clear() method removes all the elements from a
list.
fruits.clear()
Delete List Elements
reverse() Method
The reverse() method reverses the sorting order of the
elements
fruits.reverse()
sort() Method
The sort() method sorts the list ascending by default.
You can also make a function to decide the sorting
criteria(s).
Syntax
list.sort(reverse=True|False, key=myFunc)
Optional. A function to
key specify the sorting
criteria(s)
List Methods
sort() Method
cars.sort(key=myFunc)
sort() Method
Sort a list of dictionaries based on the "year" value of the
dictionaries:
# A function that returns the 'year' value:
def myFunc(e):
return e['year']
cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]
cars.sort(key=myFunc)
List Methods
copy() Method
The copy() method returns a copy of the specified list.
x = fruits.copy()
List Methods
count() Method
The count() method returns the number of elements with
the specified value.
Return the number of times the value "cherry" appears int
the fruits list:
fruits = ['apple', 'banana', 'cherry']
x = fruits.count("cherry")
Return the number of times the value 9 appears int the list:
points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = points.count(9)
List Methods
index() Method
The index() method returns the position at the first
occurrence of the specified value.
What is the position of the value "cherry":
len(list)
It is used to calculate the length of the list.
max(list)
It returns the maximum element of the list.
min(list)
It returns the minimum element of the list.
list(seq)
It converts any sequence to the list.