程序代写代做 go flex Java database clock C data structure html Python Functions

Python Functions

I. Working with Strings

As we have seen a string is probably the most commonly used variable data type when developing scripts or programs. Python provides a large library of string functions to help us manage, manipulate, validate and transform strings.

A String is a consecutive list of alphanumeric characters enclosed in either a pair of single quotes or a pair of double quotes. You can place a single quote inside a double quote, or vise versa. In Python 3x, you can also use an fstring. An fstring allows you to have variable substitutions

Examples: fname Sam
middle empty string
lname Sultan
myWorld Sams World single quote inside double quote
Fstring F your name is fname your name is Sam

Strings allow for certain escaped characters. You can include the following escape characters within a string:

t the tab character
n the newline character

Example: Hello World n this will print and move to the next line
however on the web, you need a br tag

You can span a Python string across multiple lines. There are 2 ways to do that.

Using the triple quotes single or double
Using the backslash This technique is also good for any HTML or SQL code statement.If using this technique, make sure that there no additional characters after the not even spaces.

Examples: str The quick brown fox
jumped over the lazy dog

print
html
pHello Worldp

query SELECT stuid, fname, lname
FROM student
WHERE fname name
AND stuid strnum notice the str function

PS. Do not confuse the above triple quotes, with the multiline comment that also uses triple quotes.
String FunctionsMethods

Function
Description
printstring1, string2, num
Prints multiple strings Automatically adds a newline after print
printstr1 str2 strnum
Using the symbol to concatenate strings with strnumber
printstr1, str2, end
With ending end, does not add a newline.
printformat num1, num2
Prints a number rounded and formatted using format. Example: print 5.2f f 12.3, 6.2
printformat.formatn1, n2
Prints a number rounded and formatted using format. Example: print :5.2f :f.format num1, 6.2
lenstring
Returns the length of the string
text.lower text.upper
Returns a lower, or upper case version of the string.
text.strip lstrip rstrip
Removes white spaces from the left, right or both ends of string
text.indexsubstr, start, end
text.findsubstr, start, end
Returns the position in text where first occurrence of substr is foundIf startend is given, search within startend range only. 0 basedReturns 1 if substr is not found within text.
substr in text
Returns TrueFalse if substr is found in text.
textstart : end
Returns a substring of text from start to end end is not included
If no colon e.g. name 5 , then take 5th character only
If start is not given e.g. name : 5 , then beginning to 5th char
If end is not given e.g. name5 : , then char 5 to end of text
text.replaceold, new, count
Replace all occurrences of the old string with the new string
If count is given, replace only that many numbers of occurrences
text.centerwidth, fillchartext.rjustwidth, fillchar ljust
Returns a copy of the text center, right, or left justified to specified width. If fillchar is not given, space is assumed.
strvariable
Convert any variable number, list, tuple, dictionary to a string
listtext
Splits the text string on all the characters and create a list
delimeter.joinlist
Combine all elements of a list using the delimiter, and return a string
text.splitdelimeter, count
Splits the text using delimiter or whitespace if none, return a list
If count is given, only splits that many number of tokens
text.splitlineskeepends
Splits the text on newlines. If keepends is True, keep newline char
re.split regex, string
Splits the string using the regex delimiter and returns a list
Must import re regular expression module
re.search regex, string, flagsre.match regex, string, flags
Returns whether the regex pattern is found in the string
Returns whether the string matches the regex exactly startfinish.
flags could be re.I for case insensitive
re.subregex, new, string, limit
Substitute replace the regex pattern found with the new value
If no limit is specified, all occurrences will be replaced

Examples:

text the quick brown fox jumped over the lazy dog

The length of the string

printThe length of the string is: , lentext 44

Finding substrings

printWhere is fox…….? , text.indexfox 16
printWhere is 2nd the? , text.indexthe, 10 32

Extracting substrings

printExtract the dog..: text41 : 44
printbeginning to fox: text 0 : text.indexfox nested functions
printfox to the end….: text text.indexfox :

Replacing substrings

printSwitch the fox with the dog:
newString text
newString newString.replacefox, xxx
newString newString.replace dog, fox
newString newString.replace xxx, dog
printNow the string is: newString

Converting a string to a list

printConverting a string to a list:
list1 text.split split string on any whitespace
printlist1 the, quick, brown, fox,

Converting a list to a string

printbConverting a list back to a string: bbr
newString .joinlist1 join the list using
printnewString thequickbrownfox…

Printing a rounded and formatted number

print .2f 1234.5 1234.50
printNum: 5.2f 104 Num: 2.50
printNum: 10.2f 104 Num: 2.50
printNum: 5.2f and 6.3f 104, 75.6667 Num: 2.50 and 75.667
or printNum: :5.2f and :6.3f.format104, 75.6667 Num: 2.50 and 75.667

Regular Expression regex Advanced Topic Optional SelfStudy

To use regex in Python, you must import re

Meta Character
Description
Any character
Matches itself unless it is one of the characters below
.
a dot A wildcard that matches any single character
d
Matches any digit 09
D
Matches any character that excluding 09
w
Matches any character in the range az, AZ, 09, and underscore
W
Matches any character excluding az, AZ, 09, and underscore
s
Matches any white space including space, tab, newline, form feed, etc.
S
Matches any character excluding white space
b
Matches at a word boundary
Example: bscoreb matches score but not scores, scoreboard or underscore
B
Matches content but not a word boundary
Example: Bscore matches underscore but not score or scores
?
The previous character must exist 0 or 1 timeExample: a? matches a or nothing at all

The previous character must exist 0 or more timesExample: a matches a, aa, aaa, etc. as well as nothing at all.

The previous character must exist 1 or more timesExample: a matches a, aa, aaa, etc..
? ?
Perform the matching in a non greedy fashion
char
Any meta character can be escaped by using a slash
Example: . matches a dot. It is no longer used as a wildcard character.
n
The previous character must exist n timesExample: a3 matches aaa only
n,m
The previous character must exist at least n times, but no more than m timesExample: a3,5 matches aaa, aaaa, aaaaa only
n,
The previous character must exist at least n times, no upper limit
,m
The previous character must exist no more than m times, no lower limit
aeiou
Matches any 1 character from the list of characters enclosed
Example: abc matches either a, b or c
az or azAZ09
Matches any 1 character from the range of characters enclosed
Example: azAZ09 matches any loweruppercase letter or a number
az
Matches any 1 character that is not in the range of characters enclosed
Example: az matches any non lowercase letter

Matches the next character at beginning of the string
Example: az09 matches any string, starting with an alpha, then a number

Matches the previous character at the end of the string
Example: az09 matches any string, must end with an alpha, then a number

Used for grouping
AB
Used for alternatives
Example: graey matches gray or grey
Regex Examples: Optional Study

ddddddddd Will match a social security number 123456789

d3sd3ssd4 Will match a telephone number 1234567890
as well as 123 456 7890

s Will match all spaces or nulls perhaps need to issue error msg.

Eliminating all html tags from a string using Regex

import re import regular expression module

string bI am entering some data uwithu HTML tags b

string2 re.sub.?, , string

printThe string without any html tags is: string2

where: the less than sign
. any character a dot is a wildcard for any character
one or more of the previous character
? nongreedy. The previous or should not be greedy
the greater than sign

Validating an email address using Regex

import re import regular expression module

email sam.sultannyu.edu;
regex 09Az09.Az09Az09.Az09.Az2,4

if re.matchregex, email :
printEmail address is valid.
else :
printEmail address is not valid.

where: beginning with
09 anything but 09
Az09 anything between Az or 09 or
one or more of the previous character
. a dot a dot has to be escaped, otherwise it is a wildcard char
zero or more of the previous character
an sign
Az anything between Az alpha upper or lower case only
2,6 from as low as 2 to as many as 6 of the previous character
ending with

A good web site that helps you learn regex is: HYPERLINK http:txt2re.com http:txt2re.com
or HYPERLINK http:samsultan.compythondemo2functionregexPracticeweb.py http:samsultan.compythondemo2functionregexPracticeweb.py
II. Working with Numbers

As we have seen a Python number can either be an integer or a floating point decimal number. Numbers can be manipulated mathematically using any of the numeric operators and .

In addition, Python offers a wide range of other mathematical functions that can be used with numeric variables. Some of these require the import of additional modules such as math or random.

Number FunctionsMethods

Function
Description
intstring
Convert a string or a float to an integer number
floatstring
Convert a string or an int to a floating point decimal number
absnumber
Returns the absolute value of number the number without the sign
roundnumber, places
Rounds the decimal number to the requested decimal places
math.ceilnumber
Elevates the decimal number to the next whole integer
math.floornumber
Chops the decimal number down to the previous whole integer
math.pi
Returns PI as the value 3.14159265
math.pownumber, exp
Returns the number to the power of the exponent
math.sqrtnumber
Returns the square root of the number
math.lognumber, base
Returns log of the number to given base. If no base, use natural log
random.seednum
Sets a seed for the random generator, ensures repeatable random nums
random.random
Returns a random number between 0 and .999999999
random.randrangemin, max
Returns a random integer between min and max max not included.
random.randintmin, max
Returns a random integer between min and max max included.

Examples:

import math
import random

num 1234.567
print roundnum, 2 prints1234.57
print math.floornum prints 1234.0

string1 123
string2 123.45
num1 intstring1 prints 123
num2 floatstring2 prints 123.45

printRandom number is.: , random.random .1973026838
printRandom number for range is: , random.randint1,100 76
Generic FunctionsMethods

The functions below work on different Python datatype variables i.e. string, numeric, lists, etc.

Function
Description
str.isalpha
Returns whether the string has at least 1 alpha character
str.isdigit
Returns whether the string is all digits 123 true, 123, 123.56 false
str.isspace
Returns whether the string only contains whitespace space, tabs, newlines
intstring
Convert a string or a float to an integer number
floatstring
Convert a string or an int to a floating point decimal number
typevariable
Returns the type of variable as: int, float, bool, str, list, tuple, set, dict, etc.
isinstancevar, type
Returns TrueFalse whether the variable is of that type
idvariable
Returns the address in memory where the variable is located
try : except :
Test or try to execute some statements, if error is detected, execute except statements
exit or quit
Exit the program immediately

Examples:

var var can be null, 0, False or None
if not var : if var is empty
printVariable is empty, 0 or null yes it is empty

var
if var.isspace : if var is spaces, tabs or newlines
printVariable is whitespace yes it is

var 123456.789
print typevar type float

var 1:a, 2:b, 3:c
if typevar is dict : True
printThe variable is a dictionary

def isnumericvar : function to check if string is numeric
try:
floatvar try to convert a string to a decimal number
return True
except:
return False
Notice, function must be declared prior to usage
if isnumeric1234.56 :
printVariable is numeric Variable is numeric
III. Working with Dates

When writing programs, you will inevitably need to display and manipulate date and time data. Dates are special data types in most languages, and Python is no exception.

Date and time is generally represented as a timestamp. It is the number of seconds since January 1, 1970 00:00:00 GMT Greenwich Mean Time. This time is called EPOCH date. Dates prior to January 1, 1970 are represented as negative numbers.

Python provides numerous modules packages and objects within those modules that allow you to extract meaningful information out of the timestamp, as well as enable you to perform date processing such as calendar generation and date additions and subtractions.

1 The datetime Module package

The most common module to use for date manipulation is the datetime module. As such we will need to import that module. Within the module, there are 2 objects that we will use:

datetime.datetime This is the most common object to manipulate date time
datetime.timedelta This object allows you to perform dateinterval addition

1.1 The datetime Object

from datetime import datetime From the datetime module, import the datetime object
or from datetime import to import all objects

datetime.today Create a datetime object with current date and time
datetime.now Create a datetime object with current date and time
datetime.utcnow at GMT Example: current datetime.now
printcurrent 20190315 18:25:51.865944

datetimeyyyy,mm,dd,hh,mi,ss,micro Create a new datetime object for the specified parameters.
Only yyyy, mm, dd are required
Example: day2 datetime2019,12,1,15,30,43,100000

Attributes: instance

year, month, day, Access that component of the datetime object
hour, minute, second, Example: current datetime.now
microsecond printcurrent.day, current.month

Methods: instance

date Returns a date object format: yyyymmdd for today
time Returns a time object format: hhmmss for now
replaceyyyy,mm,dd,hh,mi,ss Returns a copy of a datetime object with those components changed
weekday Returns the day number as an int 0Mon, 1Tue, 2Wed , 6Sun
Formatting Date and Time

dt.strftimeformat Format a datetime object into a string using the formats below

a A day name abbreviated and full name
b B month name abbreviated and full name
c the full datetime as: Day Mth dd hh:mm:ss yyyy
y Y the year with 2 digits and 4 digits
m the month number 112
d the day number 131
H I the hour in 24 hour clock and in 12 hour clock
M the minutes 059
S the seconds 059
s number of seconds since EPOCH day 111970
j the Julian day 1366
w the day number 06 0Mon, 1Tue, , 6Sun
U the week number 153
x the full date as: mmddyy
X the full time as: hh:mm:ss
p AMPM indicator

datetime.strptimestr,format Convert a string to a datetime object using the formats above

Examples:
from datetime import datetime from datetime module, import datetime object

now datetime.now create date obj for now
gmt datetime.utcnow create date obj for GMT now
printnow.day, , now.month, , now.year dd mm yyyy
printDate now is: , now.date yyyymmdd
printTime now is: , now.time hh:mi:ss
printToday is: , now.weekday 0Mon, 1Tue, 6Sun
printThe date only , now.strftimeA dm, B Y Sunday ddmm April yyyy
printThe time is: , now.strftimeH:M:S I:M p h24:mi:ss h12:mi AM
printGMT offset: , gmt now 5 hour difference
dt datetime.strptimeDec 1 2019 1:33, b d Y I:M convert a string to a datetime

1. Determine the interval between 2 dates here in number of days

from datetime import datetime from datetime module, import datetime object

someDay datetime2019,12,31,15,30,00
delta someDay now delta is a timedelta object
seconds delta.totalseconds number of seconds in delta
numDays seconds 246060 divide by 1 day worth of seconds

2. Addsubtract an interval to a date here in days

from datetime import timedelta from datetime module, import timedelta object

future now timedeltadays365 you can use: weeks,days,hours,minutes,seconds
printfuture
IV. Working with Lists

In any language including Python, lists known as arrays in most other programming languages are such useful and powerful data structures. Unlike other more strongly typed languages such as Java, Python lists can have heterogeneous data types, and can grow automatically as needed. A list is a single variable that can contain different types of data all at once including certain elements being numbers, or strings, or even other additional lists, creating the ability to implement a 2 dimensional list. This makes working with Python lists easy and very flexible.

You can think of a list as a single variable container that can store multiple values. List elements are enclosed in square brackets and are separated using a comma.

To access elements of the list, you include the list name, immediately followed by a pair of square brackets . Within the square brackets you identify the index number of the particular element you want to access. Index numbers start at 0.

To Create a List:

stuff1 or list create an empty list
stuff2 Jan, Feb, Mar, Apr create an populate a list
stuff3 abc, xyz, 100, 3.14 create a heterogeneous list different data types
stuff4 stuff3 stuff4 is a reference to stuff3
stuff5 liststuff3 create an actual list copy of stuff3.

To AccessManipulate List Elements:

month stuff20 month is now Jan
stuff20 January changing the value of Jan to January
index 3
stuff2index April using a variable as an index

stuff2.appendMay adding a new element to stuff2
stuff1.appendSam adding a first element to stuff1

stuff1.insert0, John insert element John at index 0

del stuff30 delete element 0 of stuff3

subList stuff20 : 2 Take a portion of a list element 0, 1 only

To Print Entire or portion of a List:

print stuff2 January, Feb, Mar, April, May

print stuff20 : 3 print element 0 thru 2 not including 3
January, Feb, Mar
List FunctionsMethods

Function
Description
printlist
Prints all values a list. a,b,c Great for debugging purposes
lenlist
Returns the number of elements in the list.
listvariable
Converts a string, a tuple, a set, or dictionary keys to a list.
list2 list1.copy list2 listlist1
list2 is a copy of list1You can use either method
subList list1from : to
Copy element values from index, to index to index not includedIf no from, start from beginning. If no to, go to end
list.appendelement
Add an element to the end of the list
list.insertindex, element
Add an element at the given index position
del listn
Delete element with index n from the list.
list.removevalue
Delete the first occurrence of element with given value
list.popn
Delete the n element from an array or the last element if no n.
list.clear
Delete all the elements in the list. Keep the list
del list
Delete entire list
strlist
Converts the list into a string, format a, b, c
delimiter.joinlist
Converts the list into a string using the delimiter as a glue
str.splitdelimeter
Splits the str using delimiter or whitespace if no delim. and return a list
value in list
Returns True or False whether the value given is found within the list
list.indexvalue
Returns the index for the value if it is found in the list. If not found, error
list.sort reverseTrue, keyfunction
Sorts the values of the list in ascending order.With options, discussed later
list.reverse
Reverses the order of all elements in the list

Examples:
animals dog, cat ,pig, cow, duck, bird

printanimals dog, cat ,pig, cow, duck, bird
printanimals2 : 5 print elements 24 pig, cow, duck

animals.appendfish add fish
animals.removepig remove 1st occurrence of pig

found cow in animals True

animals.sort ; sort ascending
animals.sort reverseTrue sort descending

for value in animals : iterate through the list
printvalue

for idx in range lenanimals : iterate through the list another way
printanimalsidx
Analytics FunctionsMethods for Lists Self Study

Function
Description
lenlist
Returns the number of elements in the list.
sumlist
Returns the sum or the values within the list
minlist maxlist
Returns the minimum or maximum value within the list
statistics.meanlist
Returns the average value of a list
statistics.medianlist
Returns the median sorted midpoint element of a list. If number of elements is even, return average of the two midpoints
statistics.medianlowlist
If number of elements is even, return element before the midpoint
statistics.medianhighlist
If number of elements is even, return element after the midpoint
statistics.modelist
Returns a single mode most common element of the list.If list has multiple modes, raises an exception.
statistics.stdevlist
Returns a sample standard deviation
statistics.pstdevlist
Returns the population standard deviation
random.shufflelist
Shufflerandomize the elements within the list in place
random.choice list
Returns a random single element from the list
random.samplelist, num
Returns a random specified number of elements from the list

Examples:
import statistics
import random

list 1,2,3,4,5,6,7,8,9

print lenlist prints the number of elements
print sumlist prints the sum of the elements
print minlist prints the smallest element
print maxlist prints the largest elements
print statistics.meanlist prints the average of the elements
print statistics.medianlist prints the median midpoint or avg. of 2 midpoints
try:
print statistics.modelist prints mode of list. Single mode only
except statistics.StatisticsError as e : if multiple modes, raises an exception
printmultiple or no unique mode:, e

print statistics.stdevlist prints sample standard deviation
print statistics.pstdevlist prints population standard deviation

list2 random.samplelist, 5 returns a sample of 5 elements from the list
random.shufflelist shuffle the list in place
Two Dimensional Lists Advanced Topic

Python allows you to create 2 dimensional lists. Actually it is best said that Python allows you to create a list of lists. In theory, you can create any number of nested multidimensional lists, so you can have any level of lists within lists i.e. 3 dimensional, 4, etc..

An application of a 2 dimensional lists would be a spreadsheet, a scoreboard, etc. In addition, another application of a 2 dimensional lists would be the output of a database query, where each element of the first dimension represents a different row returned from the query, and each element of the second dimension represents a different column returned from the query.

Example of person list:

1st dim. 2nd Dimension
person

person00

person0

person1

person2

person23

To Create 2 Dimensional Lists:

person1 Sam, 6.2, M, 51 create a list
person2 Bill, 5.10, M, 44
person3 Sue, 5.6, F, 26
persons person1, person2, person3 create lists within a list
or
persons Sam, 6.2, M , Bill, , create lists within a list

To Access MultiDimensional Elements:

someone person0 someone is now an entire list
printsomeone Sam, 6.2, M, 51
someAge person03 someAge is a single cell
printsomeAge 51

Iterating through a Two Dimensional List Advanced Topic

Now that you have created a 2 dimensional list, it is now time to learn how to iterate through it. You can use the for loop in one of 2 styles

data 123, Barbara, Burns, 000010001, F,
124, Vincent, Cambria, 000010002, M,
125, Duncan, Davidson, 000010003, M

Style 1

print Looping thru 2 dimensional list..

for row in data: row is each list of 2dim data
for element in row: element is each element of row
printelement, t, end
print

Style 2

print Looping thru 2 dimensional list..

for row in rangelendata : len of data is the number of rows
for col in rangelendatarow : len of each row
printdatarowcol, t, end
print

In either case, the output

Looping thru 2 dimensional list…
123 Barbara Burns 000010001 F
124 Vincent Cambria 000010002 M
125 Duncan Davidson 000010003 M

Explanation

In the 1st style, row is the entire list of each row within the 2 dimensional data list.
And element is the value of each element in that row

In the 2nd style, rangelendata will return the number of rows in data which is 3. And rangelendatarow will return the number of elements in each row which is 4.As such row is an index in the range of 0 to 3, and col is an index in the range of 0 to 4.
V. Working with Tuples

A Tuple in Python is similar to a Python list. A tuple is a variable that holds a set of data elements. Each element within that tuple will have an index component and a value component. Think of a tuple as a complex container having many values included in a single box.

Unlike Python lists arrays for optimization purposes, a tuple is immutable. That is once you create a tuple, you can no longer modify it. You cannot change element values, nor can you add any additional elements to it.

To create a tuple you use the parenthesis notation. Within the parenthesis, you add the list of elements as a comma separated list of values.

Python tuples are numerically indexed starting at 0. Each element within the tuple will have its own index. The first element will be given index 0, the second will be given index 1, and so forth.

Examples:
tuple1 or tuple create an empty tuple
tuple2 apples, bananas, oranges a tuple with 3 elements
tuple3 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 a numeric tuple
tuple4 11, 12, 13, 14, 15

Although you cannot modify a tuple, you can concatenate another tuple to an existing tuple.

Examples:
tuple2 peaches, pears concatenate 2 more elements
tuple2 strawberries , concatenate 1 more element
notice the comma after the element
tuple3 tuple4 concatenate 5 more elements

Tuple Functions

Most of the functions that work on a list, will also work on a tuple, providing that the function does not alter or modify the tuple elements

VI. Working with Sets

A set is an unordered list of items. Just like a list or a tuple, a set can include many elements. However, unlike a list or a tuple, the items are unordered no guarantee that they will be returned in the same order as originally stored as well as the fact that a set requires that every element must be unique within the set a set will not accept 2 elements that have duplicate values.

You create a set by using curly braces. Each element in the set is separated using a comma.

To Create a Set:

set1 set create an empty set
set2 1,2,3,4,5,6,7,8,9,10 elements must be unique
set3 6,7,8,9,10,11,12
set4 Jan, Feb, Mar

To AccessManipulate Set Elements:

Since elements in a set are not indexed, we cannot accesschange an individual element. We can however add new elements by using the add method, and delete elements by using discard . If you attempt to add a second element with the same value, your add operation will be ignored.

Examples:
set4.addApr Add new element
set4.add11
printset4 11, Jan, Feb, Mar, Apr

set4.discard11 Delete an element
printset4 Jan, Feb, Mar, Apr

set4.addJan will not be added since it is a duplicate
printset4 Jan, Feb, Mar, Apr

isExist Jan in set4 Does element exist?
printisExist True

for element in set4: Iterate through the set
printelement print the elements Jan Feb Mar Apr

Set Operations: If you have 2 sets, you can perform Set operations such as union, intersect, minus

Examples:
x set2 set3 or use: set2.unionset3
printx 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

x set2 set3 or use: set2.intersectionset3
printx 6, 7, 8, 9, 10

x set2 set3 or use: set2.differenceset3
printx 1, 2, 3, 4, 5
VII. Working with Dictionaries

In many languages including Python, Dictionaries known as hashes or associative arrays or maps in other programming languages are available, and are such useful and powerful data structures. Just like lists, a dictionary is a single complex variable that can contain many values within it.

A dictionary can contain heterogeneous data types. That is a single dictionary can contain different type of data all at once including certain elements being numbers, others being strings, and even others being additional lists, or other dictionaries. This allows you the creation of any complex data structure to suit your needs.

You can think of a dictionary as a single variable container that can store multiple keys and values. These are called keyvalue pairs, they are also often called namevalue pairs. To create a dictionary, you use curly braces . Within a dictionary definition, you specify each key and value pair separated with a colon, multiple keyvalue pairs are separated with commas.

To access elements of a dictionary, you include the dictionary name, immediately followed by a pair of square brackets . Within the square brackets you identify the key of the element.

To Create a Dictionary:

stuff1 or dict create an empty dictionary
stuff2 1:Jan, 2:Feb, 3:Mar, 4:Apr create and populate a list
stuff3 a:abc, b:xyz, c:100, d: 1,2,3 create a heterogeneous dictionary
notice the last element value is a list
stuff4 stuff3 stuff4 is a reference to stuff3.
stuff5 dictstuff3 create an actual copy of stuff3.

To AccessManipulate Dictionary Elements:

month stuff24 month is now Apr
stuff3a ABC changing the value of abc to ABC
key b
stuff3key XYZ using a variable as a key

stuff25 May adding a new keyvalue to stuff2
stuff1fname Sam adding a new keyvalue to stuff1

del stuff1fname delete a keyvalue pair from dictionary

To Print Entire Dictionary:

When accessingprinting an entire dictionary, keyvalue pair order is not guaranteed to be returned in the same order it was created

printstuff3 a: ABC, c: 100, b: XYZ, d:1, 2, 3
Dictionary FunctionsMethods

Function
Description
printdictionary
Prints all values a dictionary. key1:val1, key2:val2, key3:val3
lendictionary
Returns the number of keyvalue pairs in the dictionary
dict2 dict1.copy
dict2 dictdict1
dict2 is a copy of dict1
You can use either method
del dictionarykey
Delete keyvalue pair with given key from the dictionary
dictionary.clear
Delete all keyvalue pairs from the dictionary. Keep the dictionary
del dictionary
Delete entire dictionary
dictionary.getkey
Returns the value for that key, or None is not foundMethod is better than dictionarykey as it does not fail when not found
strdictionary
Converts the dictionary into a string, format key1:val1, key2:val2
mindict maxdict
Returns the minimum or maximum key within the dictionary
dictionary.keys
Returns all the dictionary keys as a list
dictionary.values
Returns all the dictionary values as a list
dictionary.items
Returns all keyvalue elements of a dictionary as a list of tuples. format: k1,v1, k2,v2, k3,v3
dictionary.haskeykey
Returns TrueFalse whether the key given is found within the dictionary
key in dictionary
Returns TrueFalse whether the key given is found within the dictionary
val in dictionary.values
Returns TrueFalse whether the val given is found within the dictionary

Examples:
months 1:Jan, 2:Feb, 3:Mar, 4:Apr, 5:May, 6:Jun

howMany lenmonths result is 6

months7 Jul add keyvalue pair 7:Jul
del months3 remove Mar
printmonths

if 10 in months False search thru the keys
if Jan in months.values True search thru the values

printmonths.keys 1, 2, 5, 4, 7, 6 order is not guaranteed
printmonths.values Jan, Feb, May, Apr, Jul, Jun same
printmonths.items 1, Jan, 2, Feb, 5, May, 4, Apr

for key in months : iterate through the dictionary
printkey, is, monthskey

for key,value in months.items : iterate through the dictionary another way
printkey, is, value
Defining your own Functions

You can create your own function. A function is a block of code that is designed to perform a specific task. It is up to you to design and develop the appropriate code that is inside the function. Python allows you to designate such code as a separate function by the use of the def statement. In Python, function declaration must come before usage calling the function.

def functionName parameter1, parameter2, parameter3100, :
Python code

Advantages of functions:

Functions are isolated from the main code. This enables you to develop structured code more specific code divide and conquer for ease of coding and debugging.
You can call invoke a function repeatedly whenever needed, for as many times as desired.
Well designed functions can accept variables called parameters. By doing so, you can develop functions that are generic to handle many situationsvalues.
In addition functions can also return a resulting value to the main code.

Calling a Function

Unlike the rest of your Python code, functions are not automatically executed. Functions must be explicitly called i.e. invoked. To invoke a function, simply call the function by its name, followed by a pair of parenthesis. The call to the function must be after the definition.
If the function expects to receive parameters, you include this data in the parenthesis. You can skip any parameter that has a default value e.g. parameter3100 above
If the function returns data, you must assign the return data to a variable.

Passing and Returning Data

1 Functions can optionally receive data from the calling code typically your main Python code. This data passing mechanism is one of the main advantages for creating functions.

Your main code can pass data mostly variables to the function. When variables or values are passed to the function, they are called arguments.
The function receives those variables. When functions receive those variables, they are called parameters. For an optional parameter, you must assign a default value to it. Example: param3100 Optional parameters must be defined at the end of the parameter list.

Most people however use the words arguments and parameters almost interchangeably.

2 Function can also optionally return data to the calling code typically your main Python code.
When returning data to the main code, the function uses the return statement. The calling code accepts this data by assigning the returned data to a variable.
Example1: Creating and Calling a function

from datetime import datetime from datetime module, import datetime class

printOur first call to a function

def printGreeting : define printGreeting function

now datetime.now get the current date and time
hour now.hour
if hour 12 : are hours 12
printGood Morning
else :
printGood Afternoon
printthe datetime is now , now.strftimemdY H:M:S

printGreeting call printGreeting function

Example2: Passing data

printOdd or Even?

def oddevennum : a function that accepts 1 parameter

oddEven even if num 2 0 else odd is the remainder of 2 odd or even
print The number, num , is , oddEven

oddeven100; call function and pass 1 argument

Example3: Passing and Returning data

import math, random

printThe future value of money
amt random.randint100,5000
interest random.randint200,799 100.0 interest is now from 2.00 to 7.99
year random.randint1,10

def futurevalueamt, rate, year15 : func that accepts 3 params year is optional

rate1 1 rate 100 1 interest rate
fv amt math.powrate1, year amount int to power of year
returnfv function returns data to calling code

value futurevalueamt, interest; call function, pass and receive data
no need to pass year, as it has a default value

printF the future value of amt at interest, for year years is value

PS. Notice the names of the variables used to pass data can either be the same, or can be different.
Variable Scope Advanced Topic

A variable scope is the portion of the Python code that the variable is visible i.e. accessible. Python variables have function scope. This means that they are typically only available within the function they are defined in. Variable scope trickles down to inner functions for read only. That is, if a variable is defined outside of the function in the main code, that variable is available in the inner function, providing that you are simply reading the variable accessing its value or content. If you intend to change the variable, then you must specify that you want that variable as global.

Variables defined in the inner functions cannot be accessed outside of the function where defined.
You can declare that you want a variable within a function to have a global scope. Variables declared with global scope are accessible throughout the entire Python script. Variables that are not declared with a global scope and are defined within a function, are only accessible in the function where defined.

In summary, the scope rules are:

Variable defined outside of functions have global scope for read only. You can read them in a function, but you cannot change them. If you intend to change them, you must make them global within the function.

Variable defined inside of functions have local scope, unless you predefine them using global

The syntax of the global statement is global variable1, variable2,

Example: outerNum1 100 variable defined outside of a functions
outerNum2 200

def scopeTest :

global outerNum1, inner1 makes outerNum1 and inner1 global variables

inner1 1000 variable defined inside of a function
inner2 2000

outerNum1 150 OK variable is global
outerNum2 250 Will create a new local variable
printouterNum1, outerNum2 prints 150 250
printinner1, inner2 prints 1000 2000

scopeTest call the function

printouterNum1, outerNum2 prints 150, 200;
printinner1 OK variable is global
printinner2 ERROR cannot access variable

As such, within the function, you can define a variable that has the same name as outside the function, example outerNum2 as long as you do not declare it global, those will be 2 different variables.
Sorting Lists and Dictionaries

You can always use the Python sort or sorted methods to sort a list or a dictionary.

The sort method

The sort method sorts a single or 2dimensional list in place. It cannot sort a tuple, set or dictionary.
By default, the sort method will sort in ascending order. However, you can supply optional parameters andor a custom function to change that order.

The sort method syntax:

list.sortreverseTrue, keyfunction
where:
reverseTrue Allows you to sort in descending order

keyfunction Allows you to provide a custom function that will receive an element of the list
Your job is to return the portion of the element to sort on.
You can even provide a lambda function.
Examples:

names Sam Sultan, George Washington, Abraham Lincoln, Donald Duck

dim2 Sam, Sultan, George,Washington, Abraham,Lincoln, Donald,Duck

def bylastnameelement : function to sort by lastname
lastname elementelement.index 1 : find space, take all the way to end
return lastname return the portion of element to sort on

def bylnamefnameelement : function to sort by lastname firstname
firstname element : element.index from start, to first space
lastname elementelement.index 1 : from first space, all the way to end
return lastname, firstname return a tuple to sort on

def by2dimlastnameelement : function to sort 2 dim by lname fname
lastname element1 take element1 which is lastname
return lastname return element to sort on

names.sort sort ascending by firstname
names.sortreverseTrue sort descending
names.sortkeybylastname sort by lastname using custom function
names.sortkeybylnamefname sort by lname fname using custom func

dim2.sort sort by element0 firstname
dim2.sortkeyby2dimlastname sort by element1 lastname
dim2.sortkeylambda elem : elem1 sort by element1 using a lambda function

receives returns
The sorted method

The sorted method sorts a single or 2dimensional list, tuple, set or dictionary. The sorted method requires an assignment to another list. By default, the sorted method will sort in ascending order. However you can supply parameters andor a custom function to change that order.

The sorted method syntax:

newList sorted list, reverseTrue, keyfunction
where:
reverseTrue Allows you to sort in descending order

keyfunction Allows you to provide a custom function that will receive an element of the list
Your job is to return the portion of the element to sort on.
You can even provide a lambda function.

Examples:
names Sam Sultan, George Washington, Abraham Lincoln, Donald Duck

dim2 Sam, Sultan, George,Washington, Abraham,Lincoln, Donald,Duck

dict fname:Sam, lname:Sultan, middle:E, sex:male, age:unknow

Lists or Tuples or Sets:
names2 sortednames sort ascending by firstname
names2 sortednames, reverseTrue sort descending
names2 sortednames, keybylastname sort by lastname using custom function
names2 sortednames, keybylnamefname sort by lname fname using custom func

dim2s sorteddim2 sort by element0 firstname
dim2s sorteddim2, keyby2dimlastname sort by element1 lastname

Dictionary by Keys:
keys dict.keys get the keys as a list
keys sortedkeys sort the keys
for key in keys :
print key, , dictkey
or simply
listOfTuplesByKeys sorteddict.items returns a sorted list of tuples by key order

Dictionary by Values:
def byvalueelement : function to sort by value
key, value element receives a dict element, which is a kv tuple
return value
listOfTuplesByValues sorteddict.items , keybyvalue
or
listOfTuplesByValues sorteddict.items , keylambda elem : elem1 using lambda func
for key, value in listOfTuplesByValue :
print key, , value
Importing a Module or a Program

You can include another Python module or script file within the current Python file by using the import keyword. The imported program could either be a builtin Python module by the standard Python library, a Python module that you install, or it could be a program that you custom built yourself. As part of the import, you can also rename the module.

To install a module from the internet, use: pip install somemodule

Builtin or installed Python Modules:

These are modules and classes that are provided within the extensive Python library, or installed by you. These are located in pythonhomedirlib directory.

1 import math import the math module
2 import datetime import the datetime module
3 from datetime import datetime from the datetime module import datetime object
4 from datetime import datetime as dt import datetime and rename it dt in this program
Usage:
1 x math.floor calling a method of the module
2 x datetime.datetime.now example for 2 above. module.object.method
3 x datetime.now example for 3 above. object.method
4 x dt.now example for 4 above. objNewName.method

Custom Programs you Create:

Supposing I have a main.py which is my main program, and I decide to code a couple of utility functions in a file called utils.py. The functions are called abc and xyz

1 If utils.py is in the same directory as main.py, or is in the standard pythonhomedirlib directory:

import utils import utils.py from within main.py
do not use .py extension

x utils.abc calling a function of the module

2 If utils.py is not in the same directory as main.py, or not in the pythonhomedirlib directory:

import sys
sys.path.insert0, homessultanswebpythondemo add the directory that contains the utils.py to the Python path

import utils import utils.py

x utils.abc calling a function of the module

Python Functions

Property of: Sam Sultan Page PAGE 21 of NUMPAGES 24

ref

ref

ref

6.2

M

Sam

51

M

5.10

Bill

44

F

5.6

Sue

26

ref

function

function

function

function