Py Script PDF
Py Script PDF
https://pynative.com/python/object-oriented-programming/
https://realpython.com/python3-object-oriented-programming/
https://www.freecodecamp.org/news/object-oriented-programming-in-python/
https://docs.python.org/3/tutorial/classes.html#class-definition-syntax
https://kinsta.com/blog/python-object-oriented-programming/
https://www.listendata.com/2019/08/python-object-oriented-programming.html
Py Script Page 1
->> string methods
Py Ch 1 https://docs.python.org/3/library/stdtypes.html#string-methods
Thursday, 30 March 2023 2:10 PM https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
From <https://onenote.officeapps.live.com/o/onenoteframe.aspx?ui=en-US&rs=en-
AU&hid=DhO%2BtZXHZESjX7xOm2F4Ww.0&wopisrc=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwopi.onedrive.com%
-> command to go enter into python session in Linux 2Fwopi%2Ffolders%2F5EEC33A5F1C43452!240&wdorigin=704&sc=host%3D%26qt%
/usr/bin/python3 3DDefault&mscc=1&wdp=0&uih=OneDrive&wdhostclicktime=1680997588489&jsapi=1
print(4) -> output : 4 &jsapiver=v1&newsession=1&corrid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&usid=dfdb61d2-
bfa5-40c2-b418-a26caea354cc&sftc=1&wdredirectionreason=Force_SingleStepBoot>
type(4) -> output : int
type(' it's a string ' ) -> output : str
Values
Variables
One of the most powerful features of a programming language is the ability to
manipulate variables. A variable is a name that refers to a value.
M = 16
Pi = 3.14592653589793
Statements
A statement is a unit of code that the Python interpreter can execute. We have
seen two kinds of statements: print being an expression statement and assignment.
print(1)
x=2
print(x)
Python 2.0 would divide two integers and truncate the result to an integer; the above equation results in 0.
To obtain the same answer in Python 3.0 use floored ( // integer) division.
-> The modulus operator works on integers & yields the remainder.
>>> remainder = 7 % 3
>>> print(remainder): 1
Py Script Page 2
-> When more than one operator appears in an expression, the order of evaluation depends on the rules of
precedence. Acronym PEMDAS is a useful way to remember the rules:
Parentheses, Exponentiation, Multiplication, Division, Addition & Division.
String operations
The + operator works with strings, but it is not addition in the mathematical sense.
Instead it performs concatenation, which means joining the strings by linking them
end to end.
… first = 100
>>> second = '150'
>>> print(first + second)
100150
-> The user entered value is a string, convert it integer bfore using it as Integer
you can try to convert the return value to int using the int() function:
Constants
Numeric constants
String constants are decalred inside single or double quotes ( ' ', " " ).
Indenting Your Code
Python uses code indentation to determine which blocks of code to run.
Boolean Expression
Logical operators
There are three logical operators: and, or, and not. The semantics (meaning) of
these operators is similar to their meaning in English.
n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the
number is divisible by 2 or 3
Conditional execution
The boolean expression after the if statement is called the condition. We end the
if statement with a colon character (:) and the line(s) after the if statement are
indented; If the logical condition is true, then the indented statement gets executed
Py Script Page 3
indented; If the logical condition is true, then the indented statement gets executed
-> compound statements because they stretch across more than one line.
-> There is no limit on the number of statements that can appear in the body, but
there must be at least one. with no statements, In that case, you can use the pass statement, which does
nothing.
-> When using the Python interpreter, you must leave a blank line at the end of a block, otherwise Python will
return an error:
Nested conditionals
Such as input statement; where expected input is not of the type that is being
Expected from the user.
For ex:
prompt = "What is the air velocity of an unladen swallow?\n"
speed = input(prompt)
What is the air velocity of an unladen swallow?
What do you mean, an African or a European swallow?
int(speed)
ValueError: invalid literal for int() with base 10:
However if you place this code in a Python script and this error occurs, your script
immediately stops in its tracks with a traceback. It does not execute the following
statement. There is a conditional execution structure built into Python to handle these types
of expected and unexpected errors called “try / except”.
The idea of try and except is that you know that some sequence of instruction(s) may have a problem and you
want to add some statements to be executed if an error occurs. These
extra statements (the except block) are ignored if there is no error.
In general, catching an exception gives you a chance to fix the problem, or try again, or at least end
the program gracefully.
inp = input('Enter Fahrenheit Temperature:')
try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
Py Script Page 4
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
except:
print('Please enter a number')
Short-circuit evaluation of logical expressions
Python detects that there is nothing to be gained by evaluating the rest
of a logical expression, it stops its evaluation and does not do the computations
in the rest of the logical expression.
When the evaluation of a logical expression stops because the overall value is already known, it is called short-
circuiting the evaluation.
>>> x = 6
>>> y = 0
>>> x >= 2 and (x/y) > 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
Debugging
The traceback Python displays when an error occurs contains a lot of information,
but it can be overwhelming. The most useful parts are usually:
• What kind of error it was, and
• Where it occurred.
Syntax errors are usually easy to find, but there are a few gotchas. Whitespace
errors can be tricky because spaces and tabs are invisible and we are used to
ignoring them.
From <https://onenote.officeapps.live.com/o/onenoteframe.aspx?ui=en-US&rs=en-AU&hid=DhO%2BtZXHZESjX7xOm2F4Ww.0&wopisrc=https%
3A%2F%2Fwopi.onedrive.com%2Fwopi%2Ffolders%2F5EEC33A5F1C43452!240&wdorigin=704&sc=host%3D%26qt%3DDefault&mscc=1&wdp=0
&uih=OneDrive&wdhostclicktime=1680997588489&jsapi=1&jsapiver=v1&newsession=1&corrid=dfdb61d2-bfa5-40c2-b418-
a26caea354cc&usid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&sftc=1&wdredirectionreason=Force_SingleStepBoot>
Py Script Page 5
Py Ch 2
Sunday, 9 April 2023 10:00 AM
Recursion
A function that calls itself is recursive; the process of executing it is called recursion.
If n is 0 or negative, it outputs the word, “Blastoff!” Otherwise, it outputs n
and then calls a function named countdown—itself—passing n-1 as an
argument.
def countdown(n):
if n <= 0:
print('Blastoff!')
Return
else:
print(n)
countdown(n-1)
-> If n <= 0 the return statement exits the function. The flow of execution immediately returns to the
caller, and the remaining lines of the function don’t run.
Infinite recursion
If a recursion never reaches a base case, it goes on making recursive calls forever, and the program
never terminates. This is known as infinite recursion, and it is generally not a good idea. Here is a
minimal program with an infinite recursion:
Err:
File "<stdin>", line 2, in recurse
Py Script Page 6
Functions:
It is common to say that a function “takes” an argument and “returns” a result.
The result is called the return value.
The other built-in function is the len function which tells us how many
items are in its argument. If the argument to len is a string, it returns the number
of characters in the string.
------------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------
Type conversion functions
-> built-in functions that convert values from one type to an- other. The int function takes any
value and converts it to an integer, if it can, or complains otherwise:
int('32')
32
int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'
-> int can convert floating-point values to integers, but it doesn’t round off; it chops
offthe fraction part:
int(3.99999)
3
int(-2.3)
-2
Math functions
we can use the module, we have to import it
Import math
-> This statement creates a module object named math. If you print the module object,
print(math)
<module 'math' (built-in)
-> The module object contains the functions and variables defined in the module. To
access one of the functions, you have to specify the name of the module and the
name of the function, separated by a dot; this format is called dot notation
Random numbers
The random module provides functions that generate pseudorandom numbers
The function random returns a random float between 0.0 and 1.0 (includinng 0.0, not 1.0 )
The function randint takes the parameters low and high, and returns an integer
between low and high (including both)
Py Script Page 7
3
The random module also provides functions to generate random values from con-
tinuous distributions including Gaussian, exponential, gamma,
New functions
-> A function definition specifies the name of a new function and the sequence of statements
that execute when the function is called.
def print_lyrics(): //def is a keyword that indicates that this is a function definition.
-> The first line of the function definition is called the header; the rest is called
the body. The header has to end with a colon and the body has to be indented.
By convention, the indentation is always four spaces. The body can contain any
number of statements.
-> Execution always begins at the first statement of the program. Statements are
executed one at a time, in order from top to bottom
-> Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called
-> n a script, if you call a fruitful function( which return some value ) and do not store the result
of the function in a variable, the return value vanishes into the mist!
Math.sqrt(5)
-> Void functions might display something on the screen or have some other effect, but they
don’t have a return value. If you try to assign the result to a variable, you get a special value
called None.
From <https://onenote.officeapps.live.com/o/onenoteframe.aspx?ui=en-US&rs=en-AU&hid=DhO%2BtZXHZESjX7xOm2F4Ww.0
&wopisrc=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwopi.onedrive.com%2Fwopi%2Ffolders%2F5EEC33A5F1C43452!240&wdorigin=704&sc=host%3D%
26qt%3DDefault&mscc=1&wdp=0&uih=OneDrive&wdhostclicktime=1680997588489&jsapi=1&jsapiver=v1&newsession=1
&corrid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&usid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&sftc=1
&wdredirectionreason=Force_SingleStepBoot>
Iteration
Updating variables
If you try to update a variable that doesn’t exist, you get an error, because Python
evaluates the right side before it assigns a value to x:
>>> x = x + 1
NameError: name 'x' is not defined
The while statement
1. Evaluate the condition, yielding True or False.
2. If the condition is false, exit the while statement and continue execution at the next statement.
3. If the condition is true, execute the body and then go back to step 1.
Py Script Page 8
Infinite loops
In the case of countdown, we can prove that the loop terminates because we know that the value of n is
finite, and we can see that the value of n gets smaller each time through the loop, so eventually we have
to get to 0. Other times a loop is obviously infinite because it has no iteration variable at all. In that case
you can write an infinite loop on purpose and then use the
break statement to jump out of the loop.
an infinite loop because the logical expression on the while statement is simply the logical constant
True:
-> Looking at the for loop, for and in are reserved Python keywords, and friend
and friends are variables.
Loop patterns
These loops are generally constructed by:
• Initializing one or more variables before the loop starts
• Performing some computation on each item in the loop body, possibly changing the variables in the
body of the loop
• Looking at the resulting variables when the loop completes
Strings is immutable,
A string is a sequence of characters. You can access the characters one at a time with the
bracket operator:
The expression in brackets is called an index. The index indicates which character in the
sequence you want
You can use any expression, including variables and operators, as an index, but
the value of the index has to be an integer. Otherwise you get:
Py Script Page 9
Another way to traverse; the String
String slices
-> A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
-> returns part of the string from the “n-th” character to the “m-th” character, including the first
but excluding the last.
-> omit the first index (before the colon), the slice starts at the beginning of the string. If you
omit the second index, the slice goes to the end of the string:
-> If the first index is greater than or equal to the second the result is an empty string; An empty
string contains no characters and has length 0, but other than that, it
is the same as any other string.
-> The “object” in this case is the string and the “item” is the character you tried
to assign. For now, an object is the same thing as a value, but we will refine that
definition later. An item is one of the values in a sequence.
-> The reason for the error is that strings are immutable, which means you can’t
change an existing string. The best you can do is create a new string that is a
variation on the original
The "in" operator
-> The word in is a boolean operator that takes two strings and returns True if the first
appears as a substring in the second:
String comparison
-> If comparing string use ( == , <, > )
String methods
Py Script Page 10
> Strings are an example of Python objects.
> An object contains both data (the actual string itself) and methods, which are effectively
functions that are built into the object and are available to any instance of the object
> Python has a function called dir which lists the methods available for an
object. The type function shows the type of an object and the dir function shows
the available methods
-> Calling a method is similar to calling a function (it takes arguments and returns
a value) but the syntax is different. We call a method by appending the method
name to the variable name using the period as a delimiter.
-> Instead of the function syntax upper(word), it uses the method syntax
word.upper()
-> One common task is to remove white space (spaces, tabs, or newlines) from the
beginning and end of a string using the strip method:
>>> line = ' Here we go '
>>> line.strip()
'Here we go'
A method call is called an invocation; in this case, we would say that we are
invoking upper on the word.
Parsing strings
• look into a string and find a substring.
• pull out only the second half of the address from each line
• we can do this by using the find method and string slicing.
•
Format operator
The format operator, % allows us to construct strings, replacing parts of the strings with the data
stored in variables. When applied to integers, % is the modulus operator. But when the first
operand is a string, % is the format operator. The first operand is the format string, which
contains one or more format sequences that specify how the second operand is formatted. The
result is a string.
Py Script Page 11
From <https://onenote.officeapps.live.com/o/onenoteframe.aspx?ui=en-US&rs=en-AU&hid=DhO%2BtZXHZESjX7xOm2F4Ww.0
&wopisrc=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwopi.onedrive.com%2Fwopi%2Ffolders%2F5EEC33A5F1C43452!240&wdorigin=704&sc=host%3D%
26qt%3DDefault&mscc=1&wdp=0&uih=OneDrive&wdhostclicktime=1680997588489&jsapi=1&jsapiver=v1&newsession=1
&corrid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&usid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&sftc=1
&wdredirectionreason=Force_SingleStepBoot>
Py Script Page 12
Py Ch 3
Sunday, 9 April 2023 10:02 AM
If the file does not exist, open will fail with a traceback and you will not get a
handle to access the contents of the file
<<pyNwFil.py>>
-> To break the file into lines, there is a special character that represents the “end of
the line” called the newline character.
-> In Python, we represent the newline character as a backslash-n in string constants.
Even though this looks like two characters, it is actually a single character.
-> While the file handle does not contain the data for the file, it is quite easy to
construct a for loop to read through and count each of the lines in a file:
-> The reason that the open function does not read the entire file is that the file might
be quite large with many gigabytes of data. The open statement takes the same
amount of time regardless of the size of the file. The for loop actually causes the
data to be read from the file.
When the file is read using a for loop in this manner, Python takes care of splitting
the data in the file into separate lines using the newline character. Python reads
each line through the newline and includes the newline as the last character in the
line variable for each iteration of the for loop.
If you know the file is relatively small compared to the size of your main memory,
you can read the whole file into one string using the read method on the file handle.
-> It is a good idea to store the output of read as a variable because each call to read exhausts
the resource; that this form of the open function should only be used if the file data
will fit comfortably in the main memory of your computer.
We use string slicing to print out the first 20 characters of the string data stored in inp.
Py Script Page 13
Searching through a file
When you are searching through data in a file, it is a very common pattern to read
through a file, ignoring most of the lines and only processing lines which meet a
particular condition. We can combine the pattern for reading a file with string
methods to build simple search mechanisms.
-> Each of the lines ends with a newline, so the print statement, prints the string in the variable line
which includes a newline and then print adds another newline, resulting in the double spacing effect we
see.
-> line slicing to print all but the last character, but a simpler approach
is to use the rstrip method which strips whitespace from the right side of a string
Py Script Page 14
The exit function terminates the program. It is a function that we call that never returns.
Writing files
To write a file, you have to open it with mode “w” as a second parameter:
If the file already exists, opening it in write mode clears out the old data and starts
fresh, so be careful! If the file doesn’t exist, a new one is created.
The write method of the file handle object puts data into the file, returning the number of
characters written. The default write mode is text for writing (and reading) strings.
Again, the file object keeps track of where it is, so if you call write again, it adds
the new data to the end. We must make sure to manage the ends of lines as we write to the file
by explicitly inserting the newline character when we want to end a line.
The print statement automatically appends a newline, but the write method does not add the
newline automatically.
Python makes sure that all open files are closed when the program ends.
When we are writing files, we want to explicitly close the files so as to leave nothing to chance.
<<pyFiles.py>>
Debugging
When you are reading and writing files, you might run into problems with whites-
pace. These errors can be hard to debug because spaces, tabs, and newlines are
normally invisible:
The built-in function repr can help. It takes any object as an argument and
returns a string representation of the object. For strings, it represents whitespace
characters with backslash sequences:
Py Script Page 15
data into the file
-> The return value is the number of characters that were written. The file object keeps track of where it
is, so if you call write again, it adds the new data to the end of the file.
-> When you are done writing, you should close the file.
The argument of write has to be a string, so if we want to put other values in a file, we have to convert
them to strings. The easiest way to do that is with str:
From <https://onenote.officeapps.live.com/o/onenoteframe.aspx?ui=en-US&rs=en-AU&hid=DhO%2BtZXHZESjX7xOm2F4Ww.0
&wopisrc=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwopi.onedrive.com%2Fwopi%2Ffolders%2F5EEC33A5F1C43452!240&wdorigin=704&sc=host%3D%
26qt%3DDefault&mscc=1&wdp=0&uih=OneDrive&wdhostclicktime=1680997588489&jsapi=1&jsapiver=v1&newsession=1
&corrid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&usid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&sftc=1
&wdredirectionreason=Force_SingleStepBoot>
-> A string like '/home/dinsdale' that identifies a file or directory is called a path.
-> A simple filename, like memo.txt is also considered a path, but it is a relative path because
it relates to the current directory. If the current directory is /home/dinsdale, the
filename memo.txt would refer to /home/dinsdale/memo.txt.
-> A path that begins with / does not depend on the current directory; it is called an absolute path. To
find the absolute path to a file, you can use os.path.abspath:
Py Script Page 16
Databases
databases are organized like a dictionary in the sense that they map from keys to values. The biggest
difference between a database and a dictionary is that the database is on disk (or other permanent
storage), so it persists after the program ends.
The module dbm provides an interface for creating and updating database files. As an example, I’ll
create a database that contains captions for image files.
Pickling
A limitation of dbm is that the keys and values have to be strings or bytes. If you try to use any other
type, you get an error.
The pickle module can help. It translates almost any type of object into a string suitable for storage in a
database, and then translates strings back into objects.
Py Script Page 17
Writing modules
Any file that contains Python code can be imported as a module.
Programs that will be imported as modules often use the following idiom:
if __name__ == '__main__':
print(linecount('wc.py'))
__name__ is a built-in variable that is set when the program starts. If the program is running as a
script, __name__ has the value '__main__'; in that case, the test code runs. Otherwise, if the module
is being imported, the test code is skipped.
As an exercise, type this example into a file named wc.py and run it as a script. Then run the Python
interpreter and import wc. What is the value of __name__ when the module is being imported?
Warning: If you import a module that has already been imported, Python does nothing. It does not re-
read the file, even if it has changed.
If you want to reload a module, you can use the built-in function reload, but it can be tricky, so the
safest thing to do is restart the interpreter and then import the module again.
From <https://onenote.officeapps.live.com/o/onenoteframe.aspx?ui=en-US&rs=en-AU&hid=DhO%2BtZXHZESjX7xOm2F4Ww.0
&wopisrc=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwopi.onedrive.com%2Fwopi%2Ffolders%2F5EEC33A5F1C43452!240&wdorigin=704&sc=host%3D%
26qt%3DDefault&mscc=1&wdp=0&uih=OneDrive&wdhostclicktime=1680997588489&jsapi=1&jsapiver=v1&newsession=1
&corrid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&usid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&sftc=1
&wdredirectionreason=Force_SingleStepBoot>
The elements of a list don’t have to be the same type. The following list contains a string, a float,
an integer, and (lo!) another list:
Py Script Page 18
an integer, and (lo!) another list:
Unlike strings, lists are mutable because you can change the order of items in a
list or reassign an item in a list. When the bracket operator appears on the left
side of an assignment, it identifies the element of the list that will be assigned.
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print(numbers)
[17, 5]
Traversing a list
• Way to traverse the elements of a list is with a for loop.
for cheese in cheeses:
print(cheese)
-> You only need to read the elements of the list. But if you want to write or update the
elements, you need the indices. A common way to do that is to combine the
functions range and len:
-> This loop traverses the list and updates each element.
• len returns the number of elements in the list.
• range returns a list of indices from 0 to n − 1, where n is the length of the list.
-> A for loop over an empty list never executes the body:
for x in empty:
print('This never happens.')
-> Although a list can contain another list, the nested list still counts as a single element. The
length of this list is four:
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
List Operations
• The + operator concatenates lists
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b // [ 1, 2, 3, 4, 5, 6 ]
• List slices
The slice operator also works on lists:
lists are mutable, it is often useful to make a copy before performing operations that fold,
spindle, or mutilate lists.
//mutability
Py Script Page 19
t[1:3] = ['x', 'y']
Print(t) //['a', 'x', 'y', 'd', 'e', 'f']
List methods
• Python provides methods that operate on lists.
Deleting Elements
There are several ways to delete elements from a list
If you know the index of the element you want, you can use pop
pop modifies the list and returns the element that was removed. If you don’t
provide an index, it deletes and returns the last element
t = ['a', 'b', 'c']
X = t.pop()
Print(t) // [ 'a', 'c' ]
Print(x) // b
-> If you don’t need the removed value, you can use the 'del' operator:
t = ['a', 'b', 'c']
del t[1] // [ 'a', 'c' ]
-> If you know the element you want to remove (but not the index), you can use
remove: The return value from remove is None
t = ['a', 'b', 'c']
t.remove('b') // [ 'a', 'c' ]
-> To remove more than one element, you can use del with a slice index:
t = ['a', 'b', 'c', 'd', 'e', 'f']
del t[1:5]
print(t) // [ 'a', 'f' ]
-> As usual, the slice selects all the elements up to,
but not including, the second index.
Lists and Functions
There are a number of built-in functions that can be used on lists that allow you
to quickly look through a list without writing your own loops:
-> The sum() function only works when the list elements are numbers.
The other functions (max(), len(), etc.) work with lists of strings and other types that can
be comparable.
-> We could simply remember each number as the user entered it and use built-in
functions to compute the sum and count at the end.
numlist = list()
while (True):
inp = input('Enter a number:' )
if inp == 'done': break
value = float(inp )
Py Script Page 20
numlist.append(value)
average = sum(numlist) / len(numlist)
print('Average:', average)
Lists and Strings
• A string is a sequence of characters and a list is a sequence of values, but a list
of characters is not the same as a string. To convert from a string to a list of
characters, you can use list:
s = 'spam'
T = list( s )
Print( T ) // [ 's', 'p', 'a', 'm' ]
• You can call split with an optional argument called a delimiter that specifies which characters to use as
word boundaries. The following example uses a hyphen as a delimiter:
s = 'spam-spam-spam'
delimiter = '-'
s.split(delimiter)
['spam', 'spam', 'spam']
-> join is the inverse of split. It takes a list of strings and concatenates the elements, join is a
string method, so you have to invoke it on the delimiter and pass the list, as a parameter:
In one case, a and b refer to two different objects that have the same value. In the
second case, they refer to the same object.
To check whether two variables refer to the same object, you can use the is oper-
ator.
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
In this example, Python only created one string object, and both a and b refer to
it.
But when you create two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
-> the two lists are equivalent, because they have the same elements, but not identical, because
they are not the same object. If two objects are identical, they are also equivalent, but if they are
equivalent, they are not necessarily identical
Py Script Page 21
If a refers to an object and you assign b = a, then both variables refer to the same
object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
->
==============================================================
=
The association of a variable with an object is called a reference. In this example,
there are two references to the same object.
An object with more than one reference has more than one name, so we say that
the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:
b[0] = 17
print(a)
[17, 2, 3]
----------------------------------------------------------------------------------------------------------
----------
For immutable objects like strings, aliasing is not as much of a problem. In this
example:
a = 'banana'
b = 'banana'
it almost never makes a difference whether a and b refer to the same string or not.
List arguments
When you pass a list to a function, the function gets a reference to the list. If
the function modifies a list parameter, the caller sees the change.
def delete_head(t):
del t[0]
letters = ['a', 'b', 'c']
delete_head(letters)
print(letters)
['b', 'c']
t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print(t1)
[1, 2, 3]
>>> print(t2)
None
>>> t3 = t1 + [3]
>>> print(t3)
[1, 2, 3]
>>> t2 is t3
False
The slice operator creates a new list and the assignment makes t refer to it, but
none of that has any effect on the list that was passed as an argument.
An alternative is to write a function that creates and returns a new list.
Py Script Page 22
Dictionaries
From <https://onenote.officeapps.live.com/o/onenoteframe.aspx?ui=en-US&rs=en-AU&hid=DhO%2BtZXHZESjX7xOm2F4Ww.0
&wopisrc=https%3A%2F%2Fround-lake.dustinice.workers.dev%3A443%2Fhttps%2Fwopi.onedrive.com%2Fwopi%2Ffolders%2F5EEC33A5F1C43452!240&wdorigin=704&sc=host%3D%
26qt%3DDefault&mscc=1&wdp=0&uih=OneDrive&wdhostclicktime=1680997588489&jsapi=1&jsapiver=v1&newsession=1
&corrid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&usid=dfdb61d2-bfa5-40c2-b418-a26caea354cc&sftc=1
&wdredirectionreason=Force_SingleStepBoot>
Py Script Page 23
Functions
Friday, 28 April 2023 2:47 PM
Py Script Page 24
List & tuples
Friday, 28 April 2023 8:48 AM -> method to modify tuple through list
1. Int
2. Float
3. Complex ( x + yi )
Tuple assignment
Py Script Page 25
Mixed[ :3 ] //0,1,2
Ex: num = [ 12, 'a', 'Rama', 3.14565, ( 3+7i ) ] Mixed[ 3: ] //4, till last element
Mixed [ :: 2 ] //extract every second element
Mixed[ 1: 7: 2 ] // print every second element from index 1 to 7
Operation on Lists
1. Multiplication operation
2. Concatenating list
Methods on Lists
2. Extend the list :: means adding the elements of a list into another list
Py Script Page 26
Screen clipping taken: 1/05/2023 2:51 PM
5. MIN, MAX, List Length and SUM method to run on list containing Integer elements only
1. Tuple has not any method what are present in List like append, insert, remove as it's Immutable
Tuples
• Tuple is a collection of Immutable Heterogenous python objects
Creating Tuples
1. city = "Pune",
city = ( "Pune" )
city = ( "Pune", "Delhi", "Bangalore", "Calcutta" )
city = "Pune", "Banbhora", "Buklana", "Siana"
Py Script Page 27
2. But Tuple can be concatenated and nest tuple
2. Max : max in the tuple, min : min in the tuple, sum : sum of all elements of the tuple
Len: total number of elements in the tuple
-> Assigning tuple to variables
a : first element
c: last element
b: has all other element except a & b Converting a List to a Tuple
Py Script Page 28
2. Can perform List operation
Py Script Page 29
String
Monday, 1 May 2023 6:00 PM
String is a datatype in Python composed of collection of characters Len function works on string
And particular index can be accessed as accessing array through Indexes
Strg = 'Variable' // "Variable"
1. When using single quote, can't use single apostrophe ( ' ) inside that string
2. When using double quote, can't use single ( " ) inside that string
3. Use escape character ( \ ) with either of condition to make it work
4. But if using single quote inside a string make sure to make outside string to put in
Double quote and vice versa, if can't make it possible use escape sequence character
Slicing in string
String is a sequence
Can print characters using for loop
Py Script Page 30
2. Find method returns the index of the first occurrence of character
And Index in built method is also same as find
3. Split method that split the string based on the delimiter constant you want to apply
5. Replace method replace the character or string from the existing string
Py Script Page 31
6. Concatenating string
Py Script Page 32
Screen clipping taken: 2/05/2023 12:17 PM
Py Script Page 33
Sets and Dict
Monday, 1 May 2023 6:01 PM
Dictionary
But data stored in Dict is in Unordered format and in the key: value pair form
Py Script Page 34
Py Script Page 35