Python Module 1 PN
Python Module 1 PN
8:56 PM
Errors
Syntax errors
A syntax error means that you have violated the “grammar”
rules of Python.
>>> primt 'Hello world!'
Logic errors
A logic error is when your program has good syntax but there
is a mistake in the order of the statements or perhaps a
mistake in how the statements relate to one another.
Semantic errors
A semantic error is when your description of the steps to take
is syntactically perfect and in the right order, but there is
simply a mistake in the program. The program is perfectly
correct but it does not do what you intended for it to do.
• >>> type(17)
• <class 'int'>
• >>> type(3.2)
<class 'float'>
New Section 1 Page 9
• <class 'float'>
• If the values are entered in quotes, then the interpreter
treats it as string
• >>> type(‘22')
• <class 'str'>
• >>> type(‘5.1')
<class 'str'>
Variables
• A variable is a named place in the memory where a
programmer can store data and retrieve it later using the
variable “name”
• A variable is a name that refers to a value.
• Programmers can choose the names of the variables and they
can change the contents of a variable in a later statement
New Section 1 Page 10
can change the contents of a variable in a later statement
• A=22
• B=45
• A=60
Python Variable Name Rules
Must start with a letter or underscore _
Must consist of letters, numbers, and underscores
Ex: att, _marks, Sem4
Case Sensitive ------marks, Marks, MARKS
Statements
• A statement is a unit of code that the Python interpreter
can execute.
• Two examples of statements: print being an expression
statement and assignment.
• When we type a statement in interactive mode, the
interpreter executes it and displays the result, if there is
only one statement
• 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.
• Ex
print(5)
x = 10
print(x)
20+32
hour-1
hour*60+minute
minute/60
5**2
(5+9)*(15-7)
Expressions
An expression is a combination of values, variables, and
New Section 1 Page 14
An expression is a combination of values, variables, and
operators. A value all by itself is considered an expression,
and so is a variable
17
x
x + 17
>>> x = 2
>>> x = x + 2
>>> print(x)
4
>>> y = 440 * 12
>>> print(y)
5280
>>> z = y / 1000
>>> print(z)
5.28
New Section 1 Page 15
5.28
Order of operations
When more than one operator appears in an expression,
the order of evaluation depends on the rules of
precedence.
PEMDAS
Highest precedence rule to lowest precedence rule:
Parentheses
Left to right
>>> x =1+2**3/4*5
>>> print(x)
11
2 * (3-1)
2**1+1 is 3 , not 4
3*1**3 is 3, not 27
So 2*3-1 is 5 , not 4
6+4/2 is 8, not 5
5-3-1 is 1, not 3
Modulus operator
The modulus operator works on integers and yields
the remainder when the first
New Section 1 Page 17
the remainder when the first
operand is divided by the second.
>>> quotient = 7 // 3
>>> print(quotient)
2
>>> remainder = 7 % 3
>>> print(remainder)
1
String operations
• + operator performs concatenation, which means
joining the strings by linking them end to end.
>>> first = 10
>>> second = 15
>>> print(first+second)
25
>>> first = '10'
>>> second = '15'
>>> print(first + second)
1015
Comments
New Section 1 Page 20
Comments
• As the programs become bigger and complex it is
difficult to read and interpret the code.
• For this reason, it is a good idea to add notes to your
programs to explain in natural language what the
program is doing.
a = 30
b = 40
c = (a + b)/2
Print(c)
first_ia = 30
second_ia = 40
ia = (first_ia+second_ia)/2
print(ia)
x1q3z9ahd = 30
x1q3z9afd = 40
x1q3p9afd = (x1q3z9ahd + x1q3z9afd)/2
print(x1q3p9afd)
New Section 1 Page 22
print(x1q3p9afd)
Common Errors
• Illegal variable name, like class and yield, which are
keywords
• Illegal characters in variable name, such as, odd~job
and US$
• Space in a variable name, Python thinks it is two
operands without an operator:
>>> month = 09
File "<stdin>", line 1
month = 09
^
SyntaxError: invalid token
Conditional execution
Boolean expressions
• Booleans represent one of two values:
True or False.
x == y # x is equal to y
x != y # x is not equal to y
x>y # x is greater than y
x<y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
New Section 1 Page 25
x <= y # x is less than or equal to y
• Identity operators are used to compare the objects,
not if they are equal, but if they are actually the same
object, with the same memory location:
x is y # x is the same as y
x is not y # x is not the same as y
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
print(x is y)
print(x == y)
Logical operators
and---Returns True if both statements are true
New Section 1 Page 26
• and---Returns True if both statements are true
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.
Indentation
• Python relies on indentation (whitespace at the
beginning of a line) to define scope in the code
• Other programming languages often use curly
-brackets for this purpose.
of the block
If Statement
if x > 0 :
print('x is positive')
New Section 1 Page 28
print('x is positive')
Alternative execution
• A second form of the if statement is alternative
execution, in which there are two possibilities and the
condition determines which one gets executed.
• The elif keyword is python's way of saying "if the
previous conditions were not true, then try this
condition".
a = 33
b = 33
if b > a:
print("b is greater than a")
New Section 1 Page 30
print("b is greater than a")
elif a == b:
print("a and b are equal")
if x%2 == 0 :
print('x is even')
else :
print('x is odd')
python fahren.py
New Section 1 Page 34
python fahren.py
Enter Fahrenheit Temperature:72
22.22222222222222
python fahren.py
Enter Fahrenheit Temperature:fred
Traceback (most recent call last):
File "fahren.py", line 2, in <module>
fahr = float(inp)
ValueError: could not convert string to float: 'fred'
python fahren2.py
Enter Fahrenheit Temperature:72
22.22222222222222
python fahren2.py
Enter Fahrenheit Temperature:fred
Please enter a number
try:
print(x)
except:
print("An exception occurred")
New Section 1 Page 36
print("An exception occurred")
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except'is finished")
Functions
• A function is a block of code which only runs when it is
called. A function is a named sequence of statements
that performs a computation.
You can pass data, known as parameters or arguments,
New Section 1 Page 39
• You can pass data, known as parameters or arguments,
into a function. The argument is a value or variable that
we are passing into the function as input to the
function.
• By default, a function must be called with the correct
number of arguments. Meaning that if the function
expects 2 arguments, we have to call the function with
2 arguments, not more, and not less.
>>>
>>> len('Hello world')
11
>>>
Math functions
• Python has a math module that provides most of the
familiar mathematical functions and it has to be
imported before using.
>>> import math
• This statement creates a module object named math.
• The module object contains the functions and variables
defined in the module.
• Any function can be accessed by specifying the name of
the module and the name of the function, separated by
a dot (also known as a period). This format is called dot
New Section 1 Page 42
a dot (also known as a period). This format is called dot
notation.
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.7071067811865476
x = abs(-7.25)
print(x)
7.25
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
Random numbers
• The random module provides functions that generate
pseudorandom numbers
• The function random returns a random float between
0.0 and 1.0 (including 0.0 but not 1.0)
import random
for i in range(10):
x = random.random()
print(x)
0.11132867921152356
New Section 1 Page 44
0.11132867921152356
0.5950949227890241
0.04820265884996877
0.841003109276478
0.997914947094958
0.04842330803368111
0.7416295948208405
0.510535245390327
0.27447040171978143
0.028511805472785867
def print_twice(abc):
print(abc)
print(abc)
>>> print_twice('Sachin'*4)
New Section 1 Page 48
>>> print_twice('Sachin'*4)
Sachin Sachin Sachin Sachin
Sachin Sachin Sachin Sachin
>>> print_twice(math.cos(math.pi))
-1.0
-1.0
Lambda
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but
can only have one expression.
def myfunc(n):
return lambda a : a * n
doubler = myfunc(2)
print(doubler(11))
22
Why functions?
• Creating a new function gives us an opportunity to name a
group of statements, which makes our program easier to
read, understand, and debug.
• Functions can make a program smaller by eliminating
repetitive code. Later, if we make a change, we only have
to make it in one place.
• Dividing a long program into functions allows us to debug
the parts one at a time and then assemble them into a
working whole.
• Well-designed functions are often useful for many
programs. Once we write and debug one, we can reuse it.
Summary of Module 1
•Significance of Programming
•Vocabulary and grammar of Python
•Conversing with Python and terminologies
□ Interactive mode
□ Scripting mode
IDEs available---IDLE, Spyder,PyCharm
New Section 1 Page 52
□ IDEs available---IDLE, Spyder,PyCharm
Thonny, Atom, Jupyter Notebook, Vim
• Building blocks of the program--input
output
sequential execution
Conditional execution
Repeated execution
Reuse
• Common errors---Syntax
Logical
Semantic