0% found this document useful (0 votes)
35 views43 pages

Python Summerized Notes

Uploaded by

melodygunda6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views43 pages

Python Summerized Notes

Uploaded by

melodygunda6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Identifiers

• Name of programming elements used in python e.g. variable (named


data storage), function, class, module, etc
• Python has some rules about how identifiers can be formed

?????????????????????????????????????
Identifiers
• Python has some rules about how identifiers can be formed
• Every identifier must begin with a letter or underscore, which may be
followed by any sequence of letters, digits, or underscores

>>> x1 = 10
>>> x2 = 20
>>> y_effect = 1.5
>>> celsius = 32
>>> 2celsius
File "<stdin>", line 1
2celsius
^
SyntaxError: invalid syntax
Identifiers
• Python has some rules about how identifiers can be formed
• Identifiers are case-sensitive

>>> x = 10
>>> X = 5.7
>>> print(x)
10
>>> print(X)
5.7
Identifiers
• Python has some rules about how identifiers can be formed
• Some identifiers are part of Python itself (they are called reserved words or
keywords) and cannot be used by programmers as ordinary identifiers
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Python Keywords
Identifiers
• Python has some rules about how identifiers can be formed
• Some identifiers are part of Python itself (they are called reserved words or
keywords) and cannot be used by programmers as ordinary identifiers

>>> for = 4
File "<stdin>", line 1
An example… for = 4
^
SyntaxError: invalid syntax
Expressions
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
▪ This is an expression that uses the >>> print(x)
addition operator 5
>>> print(5 * 7)
35
>>> print("5" + "7")
Expressions
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
▪ This is an expression that uses the >>> print(x)
addition operator 5
>>> print(5 * 7)
▪ This is another expression that uses the 35
multiplication operator >>> print("5" + "7")
57
Expressions
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 2 + 3
▪ This is an expression that uses the >>> print(x)
addition operator 5
>>> print(5 * 7)
▪ This is another expression that uses the 35
multiplication operator >>> print("5" + "7")
57
▪ This is yet another expression that uses the
addition operator but to concatenate (or glue)
strings together
Expressions
• You can produce new data (numeric or text) values in your program
using expressions
>>> x = 6 >>> print(x*y)
>>> y = 2 12
>>> print(x - y) >>> print(x**y)
Another 4 Yet another 36
example… >>> print(x/y) example… >>> print(x%y)
3.0 0
>>> print(x//y) >>> print(abs(-x))
3 6
Expressions: Summary of Operators
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Float Division
** Exponentiation
abs() Absolute Value
// Integer Division
% Remainder

Python Built-In Numeric Operations


Python - Functions
• A function is a block of organized, reusable code that is used to perform a
single, related action.
• Functions provides better modularity for your application and a high
degree of code reusing.

• 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
•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.
•The code block within every function starts with a colon
(:) and is indented.
•The statement return [expression] exits a function,
optionally passing back an expression to the caller. A
return statement with no arguments is the same as
return None.
Syntax:
def functionname( parameters ):
return [expression] #optional

By default, parameters have a positional behavior, and you need to


inform them in the same order that they were defined.
• Example:
• def prime():
a=1
print(a)
prime()
Python

Control Structures
SEQUENCE SELECTION ITERATION

CONDITIONAL AND ITERATIVE STATEMENTS


2. SELECTION

A selection statement causes the program control to be transferred


to a specific flow based upon whether a certain condition is true or
not.
CONDITIONAL CONSTRUCT – if else STATEMENT

Conditional constructs (also known as if statements) provide a way to


execute a chosen block of code based on the run-time evaluation of one or
more Boolean expressions.

In Python, the most general form of a conditional is written as follows:

Contd.. Next Slide


CONDITIONAL CONSTRUCT – if else STATEMENT

: Colon Must

if first condition:
first body
elif second condition:
second body
elif third condition:
third body
else:
fourth body
CONDITIONAL CONSTRUCT – if else STATEMENT

FLOW CHART

Conditi False
Statement 1 Statement 2
on ?

Main True
Body
Statement 1

else
Statement 2 body
EXAMPLES – if STATEMENT

else is missing, it is
an optional
statement

OUT PUT
EXAMPLE – if else STATEMENT

: Colon Must

else is used

OUT PUT
3. ITERATION OR LOOPING

What is loop or iteration?


Loops can execute a block of code number of times until a certain
condition is met.
OR
The iteration statement allows instructions to be executed until a
certain condition is to be fulfilled.
The iteration statements are also called as loops or Looping
statements.
3. ITERATION OR LOOPING

Python provides two kinds of loops & they are,

while loop

for loop
while loop

A while loop allows general repetition based upon the repeated


testing of a Boolean condition

The syntax for a while loop in Python is as follows:


while condition:
body : Colon Must
Where, loop body contain the single statement or set of
statements (compound statement) or an empty statement.
Contd..
while loop - programs
# Natural Numbers generation

OUTPUT
for LOOP - range KEYWORD

The range() function returns a sequence of numbers,


starting from 0 by default, and increments by 1 (by default),
and ends at a specified number.

range(start, stop, step)

x = range(3, 6)
for n in range(3,6):
OR for n in x:
print(n)
print(n)
for LOOP - range KEYWORD

#Generating series of numbers

OUTPUT
Python Data Structures
Terms We'll Use
• Data structure-A way of organizing or storing
information.
• Ordered-The data structure has the elements
stored in an ordered sequence
• Mutable-The contents of the data structure can
be changed.
• Immutable-The contents of the data structure
cannot be changed.
Built in Types

• Lists
• Tuples
• Sets
• Dictionaries
Lists
• An ordered group of items

• Does not need to be the same type

• Could put numbers, strings or donkeys in the same list

• List contain items separated by a comma, and enclosed within square brackets[]. They
are mutable.

• List notation

• A = [1,”This is a list”, c, Donkey(“Kong”)]


Examples of other methods
• a = [66.25, 333, 333, 1, 1234.5] //Defines List
– print (a.count(333), a.count(66.25), a.count('x') ) //calls method
– 2 1 0 //output

• a.reverse() //Reverses order of list


– print (a.reverse()) //Prints reversed list
– [1234.5, 1, 333, 333, 66.25] //Output
• a.reverse()
• print(a)

• print(a.sort())
– [ 1, 66.25, 333, 333, 1234.5] //Output

• a.index(333)
• print(a.index(333)) //Returns the first index where the given value appears
– 1//output

• print(a[0]) Output?????????
• print(a[1:3]) Output???????
• print(a+a) Output ???????
Tuples
Tuples are ordered, immutable collections of elements.

The only difference between a tuple and a list is that once a tuple has been made, it
can't be changed!

Tuples contain items separated by a comma, and are enclosed in parenthesis.

Making a tuple:
a = (1, 2, 3)
Examples
a = (66.25, 333, 333, 1, 1234.5) //Defines Tuple
• print(a) //Prints tuple a
• 66.25, 333, 333, 1, 1234.5 //Output

• a.index(333)
– print(a.index(333) )//Returns the first index where the given value appears
– 1 //output

• print(a[0])Output?????????

• print(a[0:3]) Output???????

• print(a+a) Output ???????


Sets
A set is an unordered collection of elements where each element must be unique.
Attempts to add duplicate elements are ignored.
Creating a set:
mySet = set(['a', 'b', 'c', 'd'])
Or:
myList = [1, 2, 3, 1, 2, 3]
mySet2 = set(myList)
Note that in the second example, the set would consist of the elements ??????
Sets
Things we can do with a set:

mySet = set(['a‘])

# Add an element:
mySet.add(‘e')
print(mySet)
mySet.add(‘a')
print(mySet)
Output ???????????

#Remove an element:
mySet.remove('b')
print(mySet)
Output ????????????
Dictionaries
Dictionaries let use whatever kind of keys we want!
Instead of having 1 correspond to 'b', I can have "hello" correspond to 'b'.
Before: Now I can do things like:
0 'a' "Hello" 'a'
1 'b' 1 'b'
2 'c' 3.3 'c'
Dictionaries
myDict = {}

Keys are enclosed in single quotes (‘’) plus a colon


separated by a comma.

Values are enclosed in double quotes if they are


strings. (“”)

e.g.

myDict ={‘student’: “John”, ‘age’: 20}


Dictionaries
e.g
dict= {ʻnameʼ: “Rise”, ʻcodeʼ:8, ʻdeptʼ: “CS”}
Determine the Output of the following:

print(dict[ʻnameʼ])

print(dict)

print(dict.values())

print(dict.keys())
Exceptions

What is an exception?

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

For Example
Handling Exceptions

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

note that a user-generated interruption is signalled by raising the


KeyboardInterrupt exception.
Handling Exceptions

For Example

You might also like