0% found this document useful (0 votes)
420 views

Py Script PDF

This document provides an overview of key concepts in Python including variables, data types, operators, conditional execution, functions, classes and exceptions. It explains variables and how they store and reference values. It also covers built-in data types like integers, floats and strings. Operators for arithmetic, comparison and logical operations are defined. The basics of conditional execution with if/else statements and boolean logic are explained. Finally, it touches on concepts like functions, classes and exceptions handling.

Uploaded by

Pooja Handuja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
420 views

Py Script PDF

This document provides an overview of key concepts in Python including variables, data types, operators, conditional execution, functions, classes and exceptions. It explains variables and how they store and reference values. It also covers built-in data types like integers, floats and strings. Operators for arithmetic, comparison and logical operations are defined. The basics of conditional execution with if/else statements and boolean logic are explained. Finally, it touches on concepts like functions, classes and exceptions handling.

Uploaded by

Pooja Handuja
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Few links

Thursday, 20 April 2023 5:01 PM

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.

message = 'And now for something completely different'


Print(message) o/p : the assigned string

Similar for other like Integer & float

M = 16
Pi = 3.14592653589793

Print(M) // output : 16 ; type(M) ; <class 'int'>


Print(Pi) // output : pi value ; type( pi) : <class 'float'>

Variable Names & Keywords


Variable names can be arbitrarily long. They can contain both letters and numbers,
but they cannot start with a number.

Ex: 76trombones = 'big parade' results in SyntaxError: invalid syntax

The underscore character ( _ ) can appear in a name. But @ is an illegal character.

Python has 35 reserveded keywords

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.

A script usually contains a sequence of statements. If there is more than one


statement, the results appear one at a time as the statements execute.

print(1)
x=2
print(x)

produces the output


1
2
Operators & operands
The operators +, -, *, /, and ** perform addition, subtraction, multiplication, division, and exponentiation,

In Python 3.x, the result of this division is a floating point result:


minute = 59
>>> minute/60
0.9833333333333333

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

>>> first = 'Test '


>>> second = 3
>>> print(first * second)
Test Test Test

Asking the user for input


Python provides a built-in function called input that gets input from the keyboard. When this function is called,
the program stops and waits for the
user to type something.
When the user presses Return or Enter, the program
resumes and input returns what the user typed as a string.

>>> inp = input()


Some silly stuff
>>> print(inp)
Some silly stuff
-> Before getting input from the user, it is a good idea to print a prompt telling the
user what to input. You can pass a string to input to be displayed to the user before pausing for input

name = input('What is your name? \n')


The sequence \n at the end of the prompt represents a newline, which is a special character that causes a line
break. That’s why the user’s input appears below the prompt.

-> 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:

prompt = 'What...is the airspeed velocity of an unladen swallow?\n'


speed = input(prompt)
print('as a string', speed)
speed = int(speed)
print('as a integer', speed)
speed = speed + 5
print(speed)

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:

-> A blank line at the end of a block of


statements is not necessary when writing
And executing a script, but it may
improve readability of your code.
Chained Conditionals

There is no limit on the number of elif statements

Nested conditionals

Can have other elif statement

Catching exceptions using try and exception


Try and exception is used when we aware of a situation that can cause
Our program to stop at that point.

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.

Stack diagrams for recursive functions


Every time a function gets called, Python creates a frame to contain the function’s local variables and
parameters. For a recursive function, there might be more than one frame on the stack at the same
time.

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

RuntimeError: Maximum recursion depth exceeded


Functions:

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.

max function tells us the “largest character” in the string.


the min function shows us the smallest character

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

-> float converts integers and strings to floating-point numbers:


float('3.14159')
3.14159

-> Finally, str converts its argument to a string:

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)

• To choose an element from a sequence at random, you can use choice:


t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3

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.

-> To end the function, you have to enter an empty line


-> Function definitions get executed just like other statements, but the effect is to
create function objects. The statements inside the function do not get executed
until the function is called, and the function definition generates no output.

-> 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:

Definite loops using for


to loop through a set of things such as a list of words, the lines in a file, or a list of numbers. When we
have a list of things to loop through, we can construct a definite loop using a for statement. We call the
while statement an indefinite loop because it simply loops until some condition becomes False,
the for loop is looping through a known set of items so it runs through as many iterations as there are
items in the set.

-> 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:

-> Length of a string using len

Traversal through a string with a loop


Often they start at the beginning, select each character in turn, do something to it, and continue
until the end. This pattern of processing is called a traversal.

Py Script Page 9
Another way to traverse; the String

for char in fruit:


print(char)

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.

Fruit[ : ] // returns the complete string

Strings are Immutable


-> It is tempting to use the operator on the left side of an assignment, with the
intention of changing a character in a 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.

->> string methods


https://docs.python.org/3/library/stdtypes.html#string-methods
https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

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.

the format sequence %d means that the second operand should be


formatted as an integer (“d” stands for “decimal”):

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

When you open a file, you are


asking the operating system to find the file by name and make sure the file exists.

You are given a handle if the requested file exists and


you have the proper permissions to read the file.

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

Letting the user choose the file name

Using try, except, and open


We need to assume that the open call might fail and add recovery code when the open fails as
follows:

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:

Reading and writing


-> 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.
-> 'open' returns a file object that provides methods for working with the file. The write method puts
data into the file

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:

Don't use comma in print statement if using format characters to print

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>

Filenames and paths


The os module provides functions for working with files and directories (“os” stands for “operating
system”). os.getcwd returns the name of the current directory:

-> 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>

List And Dictionaries


• Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any
type. The values in list are called elements or sometimes items.
• Ex:

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:

A list with empty bracket


Called empty list
Lists are Mutable
The expression inside the brackets specifies the index. Remember that the indices start at 0:

cheeses = ['Cheddar', 'Edam', 'Gouda']


print( cheeses[0] ) // Cheddar

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 ]

• The * operator repeats a list a given number of times:


[1, 2, 3] * 3 // [1, 2, 3, 1, 2, 3, 1, 2, 3]

• 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.

T = ['a', 'b', 'c', 'd', 'e', 'f']


t[1:3] // [ 'b', 'c']

T[ :4 ] // [ 'a', 'b', 'c', 'd' ]


T[ 3: ] // [ 'd', 'e', 'f' ]
T[ : ] // [ 'a', 'b', 'c', 'd', 'e', 'f' ]

//mutability

t[1:3] = ['x', 'y']

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.

t = ['a', 'b', 'c']


t.append('d') // ['a', 'b', 'c', 'd']

• extend takes a list as an argument and appends all of the elements:


t1 = ['a', 'b', 'c']
t2 = ['d', 'e']
t1.extend(t2) // This example leaves t2 unmodified.

• sort arranges the elements of the list from low to high:


Most list methods are void; they modify the list and return None.
t = ['d', 'c', 'e', 'b', 'a']
t.sort()
Print(t) // ['a', 'b', 'c', 'd', 'e']

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.

nums = [3, 41, 12, 9, 74, 15]


Len( nums ), max( nums ), min( nums ), and sum( nums )

-> 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' ]

-> The list function breaks a string into individual letters.


If you want to break a string into words, you can use the split method:

s = 'pining for the fjords'


T = s.split( )
Print( T )
//['pining', 'for', 'the', 'fjords'

• 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:

t = ['pining', 'for', 'the', 'fjords']


delimiter = ' '
delimiter.join(t)
Objects and values
a = 'banana'
b = 'banana'
we know that a and b both refer to a string, but we don’t know whether they refer
to the same string. There are two possible states:

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.

delete_head removes the first element from a list:

def delete_head(t):
del t[0]
letters = ['a', 'b', 'c']
delete_head(letters)
print(letters)
['b', 'c']

-> the append method modifies a list,


but the ' + ' operator creates a new list:

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

-> In Built Math function

Screen clipping taken: 28/04/2023 3:19 PM

Screen clipping taken: 28/04/2023 3:26 PM

Py Script Page 24
List & tuples
Friday, 28 April 2023 8:48 AM -> method to modify tuple through list

List_X = [ 32, 34, 987 ] Dealing with Files


List_X[0] = 97 1. X = open( ' path_to_file ', 'r' )
X pointer to file path
Print( List_X )

-> [ 97, 34, 987 ]


Data Types in Python

1. Int
2. Float
3. Complex ( x + yi )

Tuple : are Immutable

Screen clipping taken: 28/04/2023 2:18 PM

Screen clipping taken: 28/04/2023 12:16 PM


1. Power of x^y
x**y

Screen clipping taken: 28/04/2023 9:35 AM

Tuple assignment

Screen clipping taken: 28/04/2023 12:19 PM

Screen clipping taken: 28/04/2023 11:38 AM

Screen clipping taken: 28/04/2023 11:47 AM

Tuple is Immutable like this as well

Screen clipping taken: 28/04/2023 11:49 AM

List Accessing elements inside the lists

1. Extracting elements value from the list.


1. List is a collection of data, and can hold values of multiple data types. mixed[ IndexFrom : IndexTo ]
2. It start from index zero mixed[ 1: 3 ] // extract element 1,2,
3. Can have list inside list like a 2D array in C. mixed[ 0: 2 ] // 0,1,
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

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

Screen clipping taken: 28/04/2023 3:30 PM

Screen clipping taken: 28/04/2023 3:41 PM

Mixed [ :: -1 ] // list printed in reverse order

Screen clipping taken: 1/05/2023 1:55 PM

Operation on Lists

1. Multiplication operation

2. Concatenating list

Screen clipping taken: 1/05/2023 2:42 PM

3. Creating a list of character from a String

Screen clipping taken: 1/05/2023 2:42 PM

4. Dividing a list into number of different list

Methods on Lists

1. Append list : element will be added in the end of list

Screen clipping taken: 1/05/2023 2:49 PM

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

3. Insert and removing elements from the list

Insert will add element at the particular index in the list.


Remove will delete the single occurrence of the particular method passed to the variable

Screen clipping taken: 1/05/2023 2:56 PM

4. Provide SORT method to work on LIST

Screen clipping taken: 1/05/2023 3:41 PM

5. MIN, MAX, List Length and SUM method to run on list containing Integer elements only

Screen clipping taken: 1/05/2023 3:56 PM

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

• xTuple = ( 1, 89, 'A', 'Rama', 'Laxman' )

• Indices of elements starts from zero

Creating Tuples

1. city = "Pune",
city = ( "Pune" )
city = ( "Pune", "Delhi", "Bangalore", "Calcutta" )
city = "Pune", "Banbhora", "Buklana", "Siana"

2. But Tuple can be concatenated and nest tuple

Py Script Page 27
2. But Tuple can be concatenated and nest tuple

2. Accessing Tuple elements

Slicing the Tuple 3. Repetition is allowed

Screen clipping taken: 1/05/2023 4:58 PM

Built In Functions in Tuple

1. count : number of same elements in the tuple

Screen clipping taken: 1/05/2023 4:47 PM

3. Unpacking the 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

-> not sure of number of elements in Tuple

Screen clipping taken: 1/05/2023 5:19 PM

a : first element
c: last element
b: has all other element except a & b Converting a List to a Tuple

4. Deleting a Tuple 1. Use api tuple to convert list to tuple

Use of del keyword

Screen clipping taken: 1/05/2023 5:14 PM

Method to modify tuple


1. Add tuples as a part of List

Py Script Page 28
2. Can perform List operation

Use of append, remove

Removing tuple from list

Nesting Lists withing Tuple


1. Creating list within tuples

Screen clipping taken: 1/05/2023 5:59 PM

2. Modifying list within the tuple

Screen clipping taken: 1/05/2023 5:59 PM

3. Can't add more list to tuple as tuple is Immutable

Screen clipping taken: 1/05/2023 6:00 PM

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

Screen clipping taken: 2/05/2023 10:16 AM

Slicing in string

String is a sequence
Can print characters using for loop

Screen clipping taken: 2/05/2023 10:14 AM

Screen clipping taken: 2/05/2023 10:59 AM

Methods supported on a string

Don't change the string just modify the appearance

1. Like Upper( ) and lower( ) method

2. Find method returns the index of the first occurrence of character

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

Split results in List


Split returns the List after the split call on the string.
Split removes the delimiting constant from where the split called.

4. Rpartition method returns the Tuple based on delimiter passed


Rpartition call doesn't alter the string content

Screen clipping taken: 2/05/2023 11:42 AM

5. Replace method replace the character or string from the existing string

Py Script Page 31
6. Concatenating string

Screen clipping taken: 2/05/2023 11:39 AM

Format method on String

Give the format first by providing placeholder ( { } are placeholder )


-> Placeholder shouldn't have space
-> if numbering placeholders do it from beginning
-> Indexes shouldn't be more than the number of argument

Screen clipping taken: 2/05/2023 12:12 PM

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

Is a data structure like List and tuple

But data stored in Dict is in Unordered format and in the key: value pair form

Every element is pair of key and value


Key is like an Index, what we have in list and tuples, and it can be Integer

Creating dictionary data structure syntax:

Another method using dict( ) built in function

Py Script Page 34
Py Script Page 35

You might also like