Python Notes
Python Notes
Python Notes
2
Section 3, Lecture 27
Notes and summary for section 2
If statements in Python:
In order to write useful programs, we almost always need the ability to check
conditions to change the behavior of the program accordingly. Conditional statements
allow us to do so. The simplest form is the if statement, which has the general form:
if BOOLEAN EXPRESSION:
STATEMENTS
The colon (:) is significant and required. It separates the header of the compound statement from
the body.
The line after the colon must be indented. It is standard in Python to use four spaces
for indenting.
All lines indented the same amount after the colon will be executed whenever the
BOOLEAN_EXPRESSION is true.
The boolean expression after the if statement is called the condition. If it is true, then
all the indented statements get executed. What happens if the condition is false, In a
simple if statement like this, nothing happens, and the program continues on to the
next statement.
Sometimes there are more than two conditions and we need more than two branches.
In such cases we use the elif statement.elif is an abbreviation of else if. Again, exactly
one branch will be executed. There is no limit of the number of elif statements but
only a single (and optional) final else statement is allowed and it must be the last
branch in the statement:
if choice == 'a':
print("You chose 'a'.")
elif choice == 'b':
print("You chose 'b'.")
elif choice == 'c':
print("You chose 'c'.")
else:
print("Invalid choice.")
Each condition is checked in order. If the first is false, the next is checked, and so on.
If one of them is true, the corresponding branch executes, and the statement ends.
Lists in Python:
Python has six built-in types of sequences, but the most common ones are lists and
tuples.
There are certain things you can do with all sequence types. These operations include
indexing, slicing, adding, multiplying, and checking for membership. In addition,
Python has built-in functions for finding the length of a sequence and for finding its
largest and smallest elements. The list is a most versatile datatype available in Python
which can be written as a list of comma-separated values (items) between square
brackets. Important thing about a list is that items in a list need not be of the same
type.
For example
Insert function:
This function allows you to insert some item to the list, this function is similar to
append but
it allows you to insert item at a particular position.
example:
fruits.insert(1,"banana")
This line of code places the item banana at position 1 in the list fruits.
example:
>>> range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
a = range(1, 10)
for i in a:
print i
for a in range(21,-1,-2):
print a,
#output>> 21 19 17 15 13 11 9 7 5 3 1
>>> range(20,0,-2)
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
Functions in Python:
A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high
degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but
you can also create your own functions. These functions are called user-defined
functions.
Defining a function:
You can define functions to provide the required functionality. Here are simple rules
to define a function in Python. Function blocks begin with the keyword def followed
by the function name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
Calling a function:
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.Once the basic structure of a
function is finalized, you can execute it by
calling it from another function or directly from the Python prompt.
This is another example of a compound statement in Python, and like the branching
statements, it has a header terminated by a colon (:) and a body consisting of a
sequence of one or more statements indented the same
amount from the header.The loop variable is created when the for statement runs, so
you do not need to
create the variable before then. Each iteration assigns the the loop variable to the next
element in the sequence, and then executes the statements in the body. The statement
finishes when the last element in the sequence is reached.This type of flow is called a
loop because it loops back around to the top after each
iteration.
while BOOLEAN_EXPRESSION:
STATEMENTS
Like the branching statements and the for loop, the while statement is a compound
statement consisting of a header and a body. A while loop executes an unknown
number of times, as long at the BOOLEAN EXPRESSION is true.
def add(a,b):
return a + b
def square(c):
return c * c
square(add(2,3))
Modules in Python:
A module allows you to logically organize your Python code. Grouping related code
into a module
makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.Simply, a module is a file
consisting of Python code. A module can define functions, classes and variables. A
module can also include runnable code. You can use any Python source file as a
module by executing an import statement in some other Python source file.
example:
import module_name
Here module_name is the name of the module which contains the code which you
want to use.
Browse Q&A
Continue
Show curriculum navigation
Go to Dashboard
Exceptions
Even if a statement or expression is syntactically correct, it
may cause an error when an attempt is made to execute it.
Errors detected during execution are called exceptions and are
not unconditionally fatal. It is possible to write programs that
handle selected exceptions. Look at the following example,
which asks the user for input until a valid integer has been
entered, but allows the user to interrupt the program (using
Control-C or whatever the operating system supports).
while True:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Oops! That was no valid number. Try again..."
First, the try clause (the statement(s) between the try and
except keywords) is executed.If no exception occurs, the
except clause is skipped and execution of the try statement is
finished.If an exception occurs during execution of the try
clause, the rest of the clause is skipped. Then if its type
matches the exception named after the except keyword, the
except clause is executed, and then execution continues after
the try statement.If an exception occurs which does not match
the exception named in the except clause, it is passed on to
outer try statements; if no handler is found, it is an unhandled
exception and execution stops with a message as shown
above.
Syntax
r+ : Opens a file for both reading and writing. The file pointer
placed at the
beginning of the file.