KEMBAR78
IPP Module 1 | PDF | Python (Programming Language) | Variable (Computer Science)
0% found this document useful (0 votes)
34 views230 pages

IPP Module 1

The document provides an introduction to Python programming, covering basic concepts such as data types, flow control, and functions. It includes practical examples and instructions for using the Python interpreter and IDEs like IDLE. Additionally, it discusses variable assignment, string manipulation, and the structure of a simple Python program.

Uploaded by

GAJANAN M NAIK
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)
34 views230 pages

IPP Module 1

The document provides an introduction to Python programming, covering basic concepts such as data types, flow control, and functions. It includes practical examples and instructions for using the Python interpreter and IDEs like IDLE. Additionally, it discusses variable assignment, string manipulation, and the structure of a simple Python program.

Uploaded by

GAJANAN M NAIK
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/ 230

BPLCK105B/205B : Introduction to Python Programming

Module - 1
Python Basics: Entering Expressions into the Interactive Shell, The Integer, Floating-Point, and String Data Types, String Concatenation
and Replication, Storing Values in Variables, Your First Program, Dissecting Your Program, Flow control: Boolean Values, Comparison
Operators, Boolean Operators,Mixing Boolean and Comparison Operators, Elements of Flow Control, Program Execution, Flow Control
Statements, Importing Modules,Ending a Program Early with sys.exit(), Functions: def Statements with Parameters, Return Values and
return Statements,The None Value, Keyword Arguments and print(), Local and Global Scope, The global Statement, Exception
Handling, A Short Program: Guess the Number
Textbooks

• Al Sweigart,“Automate the Boring Stuff with


Python”,1st Edition, No Starch Press, 2015.

• Allen B. Downey, “Think Python: How to Think


Like a Computer Scientist”, 2nd Edition, Green
Tea Press, 2015.
Introduction to Python
Python is an object-oriented, interpreted, high-
level programming language.

It is general purpose, and we use it to develop


GUI and web applications.

Object Oriented: Way of structuring real


world application such that “real world
problems can be modelled”.
Introduction to Python

Compiler: Source code converted to


machine language

Interpreter: Each line executed


High level language, Memory
management
Introduction to Python
Introduction to Python
Ever wondered why the language is named
Python?
Why Python?
Where can we use Python?
Introduction to Python
Running
Python
The Python Interpreter

[finin@linux2 ~]$ python


Python 3.11.3 (#1April 5, 2023)
• Typical Python
[GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on
implementations
linux2
offer both an
Type "help", "copyright", "credits" or "license"
interpreter and
for more information.
compiler.
>>> def square(x): • Interactive interface
... return x * x to Python with a
... read-eval-print loop.
>>> map(square, [1, 2, 3, 4])
[1, 4, 9, 16]
>>>
Installation
• Python is pre-installed on most Unix systems, including
Linux and MAC OS X
• The pre-installed version may not be the most recent
one (2.6.2 and 3.1.1 as of Sept 09)
• Download from http://python.org/download/ (3.11.3)
• Python comes with a large library of standard modules
• There are several options for an IDE
• IDLE – works well with Windows
• Emacs with python-mode or your favorite text editor
• Eclipse with Pydev (http://pydev.sourceforge.net/)
Download Python

INSTALL, CLICK ON ALL USER, PATH, ----FINAL MESSAGE AFTER INSTALLATION CLOSE
Download Python
INSTALL
CLICK ON ALL USER, PATH
----INSTALLATION----------------
CLOSE

SCRIPT MODE / FILE


EDITOR

INTERACTIVE MODE
Python Basics
● Entering Expressions into the Interactive Shell

● The Integer
● Floating-Point
● String Data Types
● String Concatenation and Replication

● Storing Values in Variables

● Your First Program


● Dissecting Your Program
Interactive shell
● REPL
: Read-Evaluate-Print
Loop
Lets you run (or execute) Python
instructions one at a time and instantly
shows you the results.

Using the interactive shell is great for


learning what basic Python instructions
do.
How to run python code in Interactive
mode?
● In order to run our program in the
● interactive mode,
● we can use command prompt in
windows,

● terminal in Linux, and macOS.


IDLE Development Environment

• IDLE is an Integrated DeveLopment Environment for Python, typically used


on Windows.
• Multi-window text editor with syntax highlighting, auto-completion, smart
indent and other.
• Python shell with syntax highlighting.
• Integrated debugger with stepping, persistent breakpoints, and call stack
visibility.
IDLE-SCRIPT MODE (file editor)
IDLE-SCRIPT MODE
# Python program to add two numbers
a =2
b =3

# Adding a and b and storing result in c


c =a +b

# Printing value of c
print(c)
Interactive shell
IDLE-SCRIPT MODE/ file editor
EXPRESSIONS
● >>> 2 + 2
4
>>>
Python, 2 + 2 is called an expression, which is the most
basic kind of programming instruction in the language.

Expressions consist of values (such as 2)


and operators (such as +), and they can
always evaluate (that is, reduce) down to a
single value.
EXPRESSIONS

● >>> 2
2

A single value with no operators is


also considered an expression,
though it evaluates only to itself.
Math Operators
Operator Operation Example Evaluates to . . .

** Exponent 2 ** 3 8
% Modulus/remainder 22 % 8 6
// Integer 22 // 8 2
division/floored
quotient
/ Division 22 / 8 2.75
* Multiplication 3 * 5 15
- Subtraction 5 - 2 3
+ Addition 2 + 2 4
Math Operators from Highest to Lowest
Precedence
● The order of operations (also called precedence) of Python
math operators is similar to that of mathematics.
• The ** operator is evaluated first.
• The *, /, //, and % operators are evaluated next,
from left to right
• The + and - operators are evaluated last (also
from left to right)
● You can use parentheses to override the usual
precedence if you need to. Whitespace in between the
operators and values doesn’t matter for expressions in
Python. (except for the indentation at the beginning of
the line)
Math Operators
● >>> 2 + 3 * 6
● 20
● >>> (2 + 3) * 6
● 30
● >>> 48565878 * 578453
● 28093077826734
● >>> 2 ** 8
● 256
>>> 23 / 7
3.2857142857142856
>>> 23 // 7
3
>>> 23 % 7
2
>>> 2 + 2
4
Math Operators
● >>> (5 - 1) * ((7 + 1) / (3 - 1))

16
Math Operators
This is a grammatically correct English sentence.
This grammatically is sentence not English
correct a.
>>> 5 +
File "<stdin>", line 1
5 +
^
SyntaxError: invalid syntax
>>> 42 + 5 + * 2
File "<stdin>", line 1
42 + 5 + * 2
^
SyntaxError: invalid syntax
Basic Data types
● Expressions are just values combined with operators

● A data type is a category for values, and every value


belongs to exactly one data type

Common Data Types


Data type Examples
Integers -2, -1, 0, 1, 2, 3, 4, 5
Floating-point -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25
numbers
Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'
Basic Datatypes
• Integers (default for numbers): (int), whole
numbers
z = 5 / 2 #Answer 2, integer division
• Floats : Numbers with a decimal: (float)
x = 3.456
Note that even though the value 42 is an integer, the
value 42.0 would be a floating-point number
• Strings : (str)
• Can use “” or ‘’ to specify with “abc” == ‘abc’
• Unmatched can occur within the string: “matt’s”
• Use triple double-quotes for multi-line strings or strings that contain
both ‘ and “ inside of them: “““a‘b“c”””
Basic Datatypes

● >>> 'Hello, world!


SyntaxError: EOL while
scanning string literal

● '', called a blank string or an empty


string
STRING
CONCATENATION
● The meaning of an operator may change based on the
data types of the values next to it.

● For example, + is the addition operator when it


operates on two integers or floating-point values.

● However, when + is used on two string


values, it joins the strings as the string
concatenation operator.
STRING CONCATENATION AND
REPLICATION

● >>> 'Alice' + 'Bob'

>>> 'AliceBob'
STRING CONCATENATION AND
REPLICATION

● >>> 'Alice' + 42
Traceback (most recent call last):
File "<pyshell#0>", line 1, in
<module>
'Alice' + 42
TypeError: can only concatenate
str (not "int") to str
STRING REPLICATION
● The * operator multiplies two integer or floating-point
values.
● But when the * operator is used on one string value
and one integer value, it becomes the string
replication operator.
● Enter a string multiplied by a number into the
interactive shell to see this in action.

>>> 'Alice' * 5

'AliceAliceAliceAliceAlice'
STRING REPLICATION
• The * operator can be used with only two numeric values
(for multiplication)

• Or one string value and one integer value (for string


replication).

• Otherwise, Python will just display an error message


STRING REPLICATION
● >>> 'Alice' * 'Bob'
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
'Alice' * 'Bob'
TypeError: can't multiply sequence by non-int
of type 'str'

>>> 'Alice' * 5.0


Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
'Alice' * 5.0
TypeError: can't multiply sequence by non-int
of type 'float'
Storing Values in Variables
• A variable is like a box in the computer’s
memory where you can store a single value.

• If you want to use the result of an evaluated


expression later in your program, you can
save it inside a variable.

spam = 42
is like telling the program,
“The variable spam now has the
integer value 42 in it.”
Assignment Statements
● You’ll store values in variables with
an assignment statement.
● An assignment statement consists of a
variable name, an equal sign (called
the assignment operator), and the value to be
stored.

● If you enter the assignment statement


● spam = 42,
● then a variable named spam will have the
integer value 42 stored in it.
Assignment Statements
● ➊ >>> spam = 40
>>> spam
40
>>> eggs = 2

➋ >>> spam + eggs


42
>>> spam + eggs + spam
82

➌ >>> spam = spam + 2


>>> spam
42
Assignment Statements
● A variable is initialized (or created) the first
time a value is stored in it ➊.
● After that, you can use it in expressions
with other variables and values ➋.
● When a variable is assigned a new
value ➌, the old value is forgotten, which is
why spam evaluated to 42 instead of 40 at
the end of the example. This is
called overwriting the variable.
Assignment Statements
● >>> spam = 'Hello'
>>> spam

'Hello'
>>> spam = 'Goodbye'

>>> spam
'Goodbye' When a new value is assigned to a
overwritin variable, the old one is forgotten
Variable Names
● Though you can name your variables
almost anything, Python does have some
naming restrictions.

•It can be only one word with no


spaces.
•It can use only letters, numbers, and
the underscore (_) character.
•It can’t begin with a number.
Variable Names
Valid variable Invalid variable names
names
current_balanc current-balance
e (hyphens are not allowed)
currentBalance current balance
(spaces are not allowed)
account4 4account
(can’t begin with a number)
_42 42
(can’t begin with a number)
TOTAL_SUM TOTAL_$UM
(special characters like $ are not allowed)
hello 'hello’
(special characters like ' are not allowed)
Variable Names
● Variable names are case-sensitive,
meaning that spam, SPAM, Spam,
and sPaM are four different variables.

● Though Spam is a valid variable you can


use in a program, it is a Python convention
to start your variables with a lowercase
letter.
YOUR FIRST PROGRAM
● The file editor lets you type in many
instructions, save the file, and run the
program. Here’s how you can tell the
difference between the two:

● The interactive shell window will always be


the one with the >>> prompt.
● The file editor window will not have the >>>
prompt.
YOUR FIRST
● ➊ #
P ROGRAM
This program says hello and asks for my
name.

➋ print('Hello, world!')
print('What is your name?') # ask for their
name
➌ myName = input()
➍ print('It is good to meet you, ' + myName)
➎ print('The length of your name is:')
print(len(myName))
➏ print('What is your age?') # ask for their
age
myAge = input()
print('You will be ' + str(int(myAge) + 1) +
' in a year.')
YOUR F● IRST
OncePROGRAM
you’ve entered your source code,
save it so that you won’t have to retype
it each time
● Once you’ve saved, let’s run our
program. Press the F5 key. Your
program should run in the interactive
shell window. Remember, you have to
press F5 from the file editor window
PROGRAM’S OUTPUT
Type "copyright", "credits" or "license()"
for more information.
>>> ======== RESTART ================
>>>
Hello, world!
What is your name?
Al
It is good to meet you, Al
The length of your name is:
2
What is your age?
4
You will be 5 in a year.
>>>
Dissecting Your Program
Comments
#This program says hello and asks
for my name.
Python ignores comments, and you can use
them to write notes or remind yourself what
the code is trying to do.

Any text for the rest of the line following a


hash mark (#) is part of a comment.
Comments
• Sometimes, programmers will put a # in front of a line of
code to temporarily remove it while testing a program.

• This is called commenting out code, and it can be useful when


you’re trying to figure out why a program isn’t working.

• You can remove the # later when you are ready to put the line
back in.

• Python also ignores the blank line after the comment.

• You can add as many blank lines to your program as you


want. This can make your code easier to read, like
paragraphs in a book.
Comments
The print() Function
● The print() function displays the
string value inside its parentheses on
the screen.
● print('Hello, world!')
print('What is your name?') # ask
for their name
The print() Function
• The line print('Hello, world!') means “Print
out the text in the string 'Hello, world!’.”
• When Python executes this line, you say that Python
is calling the print() function and the string value is
being passed to the function.
• A value that is passed to a function call is
an argument.
• Quotes are not printed to the screen.
• They just mark where the string begins and ends;
they are not part of the string value.
The print() Function
● You can also use this function to put a blank
line on the screen; just call print() with
nothing in between the parentheses.

● When you write a function name, the opening


and closing parentheses at the end identify it
as the name of a function.

● This is why, you’ll see print() rather


than print.
The input() Function
• Python input() function is used to get input
from the user.
• It prompts for the user input and reads a line.
• After reading data, it converts it into a string
and returns that.
myName = input()
input() function call as an expression that
evaluates to whatever string the user typed in.

If the user entered 'Al', then the expression


would evaluate to myName = 'Al'.
input() Function
Signature
input ([prompt])
Parameters prompt
It is a string message which prompts for the user
input
Return
It returns user input after converting into a
string
Printing the User’s Name
● Following print() actually contains the expression 'It is
good to meet you, ' + myName between the
parentheses.

● ➍ print('It is good to meet you, ' + myName)


● Expressions can always evaluate to a single value.

● If 'Al' is the value stored in myName on line ➌,


● then this expression evaluates to 'It is good to meet
you, Al’.
● This single string value is then passed to print(), which
prints it on the screen.
The len() Function
● You can pass the len() function a string
value (or a variable containing a string), and
the function evaluates to the integer value of
the number of characters in that string.

● ➎ print('The length of your name


is:')
print(len(myName))
len(myName) evaluates to an
integer
The len() Function
● >>> len('hello')
5
>>> len('My very energetic
monster just scarfed
nachos.') 46

>>> len('') 0
TypeError
● >>> print('I am ' + 29 + ' years
old.')
Traceback (most recent call last):
File "<pyshell#6>", line 1, in
<module>
print('I am ' + 29 + ' years
old.')
TypeError: can only concatenate str
(not "int") to str
str(), int(), and float() Functions
● >>> print('I am ' + 29 + ' years
old.’)
● Error

● >>> str(29)
'29’

>>> print('I am ' + str(29)+'years
old.')
I am 29 years old.
str(), int(), and float() Functions
● The str(), int(), and float() functions will
evaluate to the string, integer, and floating-point
forms of the value you pass, respectively.
>>> str(0)
'0'
>>> str(-3.14)
'-3.14'

>>> int('42')
42
str(), int(), and float()
● >>> int('-99') -99

>>> int(1.25) 1

>>> int(1.99)
1

>>> float('3.14')
3.14
>>> float(10)
10.0
str(), int(), and float()
● The str() function is handy when you have an
integer or float that you want to concatenate to a
string.

● The int() function is also helpful if you have a
number as a string value that you want to use in
some mathematics.

● For example, the input() function always returns a


string, even if the user enters a number.

● Enter spam = input() into the interactive shell and


enter 101 when it waits for your text.
str(), int(), and float()
● >>> spam = input()
101
● >>> spam ALWAYS TAKES STRING

'101'
>>> spam = int(spam) TAKES INT

>>> spam
101
NOW, SPAM CAN BE
>>> spam * 10 / 5 USED IN MATHEMATICAL
202.0 OPERATION
str(), int(), and float()
● If you pass a value to int() that it cannot evaluate
as an integer, Python will display an error message
>>> int('99.99')
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
int('99.99')
ValueError: invalid literal for int() with
base 10: '99.99’

>>> int('twelve')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
int('twelve')
ValueError: invalid literal for int() with
base 10: 'twelve'
str(), int(), and float()

● The int() function is also useful if you need


to round a floating-point number down.
● >>> int(7.7)
7
>>> int(7.7) + 1
8
str(), int(), and float()

● You used the int() and str() functions


in the last three lines of your program to get
a value of the appropriate data type for the
code.
● ➏ print('What is your age?') # ask
for their age
myAge = input()
print('You will be ' +
str(int(myAge) + 1) + ' in a year.')
Python input() Function Example
1. # Python input() function example
2. # Calling function
3. val = input("Enter a value: ")
4. # Displaying result
5. print("You entered:",val)

Output:
Enter a value: 45
You entered: 45
Python1.Program-2
# Python program showing.
2. # a use of input()
3. name = input("Enter your name: ") # String
Input.
4. age = int(input("Enter your age: ")) # Integer
Input.
5. marks = float(input("Enter your marks: ")) #
Float Input.
6. print("The name is:", name)
7. print("The age is:", age)
8. print("The marks is:", marks)
BUILDING BLOCKS OF
PROGRAM

● Expressions: their component values,


● operators, variables, and function calls
Python Syntax
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability
only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.

Python will give you an error if you skip the indentation:


The number of spaces is up to you as a programmer, the most common use is
four, but it has to be at least one.

You have to use the same number of spaces in the same block of code, otherwise
Python will give you an error:
Python Variables
In Python, variables are created when you assign a value to it:

Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Variable Names

•A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:A variable name must start
with a letter or the underscore character
•A variable name cannot start with a number
•A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
•Variable names are case-sensitive (age, Age and AGE are three different variables)
•A variable name cannot be any of the Python keywords.
Multi Words Variable Names
Variable names with more than
one word can be difficult to
read.
There are several techniques
you can use to make them more
readable:
Python Variables - Assign Multiple Values

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:

One Value to Multiple Variables


And you can assign the same value to multiple variables in one line:
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to
extract the values into variables. This is called unpacking.
Python - Output Variables

Output Variables
The Python print() function is often used to output variables.

In the print() function, you output multiple variables, separated by a comma:


You can also use the + operator to output multiple variables:

For numbers, the + character works as a mathematical operator:


In the print() function, when you try to combine a string and a
number with the + operator, Python will give you an error:

The best way to output multiple variables in the print() function is to


separate them with commas, which even support different data types:
Global Variables
Variables that are created outside of a function (as in all of the examples
above) are known as global variables.
Global variables can be used by everyone, both inside of functions and
outside.
Casting
If you want to specify the data type of a variable, this can be done with casting.
Get the Type
You can get the data type of a variable with the type() function.

Single or Double Quotes?


String variables can be declared either by using single or double quotes:
Case-Sensitive
Variable names are case-sensitive.
Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:

• Comments can be used to explain Python code.


• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
Comments starts with a #, and Python
will ignore them:

Comments can be placed at the end of a


line, and Python will ignore the rest of
the line:

A comment does not have to be text that


explains the code, it can also be used to
prevent Python from executing code:
Multiline Comments

Python does not really have a syntax for multiline comments.


To add a multiline comment you could insert a # for each line:

Since Python will ignore string literals that are not assigned to a variable, you can add
a multiline string (triple quotes) in your code, and place your comment inside it:
Python Numbers
There are three numeric types in Python:
•int
•float
•complex
Variables of numeric types are created when you assign a
value to them:
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Random Number
Python does not have a random() function to make a random number, but Python has
a built-in module called random that can be used to make random numbers:
Strings
Strings in python are surrounded by either single quotation marks, or
double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal
sign and the string:
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.

However, Python does not have a character data type, a single character is simply a string
with a length of 1.

Square brackets can be used to access elements of the string.


String Length
To get the length of a string, use the len() function.
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.

Use it in an if statement:
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.

Use it in an if statement:
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return
a part of the string.

Get the characters from position 2 to position 5 (not included):

Note: The first character has index 0.

Slice From the Start


By leaving out the start index, the range will start at the first character:
Slice To the End
By leaving out the end index, the range will go to the end:

Negative Indexing
Use negative indexes to start the slice from the end of the string:

Negative Indexing
Use negative indexes to start the slice from the end of the string:
Modify Strings
Upper Case

Lower Case

Remove Whitespace

The strip() method removes any whitespace from the beginning or the end:
Replace String

The replace() method replaces a string with another string:

Split String

The split() method returns a list where the text between the specified separator becomes the list items.
String Format

As we learned in the Python Variables chapter, we cannot combine strings and


numbers like this:

But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them in
the string where the placeholders {} are:
Flow Control

Flow control statements can decide


which Python instructions to
execute under which conditions
Flowchart to tell you what to do if it is raining

Branching points with


diamonds

In a flowchart, there is usually more than


one way to go from the start to the end.
>>> spam = True
>>> spam
True
>>> true
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
true
NameError: name 'true' is not defined
>>> True = 2 + 2
SyntaxError: assignment to keyword
2 + 2 == 4 and not 2+2 == 5 and 2*2==2+2
Elements of Flow
Control
Conditions:same as expressions;
condition is just a more
specific name in the context of flow control
statements. Conditions always evaluate
down to a Boolean value, True or False.
Blocks of Code: Lines of Python code can be
grouped together in blocks. You can tell when a
block begins and ends from the indentation of
the lines of code.
Three rules for blocks
1. Blocks begin when the indentation
increases.
2. Blocks can contain other blocks.
3. Blocks end when the indentation
decreases to zero or to a containing block’s
if name == 'Mary’:
indentation.
print('Hello Mary')
if password == 'swordfish’:
print('Access granted.')
else:
print('Wrong password.')
Program Execution

• The program execution (or simply, execution)


is a term for the current instruction being
executed.
• Not all programs execute sequentially in
flow control.
• Some are executed sequentially and
some are executed based on the
condition.
• You’ll probably likely to skip entire
clauses.
Flow Control
Statements
if Statements

The most common type of flow control


statement is the if statement.
An if statement’s clause (that is, the block
following the if statement) will execute if the
statement’s condition is True.
The clause is skipped if the condition is False.

“If this condition is true, execute the


code in the clause.” or skip if False
if Statements
In Python, if statement consists of the
following:
• The if
keyword
• A condition (that is, an expression
that evaluates to True or False)
• A colon (:)
• An indented block of code (called the if
clause)
if name == 'Alice’: Statement
print('Hi, Alice.') Clause, indented

Clause, indented
if name == 'Alice’:
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal
vampire.')
elif age > 100:
print('You are not Alice, grannie.')
age variable contains the value 3000 before
this code is executed?.
if name == 'Alice’:
print('Hi, Alice.')
elif age < 12
print('You are not Alice, kiddo.')
elif age > 100:
print('You are not Alice, grannie.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal
vampire.')
age variable value is 3000 before this code is
executed?.
You might print the string 'Unlike you, Alice is not an
undead, immortal vampire.'

age > 100 condition


is True (after all, 3000 is greater than 100)
the string
'You are not Alice, grannie.' is printed,
and the rest of the elif statements are
automatically skipped.
age > 100 and age > 2000 are swapped

Only one of the clauses will be executed, and


for elif statements, the order matters

else statement after the last elif statement it is


guaranteed that at least one (and only one) of the
clauses will be executed.
First, there is always exactly one if statement.
Any elif statements you need should follow the if
statement.
Second, if you want to be sure that at least one clause
while Loop Statements

You can make a block of code execute over and over


again with a while statement.
The code in a while clause will be executed as long as
the while statement’s condition is True.
if and while

spam = 0
if spam < 5:
print('Hello, world.')
spam = spam + 1

spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
while loop
An Annoying while Loop

name = ‘ '
while name != 'your name’:
print('Please type your
name.’)
name = input()
print('Thank you!')
The first line creates an infinite loop; it is a
while loop whose condition is always True.
Continue Statement
Trapped in an Infinite
Loop?
while True:
print('Hello
world!')

If you ever run a program that has a bug


causing it to get stuck in an infinite loop, press
ctr -C.
l
The while Loop
With the while loop we can execute a set of statements as long as a condition
is true.

Ex: Print i as long as i is less than 6:


The break Statement
With the break statement we can stop the loop even if the while condition is
true:
The continue Statement
With the continue statement we can stop the current iteration, and continue
with the next:
The else Statement
With the else statement we can run a block of code once when the
condition no longer is true:
for Loops and the range()
Function
The while loop keeps looping while its condition
is True (which is the reason for its name),

But what if you want to execute a block of


code only a certain number of times?

You can do this with a for loop statement and


the range() function.
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:
The break Statement
With the break statement we can stop the loop before it has looped through all
the items:

Exit the loop when x is "banana", but this time the break comes before the
print:
The continue Statement
With the continue statement we can stop the current iteration of the loop, and
continue with the next:

Do not print banana:


The range() Function
To loop through a set of code a specified number of times, we can use
the range() function,
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.
The range() function defaults to 0 as a starting value, however it is possible to specify
the starting value by adding a parameter: range(2, 6), which means values from 2 to
6 (but not including 6):
The range() function defaults to increment the sequence by 1, however it is possible to
specify the increment value by adding a third parameter: range(2, 30, 3):
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when
the loop is finished:

Example
Print all numbers from 0 to 5, and print a message when the loop has ended:
Example
Break the loop when x is 3, and see what happens with
the else block:
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
(‘+ str(i) + '): This concatenates the string representation of
the variable i with the rest of the message. The str(i) converts
the value of i to a string before concatenation.
for Loops and the range()
Function
My name is
print('My name is') Jimmy Five Times
for i in range(5): (0)
print('Jimmy Five Times (' + str(i) + Jimmy Five Times
')') (1)
Jimmy Five Times
(2)
for statement increments i by one. Jimmy Five Times
range(5) results in (3)
five iterations through the clause, Jimmy Five Times
(4) then 4.
with i being set to 0, then 1, then 2, then 3, and
The variable i will go up to, but will not include, the
integer passed to range()
for Loops and the range()
Function
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) +
')')
An Equivalent while Loop

print('My name is')


i=0
while i < 5:
print('Jimmy Five Times (' + str(i) + ')')
i=i+1

while loop do the same thing as a for loop; for loops are just more
concise
for Loops and the range()
total Function
=0
for num in range(101):
total = total + num
print(total)

An Equivalent while Loop

print('My name is')


i=0
while i < 5:
print('Jimmy Five Times (' + str(i) + ')')
i=i+1
for Loops and the range()
Function
for i in range(12, for i in range(0, 10, 2):
16): print(i)
print(i)

0
12 2
13 4
14 6
15 8
range() Function
Some functions can be called with multiple
arguments separated by a comma, and
range() is one of them.

This lets you change the integer passed to


range() to follow any sequence of integers

Including starting at a number other than


zero.
range() Function

Use a negative number for the step argument to


make the for loop count down instead of up.

for i in range(5, -1, -1): 5


print(i) 4
3
2
1
0
What is the difference between
range(10), range(0, 10), and range(0, 10, 1)
in a for loop?

Write a short program that prints the numbers 1 to 10


using a for loop.
Then write an equivalent program that prints the numbers
1 to 10 using a while loop.
import math #You need to put this
command, `import` keyword along with the name
of the module you want to import.

Example
import math
import math num = 4
num = 4 sqrt_num= math.sqrt(num)
print(math.sqrt(num)) or print (sqrt_num)

#Use dot operator to access sqrt() inside module


"math"
import math
pie = math.pi
print("The value of pi is : ",pie)
from math import pi
print(pi)

In the above code module, math is not imported, rather


just pi has been imported as a variable.

# Note that in the import example, we used


math.pi
#In the from math import pi we have used pi
import math

print(math.sqrt(16)) # Output: 4.0

print(math.sin(math.pi/2)) # Output: 1.0

print(math.log10(100)) # Output: 2.0


from module_name import *

All the functions and constants can be imported


using *.

from math import *


print(pi) 3.14159265359
print(factorial(6)) 720
Python Operators
Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

•Arithmetic operators
•Assignment operators
•Comparison operators
•Logical operators
•Identity operators
•Membership operators
•Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
Python Assignment Operators
Assignment operators are used to assign values to variables:
Precedence of Bitwise Operators in Python
The precedence of Bitwise Operators in python is as follows:
1.Bitwise NOT
2.Bitwise Shift
3.Bitwise AND
4.Bitwise XOR
5.Bitwise OR

Python Operators – GeeksforGeeks


Python Comparison Operators
Comparison operators are used to compare two values:
Python Logical Operators
Logical operators are used to combine conditional statements:
Python Identity Operators
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:
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Functions

Write / DEFINE your own function, and use it in


another program.
Functions
def hello(): # Defines function named hello
print('Howdy!') #Body of the function
print('Howdy!!!') #Output
print('Hello there.') Howdy!
# Function Howdy!!!
hello() Hello
call
hello() there.
Howdy!
hello() Howdy!!!
Hello
there.
Howdy!
file editor and save it as helloFunc.py: Howdy!!!
This code is executed when the function is called, not when
Hello
the function is first defined. there.
Functions

def
add(x,y):
return
(x+y)

def
sub(x,y):
return (x-y)
Functions
Functions
def Statements with Parameters
PARAMETER IS A
VARIABLE THAT
def hello(name): AN ARGUMENT IS
STORED WHEN
print('Hello ' + name)
FUNCTION IS CALLED
Name is a parameter
hello('Alice')
hello('Bob')

print(name) One special thing to note about


parameters is that the value stored in a
parameter is forgotten when the
function returns.
NameError because there is no variable
named name
Return Values and return
Statements

len(“Hello”)
returns the value=5
The value that a function call evaluates to is
called return value of the function

When creating a by def statement, you can specify


what the return value should be with a return
statement.
A return statement consists of the following:
 return keyword
 Value or expression that the function should
import random
def
getAnswer(answerNumber):
if answerNumber == 1:
return 'It is certain'
elif answerNumber == 2:
return 'It is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Reply hazy try
again'
r = random.randint(1, 4)
fortune = getAnswer(r)
print(getAnswer(random.randint(1, 4)))
print(fortune)
import random

The statement "import random" in Python allows


you to import the "random" module,
which provides functions related to generating
random numbers and performing random
selections.
random(): This function returns a random
floating-point number between 0 and 1 (inclusive
of 0 but exclusive of 1).
import random

random_number = random.random()
print(random_number) # Output:
0.5360886324597905
import random

randint(a, b): This function returns a random


integer between the specified range [a, b]
(inclusive of both endpoints).
Example usage:

import random
random_integer = random.randint(1, 10)
print(random_integer) # Output: (random
integer between 1 and 10)
import random

shuffle(seq): This function shuffles the elements in a


sequence randomly, in-place.

import random

my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list) # Output: (shuffled list)
None values in python

In Python, the value "None" is a special built-in


constant that represents the absence of a value
or the lack of a specific object.

It is commonly used to indicate that a variable or


function does not have a meaningful value or
does not return anything.
None values in python

None Type: "None" is of the "NoneType" data


type, which is a distinct type in Python.
You can check if a value is None using the "is"
operator.
Example:
x = None
if x is None:
print("x is None")
None values in python

Return Value: Functions in Python can have a return


statement, which specifies the value that the function
should return.
If no return statement is provided or if the return
statement does not specify a value, the function implicitly
returns None.
def my_function():
# No return statement, so the function returns
None implicitly pass

result = my_function()
print(result) # Output: None
None values in python

Assigning None: You can assign None to


variables to indicate the absence of a
meaningful value.
Example:

x = None
y = None

if x is None and y is None:


print("Both x and y are None")
None values in python

Default Function Arguments: None is often used as a


default value for function arguments when you want to
allow the caller to omit that argument.
This is useful when you need to distinguish between a
value provided by the caller and the absence of a
value.
def greet(name=None):
if name is None:
print("Hello, guest!")

greet() # Output: Hello, guest!


Local and Global Scope
Parameters and variables that are assigned in a
called function are said to exist in that function’s
local scope.

Variables that are assigned outside all functions are


said to exist in the global scope.

A variable that exists in a local scope is called a


local variable
A variable that exists in the global scope is called a
global variable.
A variable must be one or the other; it cannot be
• Local Variables cannot be used in the Global Scope
• Local Scopes cannot use variables in other Local
Scopes
• Global variables can be read from a Local Scope
• Local and Global variables with the Same Name
2.Function to generate square and square root of a
number. Write suitable python script to make function
calls.

3. Function to simulate simple calculator for addition,


multiplication, division and subtraction.
Local and Global Variable
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as
global variables.

Global variables can be used by everyone, both inside of functions and outside.

Create a variable outside of a function, and use it inside the function


If you create a variable with the same name inside a function, this variable will be
local, and can only be used inside the function. The global variable with the same
name will remain as it was, global and with the original value.

Create a variable inside a function, with the same name as the global variable
Useful links
• https://nptel.ac.in/courses/106/106/106106212/
• https://www.tutorialspoint.com/python/python_usef
ul_resources.htm
• http://www.python.org/doc/
• http://diveintopython.org/

You might also like