Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Python Module 1 PN

The document provides an overview of why learning to write computer programs is useful. It discusses how computers can assist with tasks but require being instructed through programming. The document then covers various aspects of programming including computer components, programming languages, writing and running programs, variables, data types, errors, and statements. It aims to introduce basic concepts around programming to explain the value of learning this skill.

Uploaded by

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

Python Module 1 PN

The document provides an overview of why learning to write computer programs is useful. It discusses how computers can assist with tasks but require being instructed through programming. The document then covers various aspects of programming including computer components, programming languages, writing and running programs, variables, data types, errors, and statements. It aims to introduce basic concepts around programming to explain the value of learning this skill.

Uploaded by

neelambika ns
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Saturday, May 8, 2021

8:56 PM

Why should you learn to write programs


• In our daily lives we are surrounded with computers ranging
from laptops to cell phones.
• Computers can be treated as our personal assistants
Who can take care of many things on our behalf, ie.,
they are built for one purpose - to do things for us
• But we need to speak their language to describe what we
want to be done by them, which can be accomplished with the
help of program
• The kind of things computers can do best are often the kind of
things we human find boring, tedious
and repetitive
• Programs can be written for many reasons, ranging from
making your living to solving a difficult data analysis problem
to having fun to helping someone else solve a problem.

New Section 1 Page 1


• Central Processing Unit: Runs the Program - The CPU is
always wondering “what to do next”. Not the brains
exactly - very dumb but very very fast
• Main Memory: Used to store information. Fast and small
temporary storage - lost on reboot
• Secondary Memory: Used to store information. Slower large
permanent storage - lasts until deleted - disk drive / memory
stick
• Input Devices: Through these we interact with computer.
Ex:Keyboard, Mouse, Touch Screen, microphone, etc
• Output Devices: Screen, Speakers, Printer, DVD Burner

• Programmers learn the computer “ways” and the computer


language.

• A programmer will mostly be “talking” to the CPU and telling


it what to do next. A programmer, uses and orchestrate each
of these resources to solve the problem that needs to be
solved and analyzes the data got from the solution.
New Section 1 Page 2
solved and analyzes the data got from the solution.

• Programmer is the person who answers the CPU’s “What


next?” question.

Task of Programming--Learning a language

Skills required are:

• First, need to know the programming language (Python) -


need to know the vocabulary and the grammar. Programmer
need to be able to spell the words in this new language
properly and know how
to construct well-formed “sentences” in this new language.
• Second, need to “tell a story”. In writing a story,
programmer combine words and sentences to convey an idea
to the reader. In programming, program is the “story” and the
problem we are trying to solve is the “idea”.

New Section 1 Page 3


Words and sentences
The "vocabulary” of Python is referred as the “reserved
words”. These are words that have very special meaning to
Python. They have one and only meaning.
The words which are defined by the programmer in a program
are referred as variables.
Python has following reserved words
and del global not with
as elif if or yield
assert else import pass False
break except in raise True
class finally is return None
continue for lambda try
def from nonlocal while

Conversing with Python


1.Using Command Prompt

New Section 1 Page 4


>>> print 'JSSATEB'
JSSATEB
2.Using Python Terminal

3. Using Integrated Development Environment--


IDLE

New Section 1 Page 5


• Interactive Python is good for experiments and programs of
3-4 lines long. We type directly to Python one line at a time
and it responds
• Most programs are much longer, so we type them into a file
and tell Python to run the commands in the file.
• In a sense, we are “giving Python a script”.
• As a convention, we add “.py” as the suffix on the end of these
files to indicate they contain Python.

Interpreter and Compiler


• Python is a high-level language intended to be relatively
straightforward for humans to read and write and for
computers to read and process.
• The CPU understands a language we call machine language.
Machine language is very simple and frankly very tiresome to
write because it is represented all in zeros and ones

• An interpreter reads the source code of the program as


written by the programmer, parses the source code, and
New Section 1 Page 6
written by the programmer, parses the source code, and
interprets the instructions on the fly. Python is an interpreter
and when we are running Python interactively, we can type a
line of Python (a sentence) and Python processes it
immediately and is ready for us to type another line of Python.

• A compiler needs to be handed the entire program in a file,


and then it runs a process to translate the high-level source
code into machine language and then the compiler puts the
resulting machine language into a file for later execution.

The building blocks of programs


input
Get data from the “outside world”. This might be reading data
from a file, or even some kind of sensor like a microphone or
GPS. In our
initial programs, our input will come from the user typing data
on the keyboard.
output
Display the results of the program on a screen or store them
in a file
or perhaps write them to a device like a speaker to play music
or
speak text.
sequential execution
Perform statements one after another in the order they are
encountered in the script.
New Section 1 Page 7
encountered in the script.
conditional execution
Check for certain conditions and then execute or skip a
sequence of statements.
repeated execution
Perform some set of statements repeatedly, usually with some
variation.
reuse
Write a set of instructions once and give them a name and
then reuse those instructions as needed throughout your
program.

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.

Variables, Expressions, and


New Section 1 Page 8
Variables, Expressions, and
Statements
Values and types
• A value is one of the basic things a program works with,
like a letter or a number.
• Fixed values such as numbers, letters, and strings, are
called “constants” because their value does not change
• Ex: 1,2, “JSSATEB”
• Types of values-integer, float, string, etc.
• The print statement also works for integers. We use
the python command to start the interpreter.
• python
• >>> print(4)
• 4

• If we are not sure what type a value has, the interpreter


can tell us.
• >>> type('Hello, World!')
• <class 'str'>

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

• When we type a large integer, we might be tempted to use


commas between groups of three digits, as in 1,000,000. This
is not a legal integer in Python, but it is legal:
• >>> print(1,000,000)
• 100
• Well, that’s not what we expected at all! Python interprets
1,000,000 as a comma-separated sequence of integers, which
it prints with spaces between.
• Semantic Error

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

An assignment statement creates new variables and gives


them values
>>> pro_elective='Python Application Programming'
>>> n=40
>>> pi=3.1415926535897931

To display the variable value:


>>> print(n)
40
>>> print(pi)
3.1415926535897931

The type of a variable is the type of the value it refers to.


>>> type(pro_elective)
<class 'str'>
New Section 1 Page 11
<class 'str'>
>>> type(n)
<class 'int'>
>>> type(pi)
<class 'float'>

Some of the examples of illegal variable name:


>>> 6sem = 'pre final year'
SyntaxError: invalid syntax
>>> abc@ = 350
SyntaxError: invalid syntax
>>> class = 'Programming Applications'
SyntaxError: invalid syntax

• Python allows you to assign values to multiple variables in


one line:

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)
• We can assign the same value to multiple variables in
one line:
x = y = z = "Orange"
print(x)
print(y)
New Section 1 Page 12
print(y)
print(z)

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)

Produces the output


5
10

The assignment statement produces no output.


New Section 1 Page 13
The assignment statement produces no output.
Operators and operands
Operators are special symbols that represent
computations like addition and multiplication. The values
on which the operator is applied are called operands.

The operators +, -, *, /, and ** perform addition,


subtraction, multiplication, division, and exponentiation

20+32
hour-1
hour*60+minute
minute/60
5**2
(5+9)*(15-7)

There has been a change in the division operator


between Python 2.x and Python
3.x. The division operator in Python 2.0 would divide
two integers and truncate the
result to an integer. In Python 3.x, the result of the
division will be floating point

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

If we type an expression in interactive mode, the


interpreter evaluates it and displays the result. But in a
script, an expression all by itself doesn’t do anything
>>> 1 + 1
2
Numeric Expressions

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

 Exponentiation (raise to a power)

 Multiplication, Division, and Remainder

 Addition and Subtraction

 Left to right
>>> x =1+2**3/4*5
>>> print(x)
11

2 * (3-1)

New Section 1 Page 16


(1+1)**(5-2)

2**1+1 is 3 , not 4

3*1**3 is 3, not 27

Multiplication and Division have the same


precedence, which is higher than
Addition and Subtraction, which also have the same
precedence

So 2*3-1 is 5 , not 4

6+4/2 is 8, not 5

Operators with the same precedence are evaluated


from left to right. So the expression

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

• The * operator also works with strings by multiplying


the content of a string by an integer.
>>> first = 'Test '
>>> second = 3
>>> print(first * second)
New Section 1 Page 18
>>> print(first * second)
Test Test Test

Asking the user for input


• The built-in function called input gets input from the
user via 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()


JSSATEB
>>> print(inp)
JSSATEB

• User can be given an idea what to type by using a


Print before pausing for input.

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


What is your college name?
JSSATEB
>>> print(name)
JSSATEB

New Section 1 Page 19


• If an integer is expected from the user, then return
value can be to converted to integer using the int()
function:
>>> internalmarks='What is the average of test marks
\n'
>>> final_ia = input(internalmarks)
'What is the average of test marks'
22
>>> int(final_ia)
22
>>> int(final_ia) + 5
27

• But if the user types something other than a string of


digits, we get an error:

>>> internalmarks='What is the average of test marks


\n'
>>> final_ia = input(internalmarks)
'What is the average of test marks'
abc
>>> int(final_ia)
ValueError: invalid literal for int() with base 10

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.

# compute the internal assessment marks


final_ia = (ia1+ia2a+ia3) / 3

• Comments can also be at the end of a line:


final_ia = (ia1+ia2a+ia3) / 3 # compute the internal
assessment marks

• Everything from the # to the end of the line is ignored


and has no effect on the program.
• Comments are most useful when they explain
non-obvious features of the code.
• With the help of comments, the reader can figure out
what the code does
• It is much more useful to explain why.
• Good variable names can reduce the need for
comments
• To add a multiline comment you could insert a # for
each line:
Choosing mnemonic variable names
New Section 1 Page 21
Choosing mnemonic variable names

• Since we programmers are given a choice in how we


choose our variable names, We name variables to
help us remember what we intend to store in them
(“mnemonic” = “memory aid”)
• For example, the following three programs are
identical in terms of what they accomplish, but very
different when you read them and try to understand
them.

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)

• The Python interpreter sees all three of these


programs as exactly the same but humans see and
understand these programs quite differently.
• Python reserved words can't be used as variables.
• Many editors show the keywords in bold or color

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:

>>> sem sec = 5


SyntaxError: invalid syntax

>>> month = 09
File "<stdin>", line 1
month = 09
^
SyntaxError: invalid token

Another run time error “use before def;”


New Section 1 Page 23
Another run time error “use before def;”
>>> principal = 327.68
>>> interest = principle * rate
NameError: name 'principle' is not defined

• Variables names are case sensitive, so LaTeX is not


the same as latex.

Conditional execution
Boolean expressions
• Booleans represent one of two values:
True or False.

• A boolean expression is an expression which ask a


question and produce Yes(True) or No(False) result
which we use to control program flow.
• We can evaluate any expression in Python,
and get one of two answers, True or False.
• When you compare two values, the expression
is evaluated and Python returns the Boolean
answer:

• The following examples use the operator ==, which


compares two operands and produces True if
they are equal and False otherwise:
>>> 5 == 5
True
New Section 1 Page 24
True
>>> 5 == 6
False
>>>print(10 > 9)
True
>>>print(10 == 9)
False
>>>print(10 < 9)
False

• True and False are special values that belong to the


class bool; they are not strings:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
• Comparison operators are used to compare two
values:

• Comparison operators look at variables but do not


change the variables

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)

Returns True because z is the same object as x

print(x is y)

Returns False because x is not the same object as


y, even if they have the same content

print(x == y)

To demonstrate the difference betweeen "is" and


"==": this comparison returns True because x is
equal to y

Logical operators
and---Returns True if both statements are true
New Section 1 Page 26
• and---Returns True if both statements are true

x > 5 and x < 10

Is true only if x is greater than 5 and less than 10.

• or--Returns True if one of the statements is 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.

• not--Reverse the result, returns False if the result is


true
X=5
print(not(x > 3 and x < 10))
False
Any nonzero number is interpreted as “true.”

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.

• Increase indent Indent after an if statement or for


statement (after : )
New Section 1 Page 27
• Maintain indent to indicate the scope of the block

(which lines are affected by the if/for)

• Reduce indent back to the level of the if

statement or for statement to indicate the end

of the block

We can change the behavior of the program by

using conditional statements


if x > 0 :
print('x is positive')

If Statement

if x > 0 :
print('x is positive')
New Section 1 Page 28
print('x is positive')

• If the logical condition is true, then the indented


statement gets executed. If the logical condition is false,
the indented statement is skipped.

• The statement consists of a header line that ends with


the colon character (:) followed by an indented block.
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get
an error
• Statements like this are called 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.
• If we enter an if statement in the Python interpreter,
the prompt will change from >>> to three dots to
New Section 1 Page 29
the prompt will change from >>> to three dots to
indicate we are in the middle of a block of statements,
>>> x = 3
>>> if x < 10:
... print('Small')
...
Small
>>>
• When using the Python interpreter, we must leave a
blank line at the end of a block, otherwise Python will
return an error:

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

• Since the condition must either be true or false, exactly


one of the alternatives will be executed. The
alternatives are called branches, because they are
branches in the flow of execution.
Chained conditionals
• If there are more than two possibilities, then there will
be more than two branches. This is called chained
conditional:
x = 200
y = 33
New Section 1 Page 31
y = 33
if x < y:
print("x is lesser than y")
elif x> y:
print("x is greater than y")
else:
print("x and y are equal")

• There is no limit on the number of elif statements. If


there is an else clause, it has to be at the end, but there
doesn’t have to be one.
if choice == 'a':
print('Bad guess')
elif choice == 'b':
print('Good guess')
elif choice == 'c':
print('Close, but not correct')
New Section 1 Page 32
Short Hand If
• If we have only one statement to execute, we can put it
on the same line as the if statement.

if a > b: print("a is greater than b")

Short Hand If ... Else


• If we have only one statement to execute, one for if,
and one for else, we can put it all on the same line:
a=2
b = 330
print("A") if a > b else print("B")
Nested conditionals
• One conditional can also be nested within another.
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')

New Section 1 Page 33


• Although the indentation of the statements makes the
structure apparent, nested conditionals become
difficult to read very quickly.
• Logical operators often provide a way to simplify nested
conditional statements.
if 0 < x:
if x < 10:
print('x is a positive single-digit number.')

if 0 < x and x < 10:


print('x is a positive single-digit number.')

Catching exceptions using try and except


inp = input('Enter Fahrenheit Temperature: ')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)

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'

• When an error or exception occurs, Python will


normally stop and generate an error message.
• These exceptions can be handled using
the try statement
• The try block let us to test a block of code for errors.
• The except block lets us to handle the error.
• The finally block lets you execute code, regardless of
the result of the try- and except blocks.
• The idea of try and except is that if we know that some
sequence of instruction(s) may have a problem and we
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.
If there is an error python executes the statements
New Section 1 Page 35
• If there is an error python executes the statements
inside the except block

inp = input('Enter Fahrenheit Temperature:')


try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
except:
print('Please enter a number')

python fahren2.py
Enter Fahrenheit Temperature:72
22.22222222222222

python fahren2.py
Enter Fahrenheit Temperature:fred
Please enter a number

• Handling an exception with a try statement is called


catching an exception

try:
print(x)
except:
print("An exception occurred")
New Section 1 Page 36
print("An exception occurred")

• You can define as many exception blocks as you want,


e.g. if you want to execute a special block of code for a
special kind of error:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

• The finally block, if specified, will be executed


regardless if the try block raises an error or not.
• This can be useful to close objects and clean up
resources:

try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except'is finished")

Short-circuit evaluation of logical expressions+


New Section 1 Page 37
Short-circuit evaluation of logical expressions+
• If the evaluation of a logical expression stops because
the overall value is already known, it is called short-
circuiting the evaluation.
• The short-circuit behavior leads to a clever technique
called the guardian pattern.
• When 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.
>>> x = 6
>>> y = 2
>>> x >= 2 and (x/y) > 2
True
>>> x = 1
>>> y = 0
>>> x >= 2 and (x/y) > 2
False
>>> 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
>>>
New Section 1 Page 38
• We can construct the logical expression to strategically
place a guard evaluation just before the evaluation that
might cause an error as follows
>>> x = 1
>>> y = 0
>>> x >= 2 and y != 0 and (x/y) > 2
False
>>> x = 6
>>> y = 0
>>> x >= 2 and y != 0 and (x/y) > 2
False
>>> x >= 2 and (x/y) > 2 and y != 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>

• In the second expression, y != 0 acts as a guard to insure


that we only execute (x/y) if y is non-zero.

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.

• If we do not know how many arguments that will be


passed into your function, add a * before the parameter
name in the function definition.
• A function can return data as a result.
• Types of functions---Built in functions
User defined functions
Built-in functions
• Built-in functions can be used without the function
definition which are used to solve common problems
and included them in Python for us to use.
• Examples--
• The max function returns largest value in a list
>>> max('Hello world')
'w'

The min function returns smallest value in a list


New Section 1 Page 40
• The min function returns smallest value in a list
>>> min('Hello world')
''
• The len function tells us how many items are in its
argument.

>>>
>>> len('Hello world')
11
>>>

Type conversion functions


• The int function takes any value and converts it to an
integer
>>> int('32')
32
>>> int('Hello')
ValueError: invalid literal for int() with base 10: 'Hello'

• int converts floating-point values to integers by


chopping of the fraction part
>>> int(3.99999)
3
>>> int(-2.3)
-2
New Section 1 Page 41
-2

• float converts integers and strings to floating-point


numbers
>>> float(32)
32.0
>>> float('3.14159')
3.14159

• str converts its argument to a string:


>>> str(32)
'32'
>>> str(3.14159)
'3.14159'

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.

>>> ratio = signal_power / noise_power


>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = math.sin(radians)

• The function log computes logarithms base e.

>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.7071067811865476

• The abs() function returns the absolute (positive)


value of the specified number:

x = abs(-7.25)
print(x)
7.25

• The pow(x, y) function returns the value of x to the


power of y
x = pow(4, 3)
print(x)
New Section 1 Page 43
print(x)

• The math.ceil() method rounds a number upwards


to its nearest integer,
• and the math.floor() method rounds a number
downwards to its nearest integer, and returns the
result:

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

• The function randint takes the parameters low and


high, and returns an integer between low and high
(including both)

>>> random.randint(5, 10)


5
>>> random.randint(5, 10)
9

• To choose an element from a sequence at random, we


can use choice:
>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
New Section 1 Page 45
>>> random.choice(t)
3

Adding new functions (User defined functions)


• A function definition specifies the name of a new
function and the sequence of statements that execute
when the function is called.
• In Python a function is defined using the def keyword
• The first line in the function definition---header--:
• The rest is ---body of the function
• To call a function, use the function name followed by
parenthesis
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside
the parentheses.
• We can add as many arguments as we want, just
separate them with a comma.
• Function definition creates the function but does not
execute the body of the function
• A parameter is a variable which we use in the function
definition. It is a “handle” that allows the code in the
function to access the arguments for a particular function
invocation.
• We indent the body of the function
• A parameter is the variable listed inside the parentheses
in the function definition.
New Section 1 Page 46
in the function definition.
• An argument is the value that is sent to the function when
it is called.
• Often a function will take its arguments, do some
computation, and return a value to be used as the value
of the function call in the calling expression. The return
keyword is used for this.

• The return statement ends the function execution and


“sends back” the result of the function

>>> def greet(lang):


... if lang == 'kan':
... return 'Namasthe'
... elif lang == 'tamil':
... return 'Vanakkum'
... elif lang == 'malayalam':
... return 'Namaskaram'
... else:
... return 'Hello'
>>> print(greet('kan'),'Ram')
Namasthe Ram
>>> print(greet('tamil'),'Ram')
Vanakkum Ram
>>> print(greet('malayalam'),'Ram')
Namaskaram Ram
New Section 1 Page 47
Namaskaram Ram
>>>print(greet('en'),'Ram')
Hello Ram

def print_twice(abc):
print(abc)
print(abc)

• This function assigns the argument to a parameter named


abc.
>>> print_twice('Sachin')
Sachin
Sachin
>>> print_twice(6)
6
6

• We can use any kind of expression as an argument. The


argument is evaluated before the function is called

>>> import math


>>> print_twice(math.pi)
3.141592653589793
3.141592653589793

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

• We can also use a variable as an argument:


>>> game = 'sachin, the god of cricket.'
>>> print_twice(game)
sachin, the god of cricket.
sachin, the god of cricket.

Lambda
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but
can only have one expression.

lambda arguments : expression

• The expression is executed and the result is returned:

• Add 10 to argument a, and return the result:


x = lambda a : a + 10
print(x(5))
15
New Section 1 Page 49
15

• Lambda functions can take any number of arguments:

• Multiply argument a with argument b and return the


result:
x = lambda a, b : a * b
print(x(5, 6))
30

• Summarize argument a, b, and c and return the result:


x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
13

• The power of lambda is better shown when we use them


as an anonymous function inside another function.

def myfunc(n):
return lambda a : a * n
doubler = myfunc(2)
print(doubler(11))
22

Fruitful functions and void functions


New Section 1 Page 50
Fruitful functions and void functions
• When a function does not return a value, we call it a
“void” function

• Functions that return values are “fruitful” functions

• Void functions are “not fruitful”


• When we call a fruitful function, we almost always want
to do something with the result;
x = math.cos(radians)
y = (math.sqrt(5) + 1) / 2

• When you call a function in interactive mode, Python


displays the result:
>>> math.sqrt(5)
2.23606797749979

• But in a script, if we call a fruitful function and do not


store the result of the function in a variable,
the return value vanishes
• To return a result from a function, we use the return
statement in our function.
def add2(a, b):
sum = a + b
return sum
x = add2(4, 7)
New Section 1 Page 51
x = add2(4, 7)
print(x)
• When this script executes, the print statement will print
out “11” because the Add2 function was called with 4 and
7 as arguments.

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

• Values, variables, expressions and statements


• Operators, operands and precedence
• Sequential execution---
• Conditional execution---if, chained if, nested if
• Repeated execution---For, while,…
• Reuse--Functions

New Section 1 Page 53

You might also like