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

Module-1 Advance Python

Uploaded by

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

Module-1 Advance Python

Uploaded by

shubhangc6
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 151

Course Details

Course Code : CSA 4004

Course Name: Advance Python

Credit Structure: 1-4-4

CONTACT HOURS: Week 5 Hours

1
Module-1
Data types
Operators and Expressions
Input and Output Statements
Control Structures
Selective and Repetitive structures
Introduction to Python
WHAT?
• Created by Guido van Rossum.
• First released in 1991.

Why is it called Python?

“Monty Python's Flying Circus”

3
Why Python?
• Works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc).
• Simple syntax similar to the English language.
• Less number of lines.
• Prototyping can be very quick.
• Python can be treated in a procedural way, an object-orientated way
or a functional way.
Python Features
Easy to Use:
Python is very easy to use and high level language. Thus it is programmer-friendly language.
Expressive Language:
Python language is more expressive. The sense of expressive is the code is easily understandable.
Interpreted Language:
Python is an interpreted language i.e. interpreter executes the code line by line at a time.
This makes debugging easy and thus suitable for beginners.
Cross-platform language:
Python can run equally on different platforms such as Windows, Linux, Unix , Macintosh etc. Thus, Python is a
portable language.
Free and Open Source:
Python language is freely available(www.python.org).The source-code is also available. Therefore it is open source.
Object-Oriented language:
Python supports object oriented language. Concept of classes and objects comes into existence.
Large Standard Library:
Python has a large and broad library.
GUI Programming:
Graphical user interfaces can be developed using Python.
Integrated:
It can be easily integrated with languages like C, C++, JAVA etc. 5
Limitations of Python
Difficulty in Using Other Languages
The Python lovers become so accustomed to its features and its extensive libraries,
so they face problem in learning or working on other programming languages.
Python experts may see the declaring of cast “values” or variable “types”, syntactic
requirements of adding curly braces or semi colons as an onerous task.

Weak in Mobile Computing


Python has made its presence on many desktop and server platforms, but it is seen
as a weak language for mobile computing. This is the reason very few mobile
applications are built in it like Carbonnelle

7
Limitations of Python
Gets Slow in Speed
Python executes with the help of an interpreter instead of the compiler, which causes it to
slow down because compilation and execution help it to work normally. On the other hand,
it can be seen that it is fast for many web applications too.
Run-time Errors
The Python language is dynamically typed so it has many design restrictions that are
reported by some Python developers. It is even seen that it requires more testing time, and
the errors show up when the applications are finally run.
Underdeveloped Database Access Layers
As compared to the popular technologies like JDBC and ODBC, the Python’s database
access layer is found to be bit underdeveloped and primitive. However, it cannot be
applied in the enterprises that need smooth interaction of complex legacy data.

8
Users of Python

Web Development Games Graphics


• Google • Battlefield 2 • Walt Disney
• Yahoo • Crystal Space • Industrial Light & Magic
• Linux News • Star Trek • RoboFog

Science
Software Development
• NASA
• Red Hat
• The National Research Council of Canada
• Nokia
• AlphaGene
• Object Domain
• Applied Maths

9
Release Versions
• Python 2.0.1 – 2001
• Python 2.7 – 2010(Last Stable Version of 2.x series)
• Python 3.0 – 2008(Not Backward compatible with all earlier versions)
• Python 3.7 – June 27, 2018
• Python 3.8.4 – June 30, 2020
• Python 3.9.7 - August 30, 2021
• Python 3.10.5 - June 6, 2022
• Python 3.11.1 - December 6, 2022 – Latest Release

10
Important differences between Python 2.x and Python 3.x

Basis of comparison Python 3 Python 2


Function print
print (“hello”) print "hello"

Whenever two integers are divided, you When two integers are divided, you
Division of Integers
get a float value always provide integer value.
Syntax The syntax is simpler and easily The syntax of Python 2 was
understandable. comparatively difficult to understand.

Iteration The new Range() function introduced to In Python 2, the xrange() is used for
perform iterations. iterations.

Not difficult to port python 2 to python 3 Python version 3 is not backwardly


Backward compatibility
but it is never reliable. compatible with Python 2.

Library Many recent developers are creating


Many older libraries created for Python 2
libraries which you can only use with
is not forward-compatible
Python 3.
Installation
• Can be downloaded using
• https://www.python.org/downloads/
• Package Managers
• Anaconda
• Enthought
• PIP
• Integrated Development Environments(IDE)
• Atom
• Eclipse
• NetBeans
• Spyder
• Jupyter Notebook
• Pyroid-3 (Mobile App for Android)
12
The Jupyter Notebook is an open-source web application that allows
you to create and share documents that contain live code, equations,
visualizations and narrative text.
Uses include: data cleaning and transformation, numerical simulation,
statistical modeling, data visualization, machine learning, and much
more.
• Install Anaconda in system. Then run python scripts in Jupyter or
Spyder. (Offline)
OR
• Run python scripts in Jupyter over web using cloud based platform-
Google Collaboratory (Google Colab) (Online)

• Pyroid App (Android)- Mobile users


Launch Jupyter (to run python scripts in offline mode)
Google Colab (Colaboratory)
What- Cloud based platform- pc/mobile- developed by Google
Why- No setup required
-can be shared and edited by group of team members
simultaneously.
-free access to RAM, GPU, TPU and memory (ROM)
How
Running Jupyter Notebook on Colab

Colaboratory (short for Colab), a tool for machine learning education and research,
created as a Google research project.
Creating and running Jupyter Notebook on Colab is super easy and it’s free.
You can save your notebook to Google Drive or GitHub and even train your deep
learning on GPU.
Getting Started with Google Colab
https://colab.research.google.com
Watch how it works
https://www.youtube.com/watch?v=i-HnvsehuSw

17
18
Rename your note book with .ipynb

19
Download
or Save
colab
note book

20
Make single note book for all programs in a module

3 programs
• Print Hello
• Add 2 numbers
• Find square root of a number

21
Sharing Your Notebook
• Google Colab also gives us an easy way of sharing our work with others.
This is one of the best things about Colab:

22
Next Time open same notebook and continue

23
Comments in Python
Single line comment:
print ("Hello, Python!”) #first comment

Multiple line comment:


Ctrl+/ “””______________”””

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

24
Representation of Data
• Literal
• Numeric Literal
• String Literals
• Control Characters
• String Formatting
• Variables
• Identifiers
• Operators
• Arithmetic operators
• Expressions and Data Types
• Operator Precedence and Associativity
• Data type
• Mixed Type expressions

25
Numeric Literal

• Has only digits 0 to 9, a sign character (+ or -) and a possible decimal


point
• Commas are not used
• A numeric literal with a decimal point is a float (ex: 10.4) otherwise it
is an integer value (ex: 10)
Types of Numeric Literals:
• Integer
• Floating point

26
Numeric Literal…..

Integer Values:
5 2500 + 2500 -2500

Floating Point Values:


5. 5.0 0.0005 5000.125

2500. 2500.0 2500.125 +2500.

+2500.0 -2500. -2500.0 -2500.125


27
Numeric Literal…..

5,000.125 2,500 2,500.125

+2,500 +2,500.125 -2,500

-2,500.125

28
Numeric Literal…..

Floating Point Values in Scientific Notation:


9.0045602e+5 4.239e-16

• Python uses IEEE754 double precision format


• Range is to
• 16 to 17 digits of precision

• >>1/3
• .3333333333333333
• The repeating digit ends after the 16th digit.
29
Built in format function

• Used to print a floating point value rounded to a specific number of


decimal places
Examples:
Observe the output in each case below:
>>12/5
???
>>print(format(1/3, ’.2f’))
?????

30
Representation of Data
• String Literals
• A sequence of characters within a pair of matching single or double quotes or triple
quotes
• Ex: ‘Hello’ ‘Smith, John’
“Baltimore, Maryland” ‘ ‘ ‘’
“Jennifer’s friend”
• Convention is use single quotes for delimiting strings
• Type the following in your Jupyter notebook:
• >>> print(‘Hello’) ????? >>> print(‘Let’s Go’) ????
• >>> print(“Hello’) ????? >>> print(“Let’s Go!’) ???
• >>> print(“Let’s Go!”) ????
31
Representation of Data…..
• Representation of Character Values
• Characters are represented using the encoding scheme UTF-8
• an 8 bit encoding scheme compatible with ASCII.
• For example’ is encoded as 01000001(65) and ‘B’ is encoded as
01000010(66) and‘A so on
• ord() function gives the UTF-8 encoding of a given character
• For ex, ord(‘A’) is 65
• The chr() function gives the character for a given encoding value.
• For ex, chr(65) is ‘A’.

32
• Observe the following from the command line
• >>>ord(‘1’) >>>chr(65) >>>chr(97) >>>ord(‘2’)
• ???????? ?????? ?????? ??????

33
Control Characters
• These are nonprinting characters used to control the display of output.
• an escape sequence is a string of two or more characters used to denote
control characters
• ‘\’ serves as the escape character in Python
• For ex, the escape sequence ‘\n’ represents the new line control
character, used to begin a new screen line.
• Ex:
• >>>print(‘Hello\nJenifer’)
Hello
Jenifer

34
Control Characters….
• Explore the results of the following :
• print(‘Hello World\n\n’) ???????
• print(1,’\n’,2,’\n’,3) ???????
• print(‘\nHello World’) ??????

35
Formatting Strings

• Strings are formatted using the built in format function


• format(value, format specifier)
• Ex: format(‘Hello’, ‘<20’)
• print the string ‘Hello’ left justified in a field width of 20 characters
• Output : ‘Hello ‘
• format(‘Hello’, ‘>10’)
• print the string ‘Hello’ right justified in a field width of 20 characters
• Output : ‘ Hello’

36
• To center a string use the ‘^’ character
• Default fill character is blank
• A specific fill character can also be specified.
• print(‘Hello World’, format(‘.’, ‘.<30’), ‘Have a Nice day’)
• Output :
• Hello World……………….Have a Nice day

37
An identifier (variable)

• An identifier is a sequence of one or more characters used to name a given


program element.
• may contain letters and digits, but cannot begin with a digit.
• The only special character allowed in an identifier is underscore.
• An identifier starts with a letter A to Z or a to z or an underscore (_) followed
by zero or more letters, underscores and digits (0 to 9).
• Does not allow punctuation characters such as @, $, and % within identifiers.
• Python is a case sensitive programming language.
• Ex: ‘Python_Language’ and ‘python_language’ are different identifiers.

38
Identifier names
Python has some rules that you must follow when forming an identifier:
• it may only contain letters (uppercase or lowercase), numbers or the underscore character (_) (no
spaces!).
• it may not start with a number.
• it may not be a keyword.
Syntax error Bad practice, may correct Good practice
Person Record PRcrd PersonRecord
DEFAULT-HEIGHT Default_Ht DEFAULT_HEIGHT
class Class AlgebraCourse
2totalweight num2 total_weight

Syntax error Reason


Person Record Identifier contains a space.
DEFAULT-HEIGHT Identifier contains a minus.
class Identifier is a keyword.
2totalweight Identifier starts with a number.
39
Keywords in Python
• A keyword is an identifier that has a predefined meaning in a programming
language
• cannot be used as a regular identifier.
• Table shows list of Keywords available in Python
True False None and as

asset def class continue break

else finally elif del except

global for if from import

raise try or return pass

nonlocal in not is lambda

40
#to get the list of keywords
import keyword
print(keyword.kwlist)

# to check a word is keyword or not


import keyword
keyword.iskeyword('int')
keyword.iskeyword('if') output: True
keyword.iskeyword('yield') output: True
keyword.iskeyword('exit') output: False //exit is not a keyword

41
Python Variables
• Variable is a name which is used to refer memory location. Variable also known as identifier and used to hold value.
• In Python, we don't need to specify the type of variable because Python is a type infer language and smart enough to get
variable type.

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:


• Variable names can be a group of both letters and digits, but they have to begin with a letter or an underscore.
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• A variable name cannot be any of the Python keywords.
Example: a=0
name=‘sona’
total_marks=190

• the same variable can be associated with values of different types during program execution
• var = 12 integer
• var = 12.45 float
• var = ‘Hello’ string
42
Variable names
Valid variable names
Invalid variable names Camel case:
myvar = "John"
2myvar = "John" myVariableName = "John“
my_var = "John"
my-var = "John"
_my_var = "John"
my var = "John" Snake case:
myVar = "John"
my_variable_name = "John"
MYVAR = "John"
myvar2 = "John"
Casting: If you want to specify the data type of a variable, this can be done with casting.
x = str(3)
y = int(3)
z = float(3)
print(x)
print(y)
print(z)

sides = 4
print( type(sides) )
print( id(sides) )
Output
<class 'int'>
10915392
Mutable and immutable types

Some values in python can be modified, and some cannot.


This does not ever mean that we can’t change the value of a variable – but if a
variable contains a value of an immutable type, we can only assign it a new value.
We cannot alter the existing value in any way.
Integers, floating-point numbers and strings are all immutable types – in all the
previous examples, when we changed the values of existing variables we used the
assignment operator to assign them new values.

44
Output variables
To combine both text and a variable, Python uses the + character:
x = "awesome"
print("Python is " + x)

You can also use the + character to add a variable to another variable:
x = "Python is "
y = "awesome"
z=x+y
print(z)

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


x=5
y = 10
print(x + y)

If you try to combine a string and a number, Python will give you an error:
x=5
y = "John"
print(x + y)
Changing an Integer
a=1 a 1

a
b=a 1
b new int object created
by add operator (1+1)

a 2
a = a+1 old reference deleted
by assignment (a=...)
b 1

46
Data types
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview

Getting the data type:


You can get the data type of any object by using the type() function:
x=5
print(type(x))
Setting a specific data type:

x = str(“23")

#display x:
print(x)

#display the data type of x:


print(type(x))
Multiple Assignment
Many Values to Multiple Variables: Python allows you to assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
a,b,c = 1,2,”john”
print(a,b,c)

One Value to Multiple Variables


And you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)

x1,y1 = 2,3 # point one


x2,y2 = 6,8 # point two
m,b = float(y1-y2)/(x1-x2), y1-float(y1-y2)/(x1-x2)*x1
print ("y=", m, "*x+“ ,b)
50
Indentation (space in the beginning of a line)

if 5 > 2:
print("Five is greater than two!")

if 5 > 2:
print("Five is greater than two!") --------- This will throw error

if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")------------ This will throw error
Input and Output statement
• Some of the functions like input() and print() are widely used for standard input and output operations respectively.
• Input function is used to read a line from the keyboard.
• The input() function allows user input.
• The input function returns all inputs as strings.
• For numeric inputs, the response of the input() must be converted to appropriate type.
Syntax:input(prompt)
Parameter Description
prompt A String, representing a default message before the input.

Variable_name=input(“String”)

Example: name=input(“Enter your name”)


print("Hello, " + name)
age=int(input(“enter your age”))
print(age)

Write a simple Python script to calculate age based on the user's input for their birth year.
birth_year=int(input("Enter birth year: " ))
age=2023-birth_year
print(age) 52
Operators in Python

1. An operator is a symbol that performs some


operation.
2. An operator acts on some variables called
operands.
3. An operator acts on single variable called
unary operators.
4. An operator acts on two variables called
binary operators.

53
Operators
Unary and binary arithmetic operators
Arithmetic Meaning Example Result
Operator
-x negation -10 -10
x+y addition 10 + 25 35
x–y subtraction 10 – 25 -15
x*y multiplication 10 * 5 50
x/y division 25/10 2.5
x // y truncating 25 // 10 25// 10.0 2 2.0
division
x%y modulus 25 % 10 5
x ** y exponentiation 10 ** 2 100

54
Expressions
• a combination of operands (or a single operand) with operators that
evaluates to a value.
• If it evaluates to a numeric value it is known as arithmetic expression

2+3 +4**2 +1**3 ???? 2 + (3 * 4) ?????

2 + ((3 *4) – 8) ??? 2 + 3 * (4 – 1) ???

55
Operator Precedence
Operator Operator Name
() Parenthesis
** Exponentiation
- Unary minus
*, /, //, % Multiply, Divide, Floor Division, Modulus
+, - Addition, Subtraction
>, >=, <=, <, ==, != Relational Operators
=, %=, /=, //=, -=, +=, *=, **= Assignment Operators
is, is not Identity Operators
not in, in Membership Operators
or Logical OR
and Logical AND
not Logical NOT

56
Operator Associativity
Operator Operator Name

** Right to Left

- Left to Right

*, /, //, % Left to Right

+, - Left to Right

>, >=, <=, <, ==, != Left to Right

=, %=, /=, //=, -=, +=, *=, **= Left to Right

or Left to Right

and Left to Right

not Left to Right

57
Operator Precedence and Associativity
• Try the following:
2 + 3 * 4 ????? 2 * 3//4 ???? 2 * 3 + 4 ?????

5 + 42 % 10 ??? 2 * 3 / 4 ??? 2 * 2 ** 3 ????

6–3+2 ???? 2 * 3 / 4 ??? (2 ** 2) ** 3 ????

(6 – 3) + 2 ??? 12 % (10/2) ??? 2 ** (2 ** 3) ????

58
Mixed Type Expressions, Coercion and Type
Conversion

• It is an expression with operands of different types


• In a mixed type expression either coercion(implicit) type
conversion or explicit conversion takes place.
• Ex : 2 + 4.5 is first implicitly converted (int converted to
float) 2.0 + 4.5 which gives 6.5
• Ex: float(2) + 4.5 is first explicitly converted 2.0 + 4.5 which
gives 6.5
• 2 + int(4.5) gives 2 + 4 which is 6
59
Types of Operators in Python

1. Arithmetic Operators
2. Assignment Operators
3. Unary Operators
4. Relational Operators
5. Logical Operators
6. Boolean Operators
7. Membership Operators
8. Identity Operators

60
1. Arithmetic Operators
Operator Meaning a = 13, b e Result

+ Addition Operator a+b 18

- Subtraction Operator a–b 8

* Multiplication Operator a*b 65

/ Division Operator a/b 2.6

% Modulus Operator a%b 3

** Exponential Operator a ** b 135 = 371293

// Floor Division a // b Floor(2.6) = 2

61
num1 = eval(input("Enter the first number: "))
Program 1:Write a program that prompts a user to enter two different numbers. Perform basic arithmetic operations based on the choices.

num2 = eval(input("Enter the second number: "))


print("1: Addition")
print("2: Subtraction")
print("3: Multiplication")
print("4: Integer Division")
print("5: Float Division")
choice = int(input("Please Enter the Choice: "))
if(choice == 1):
print("Addition of ", num1, "and ", num2, " is: ", num1 + num2)
elif(choice == 2):
print("Subtraction of ", num1, "and ", num2, " is: ", num1 - num2)
elif(choice == 3):
print("Multiplication of ", num1, "and ", num2, " is: ", num1 * num2)
elif(choice == 4):
print("Integer Division of ", num1, "and ", num2, " is: ", num1 // num2)
elif(choice == 5):
print("Float Division of ", num1, "and ", num2, " is: ", num1 / num2)
2. Assignment Operators: The assignment operator in Python is used to assign a value to a variable. The
assignment operator is represented by the equals sign (=).When an assignment operator is used, the value on
the right-hand side is assigned to the variable on the left-hand side. Example: a = 10
Operator Name Description Syntax

Operator Name Description Syntax


It assigns the right-hand side expression value to the operand present on
= Assignment Operator a=b+c
the left-hand side.
Addition This operator adds left and right operands, and after that, it assigns the
+= a+=b or a=a+b
Assignment Operator calculated value to the left-hand operand.
Subtraction This operator subtracts the right operand from the left operand and
-= a-=b or a=a-b
Assignment Operator assigns the result to the left operand.
Multiplication This operator will multiply the left-hand side operand by the right-hand
*= a*=b or a=a*b
Assignment Operator side operand and, after that, assign the result to the left-hand operand.
Division This operator will divide the left-hand side operand by the right-hand side
/= a/=b or a=a/b
Assignment Operator operand and, after that, assign the result to the left-hand operand.
Modulus This operator will divide the left-hand side operand by the right-hand side
%= a%=b or a=a%b
Assignment Operator operand and, after that, assign the reminder to the left-hand operand.
Exponentiation This operator raises the left-side operand to the power of the right-side
**= a**=b or a=a**b
Assignment Operator operand and assigns the result to the left-side value.
This operator will divide the left operand by the right operand and assign
Floor Division
//= the quotient value (which would be in the form of an integer) to the left a//=b or a=a//b
Assignment Operator
operand. • 63
2. Assignment Operators
Operator Meaning x = 20, y = 10, z = 5 Result
= z=x+y z = 20 + 10 30
+= z += x z = 5 + 20 25
=> z = z + x

-= z -= x z = 5 – 20 -15
=> z = z – x

*= z *= x z = 5 *20 100
=> z = z * x

/= z /= x z = 5 / 20 0.25
=> z = z / x

%= z %= x z = 5 % 20 5
=> z = z % x

**= z **= x z = 5 ** 20 520


=> z = z ** x

//= z //= x z = 5 // 20 0
=> z = z // x
64
Example: x=5
x=5 x /= 3
print(x) print(x)

x=5 x=5
x += 3 x%=3
print(x) print(x)

x=5 x=5
x -= 3 x//=3
print(x) print(x)

x=5 x=5
x *= 3 x **= 3
print(x) print(x)

65
3. Unary Minus Operators

This operator is used to change the sign of an


operand.

num = -10
num = -num
print(num) #10

66
4. Relational Operators
• Relational operators are used for comparing the values. The relational operators are also known as Comparison
Operators
• Relational Operators in python compare the operand values on either side.
• The relational operators in Python return a boolean value, i.e., either True or False based on the value of operands.
Operator Meaning a = 13, b = 2 Result

> Greater Than a>b True

>= Greater Than OR Equal To a >= b True

< Less Than a<b False

<= Less Than OR Equal To a <= b False

== Equal To a == b False

!= Not Equal To a != b True

67
5. Logical Operators
Logical operators are used to combine conditional statements:

Operator Meaning x = 100, y=20, z=0 Result


and x and y x > y and y < z False
or x or y x > y or y < z True
not not x not z True

Example:x = 5
print(x > 3 and x < 10)

x=5
print(x > 3 or x < 4)

x=5
print(not(x > 3 and x < 10))

68
6. Boolean Operators

Boolean Operator acts upon ‘bool’ type literals.

Operator Meaning x = True, y = False Result

and Boolean And Operator x and y False

or Boolean Or Operator x or y True

not Boolean Not Operator not y True

69
7. Membership Operators

Membership operators are useful to check for


membership in a sequence (strings, lists, tuples,
dictionaries)

1. ‘in’ Operator: This operator returns ‘True’ if


element found in the sequence.
2. ‘not in’ Operator: This operator returns
‘True’ if element not found in the sequence.

70
Examples:
a=10
l=[10,23,45]
a in l
Output: True fruit='pineapple‘
‘papp' not in fruit
fruit='pineapple‘ Output: True
'apple' in fruit
Output: True

fruit='pineapple‘
‘papp' in fruit

71
8. Identity Operators

These operators are used to compare the memory


locations of two objects. id() function is used to check
the memory location of an object.

1. ‘is’ Operator: This operator will compare the


identity of two variables and return ‘True’ if they
are same object.
2. ‘is not’ Operator: This operator also will compare
the identity of two variables and return ‘True’ if
they are not the same object.

72
Example:

a = 25 a = 25
b = 25 b=a
a is b a is b
Output: True Output: True

# check id
print(id(a))
print(id(b))

# try same examples with is not


Example:
a = 25
b = 25 a = 25
if a is b: b=a
print(“Have same ID”) if a is not b:
else: print(“Different ID”)
print(“Different ID”) else:
print(“Same ID”)
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using the
str.format() method. This method is visible to any string object.
The format() method formats the specified value(s) and insert them inside the string's placeholder.
The placeholder is defined using curly brackets: {}.
The format() method returns the formatted string.
Syntax: string.format(value1, value2...)
Example: x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))
#Parameter
Output: The value of x is 5 and y is 10
Description
value1, value2... Required. One or more values that should be formatted and inserted in the string.

The values are either a list of values separated by commas, a key=value list, or a combination of
both.

The values can be of any data type

75
The Placeholders:
The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even
empty
placeholders {}.
#named indexes:
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)
print(txt1)
print(txt2)
print(txt3)

76
PRACTICE
PROGRAMS
Program 2a: Write a program in Python to Read three
numbers and print their sum
num1 = int(input('Enter first number'))
num2 = int(input('Enter Second number'))
num3 = int(input('Enter Third Number'))
sum = num1 + num2 + num3
print('Sum=', sum)

Input: 23 34 45
Output: Sum=102

78
Program 2b: Write a program in Python to add two real numbers
and print their sum using format function

07/29/2024 79
num1 = float(input('enter first number'))
num2 = float(input('enter second number'))

sum = num1 + num2

print('The sum of {0} and {1} is {2}'.format(num1,num2,sum))


Pgm No.3
Program 3: Write a program in Python to swap two given
values
a = int(input('Enter a'))
b = int(input('Enter b'))

t=a
a=b
b=t

print('The value of a after swapping is {0}'.format(a))


print('The value of b after swapping is {0}'.format(b))
07/29/2024 81
Pgm No.4
Program 4: Write a program in Python to Find the area of a triangle from its sides

82
# area of a triangle from its sides

import math

a = int(input('Enter side 1'))


b = int(input('Enter side 2'))
c = int(input('Enter side 3'))

s = float(a+b+c)/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))

print('Area = ', area)


Pgm No.5
Program 5: Write a program in Python to Find x to
the power y for some x and y. x**y
base = int(input('enter the base'))
exp = int(input('enter the exponent'))
print(base ** exp)

84
Pgm No.6
Program 6: Write a program in Python to Roots
of a quadratic equation ax**2 + bx + c = 0 given
a,b and c

07/29/2024 85
import math
a = float(input('Enter a'))
b = float(input('Enter b'))
c = float(input('Enter c'))
dis = (b**2) - (4*a*c)
root1 = (-b+ math.sqrt(dis))/(2*a)
root2 = (-b-math.sqrt(dis))/(2*a)
print('Root 1 ', root1)
print('Root2 ', root2)
Pgm No.7
Program 7a: Write a program in Python to Generate a
random number between 0 and 9

import random
print(random.randint(0,9))

07/29/2024 87
Pgm No.7
Program 7b: Write a program in Python to convert a decimal
number to binary, octal and hexa

dec = int(input('Enter a decimal number'))


print('Binary equivalent is',bin(dec))
print('Octal quivalent is', oct(dec))
print('Hexa equivalent is', hex(dec))

07/29/2024 88
Pgm 8
Program 8a: Write a program in Python to Read the radius of a circle and
find its area

Program 8b: Write a program in Python to Read the radius of a circle and
find its circumference

07/29/2024 89
Pgm 9.
Program 9: Write a program in Python to An object’s momentum is a product
of its mass and velocity. Write a Python script to accept an object’s mass (in
kilograms) and velocity (in metres per second) as inputs and output its
momentum.
mass = float(input("Enter the mass of the object (in kilograms): "))
velocity = float(input("Enter the velocity of the object (in meters per second): "))
momentum = mass * velocity
print("The momentum of the object is: {} kg*m/s".format(momentum))

07/29/2024 90
Pgm No. 10
Program 10: Write a program in Python to Read a four
digit binary number one digit at a time starting from the
rightmost digit and print its decimal value

07/29/2024 91
ones = int(input('enter the ones digit'))
sum = int(ones * (2 ** 0))
tens = int(input('enter the tens digit'))
sum = int(sum + tens *(2**1))
hund = int(input('enter the hundreds digit'))
sum = int(sum + hund *(2**2))
th = int(input('enter the thousands digit'))
sum = int(sum + th*(2**3))
print('sum = ', sum)
Control Structures
1. Programming language provides 3 fundamental forms of control
structures:

A. Sequential: Instructions are executed in the form they are written. No


jump of control.
B. Selective: Control statement that selectively executes the instructions
and may have jump of control within program.
• If
• Nested if
• if – else
• if-elif-else

93
C. Iterative: Control statements that can execute a particular set of
statements in a loop and terminates based on the given conditions.
• while
• for
• else suite
• break
• continue
• pass
• assert
• return

94
Sequential Control Statements

a = 10
b=a
print(“ a = b ”)

Indentation in Python: Indentation refers to the space that are


used in the beginning of a statement.

Statements within the same indentation belongs to the same


group called suite.

Note: By default, Python uses 4 spaces for indentation.

95
Selective Control Statements
2. ‘if’ statement:
syntax:
if condition:
statements

Example:

num = 1
str = ‘Yes’
if num == 1: if str == ‘No’:
print(“one”) print(“No”)
print(“I’m in if block”)
print(“Demo Program”)

96
Selective Control Statements
Nested ‘if’ statement:

Example:
vehicle = 1
type = ‘car’
c = ‘BMW’
b = ‘Honda’

if vehicle:
if type == ‘car’:
if c == ‘BMW’:
print(“we have a vehicle and it’s a BMW car”)
if type == ‘bike’:
if b == ‘Honda’:
print(“we have a vehicle and it’s a Honda bike”)

97
Selective Control Statements
2. ‘if - else’ statement:
syntax:
if condition:
statements
else:
statements

Example:
vehicle = ‘car’

if vehicle == ‘bike’:
print(“Riding a bike”)
else
print(“Riding a car”)

98
Selective Control Statements
2. ‘if – elif - else’ statement:
syntax:
if condition:
statements
elif condition:
statements
else:
statements
Example: Assigning a letter grade based on a numerical score
G = int(input("Enter number: "))
if G >= 90 and G <= 100:
print("A")
elif G >= 80 and G < 90:
print("B")
elif G >= 70 and G < 80:
print("C")
elif G >= 60 and G < 70:
print("D")
elif G >= 0 and G < 60:
print("F")
else:
print("Please enter a valid grade between 0 and 100.") 99
Program - 11
Program 11a: Write a program in Python to Write a python program
to determine a number is even or odd.

100
Write a python program to determine a number is even or odd.

x = int(input(“Enter any number”))

if x%2 == 0:
print(“Even number”)
else:
print(“Odd number”)

101
Program -11
Program 11b: Write a python program to know whether a number is
positive or negative or zero.

102
Write a python program to know whether an input number is positive,
negative or zero.

x = int(input(“Enter any number”))

if x<0:
print(“Negative number”)
elif x>0:
print(“Positive number”)
else:
print(“Zero”)

103
Program - 12

Program 12a:Write a Program in Python to Read two


numbers num1 and num2 and find the largest of two and
find the largest of two and also check for equality.

104
Read two numbers num1 and num2 and find the largest of two.

num1 = int(input(“Enter num1”))


num2 = int(input(“Enter num2”))

if num1 > num2:


print(“num1 is greater than num2”)
elif num1 < num2:
print(“num2 is greater than num1”)
else:
print(“num1 and num2 are equal”)

105
Program 12b: Write a Program in Python to Read three
numbers and find the largest of three.
num1 = int(input(“Enter num1”))
num2 = int(input(“Enter num2”))
num3 = int(input(“Enter num3”))

If num1 > num2:


if num1 > num3:
print(“num1”,end = “ ”)
else:
print(“num3”,end = “ ”)
else:
if num2 > num3:
print(“num2”,end = “ ”)
else:
print(“num3”,end = “ ”)
print(“ is the largest value”)

106
Program - 13
Program 13a: Write a Python script that reads the numeric grade of a
student and print its equivalent letter grade as given below:

Letter Grade Range of Numeric Grades


A All grades above 90
B All grades above 80 and below 89
C All grades above 70 and below 79
D All grades above 60 and below 69
F All grades below 59

107
Example: Assigning a letter grade based on a numerical score
G = int(input("Enter number: "))
if G >= 90 and G <= 100:
print("A")
elif G >= 80 and G < 90:
print("B")
elif G >= 70 and G < 80:
print("C")
elif G >= 60 and G < 70:
print("D")
elif G >= 0 and G < 60:
print("F")
else:
print("Please enter a valid grade between 0 and 100.")

108
Program 13b
Read a character A or B or C.
If the character input is A, program should print ‘Apple’;
if character entered is B, program should print ‘Banana’
if character entered is C, program should print ‘Coconut’

ch = input(“Enter the option”)

If ch == ‘A’:
print(“Apple”)
elif ch == ‘B’:
print(“Banana”)
elif ch == ‘C’:
print(“Coconut”)
else:
print(“Invalid option”)

109
Program 14a: Write a Python script to read the length and breadth of a
rectangular garden in centimeters. The program should also find the cost of
fencing the garden, if the cost of fencing per cm Rs.168.
Program :
l = float(input("enter the length of the garden"))
b = float(input("enter the breadth of the garden"))
p = 2 * (l + b)
cost = p * 168
print('Perimeter of the garden is', p)
print('Cost of fencing the garden is', cost)

110
Program 14b: Write a Python script to read the name and age of
two persons x and y.
The program should also print the younger of the two.

Sample Input :
Name : David Age : 67
Name: Jennifer Age : 32
Output:
Jennifer is the youngest

111
Program:
name1 = input("Enter the name of first person")
age1 = int(input("Enter the age of first person"))
name2 = input("Enter the name of second person")
age2 = int(input("Enter the age of second person"))
if age1<age2:
print(name1, "is the youngest")
else:
print(name2, "is the youngest")
Program 15a: Write a Program to read the three sides of a triangle
and check whether it is Equilateral, Isosceles or Scalene Triangle

113
Program:
a = int(input("ENter the first side"))
b = int(input("ENter the second side"))
c = int(input("ENter the third side"))

if ((a == b) and (a == c)):


print("Equilateral")
elif ((a == b) or (b == c) or (c == a)):
print("Isosceles Triangle")
else:
print("Scalene Triangle")
Program 15b: Write a Python script to read
a character and check whether it is an
alphabet, digit or a special character

115
Program:
c = input("Enter a character")
x = ord(c)

if (x >= 65 and x<= 90):


print("is an alphabet")
elif ( x>=48 and x<=57):
print("digit")
else:
print( c,"is special character")
Program 16:Write a Python script to read the x and y co-ordinate of
a point (x, y) and find the quadrant in which the point lies as given
below
Condition Quadrant

x is positive, y is positive First

x is negative, y is positive Second

x is negative, y is negative Third

x is positive, y is negative Fourth

117
if (x > 0 and y > 0):
print ("lies in First quadrant")

elif (x < 0 and y > 0):


print ("lies in Second quadrant")

elif (x < 0 and y < 0):


print ("lies in Third quadrant")

elif (x > 0 and y < 0):


print ("lies in Fourth quadrant")

elif (x == 0 and y > 0):


print ("lies at positive y axis")

elif (x == 0 and y < 0):


print ("lies at negative y axis")

elif (y == 0 and x < 0):


print ("lies at negative x axis")

elif (y == 0 and x > 0):


print ("lies at positive x axis")
else:
print ("lies at origin")
Iterative Control Structures
• While loop
• For loop
• Range function
• Break statement
• Continue statement
• PASS statement

119
While Loop
• Syntax
while condition:
suite (Statements within the same indentation belongs to the
same group called suite)
• Definite loop i=1
a program loop in which the number of times the loop will iterate can be while (i<6):
determined before the loop is executed. print(i)
i=i + 1
• Indefinite loop print('Good bye!')
program loop in which the number of times the loop will iterate cannot be
determined before the loop is executed.

120
• The break Statement: With the break statement we can stop the loop even if the while condition is true:
Example: i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Exit the loop when i is 3

The continue Statement: With the continue statement we can stop the current iteration, and continue with the next:
Example: Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement: With the else statement we can run a block of code once when the condition no longer is true:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
121
Program 17: Write a program using while loop and for loop in Python
that sums the first n integers, for a given (positive) value n entered by
the user.
# this program finds 1+2+3+…..+n, for a given n
sum = 0
current = 1
n = int(input("Enter a value:"))
while current <= n:
sum = sum + current
current = current + 1
print("Sum=", sum)

Using for loop:


sum=0
for current in range(1,4+1):
sum=sum+current
print(sum) 77
For Loop
• for loop in Python is used to iterate over a sequence (list, tuple,
string) or other iterable objects.
• Iterating over a sequence is called traversal.
• Syntax:
for var_name in sequence:
statement(s)
for i in [1,2,3,4,5]:
print(i)

123
Find output

1)# Iterating through list using for loop


L = [1,5,6,4,7,1,2,3,7] 2) #Iterating through a sequence
for i in L: defined by range function using for loop
print(I) for x in range(3, 12, 2):
print(x)
3)What happens here? Find output and
think 4) Iterating through a string using for loop
L = [1,5,6,4,7,1,2,3,7]
for x in "banana":
for i in L:
print(x)
print(i, end = " ")

124
Looping Through a String: The for statement can be applied to all sequence types, including strings. Thus, iteration
over a string can be done as follows (which prints each letter on a separate line)
for x in “Hello":
print(x)

The break Statement: With the break statement we can stop the loop before it has looped through all the items:
Example: Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break

The continue Statement: With the continue statement we can stop the current iteration of the loop, and continue with
the next. Example: Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
125
Range()
• Used to generate a sequence of numbers
• range(10) will generate numbers from 0 to 9 (10 numbers)
• Can define the start, stop and step size as range
• Default step size is 1
• All numbers generated are not stored in memory
• >>> range(10)
range(0, 10)

126
List()
• To display all the numbers generated by range()
• >>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2,8))
[2, 3, 4, 5, 6, 7]
>>> list(range(2,20,3))
[2, 5, 8, 11, 14, 17]

127
Using range() in for loop
• range() is also used in for loop to iterate over a sequence of
numbers
• Example
Program
n = int(input('Enter a number'))
for i in range(1,n+1):
print(i)
Enter a number 3
1
2
3

128
Program 18: Write a Python Program to read ‘n’ numbers and count positive,
negatives and zeros among them

np = 0
nn = 0
nz = 0
counter = 1
n = int(input('Enter the total no. of numbers'))
while counter <= n:
counter = counter + 1
num = int(input('Enter a number'))

129
if num < 0:
nn = nn + 1
elif num > 0:
np = np + 1
else:
nz = nz + 1
print('Positive count is {0}\n Negative count is {1}\n Zeros are
{2}'.format(np,nn,nz))

130
Program 19a:Write a program to check if the given number is prime or not
num=int(input())
if num==1 or num==0:
print ("Neither prime nor composite")
else:
for i in range(2,num):
if (num%i==0):
print("Not Prime")
break
else:
print("Prime")

131
Multiplication table of a given number.
Program 19b: Write a Python program that produces the multiplication
table for a specified number. The program should take the desired number
as input, and then output the multiplication table up to a certain limit,
such as up to 10.

n = int(input('Enter a number'))
for i in range(1,10+1):
print("{0} * {1} = {2}".format(n,i,n*i))

89
for i in range(n): # Loop from 0 to 4
*
**
for j in range(i): # Loop from 0 to i-1
Program 20: Write a Python program to construct the following pattern, using a nested for loop.

print('* ', end="") # Print '* ' without newline


***
****
*****
****

print('') # Print newline after inner loop completes


***
**
*

# Second pattern: Decreasing triangle


for i in range(n, 0, -1): # Loop from 5 to 1
for j in range(i): # Loop from 0 to i-1
print('* ', end="") # Print '* ' without newline
print('') # Print newline after inner loop completes
Program 21: Write a Python program to Print first n terms of the
fibonacci series.
a=0 else:
b=1 print("{0} \n{1}".format(a,b))
n = int(input('enter the number of terms')) count = 2
if n == 1:
print(a) while(count < n):
elif n == 2: c=a+b
print("{0} \n{1}".format(a,b)) print(c)
count = count + 1
a=b
b=c

90
FUNCTIONS
• A function is a piece of code in a program. The function
performs a specific task.
The advantages of using functions are:
• Reducing duplication of code
• Decomposing complex problems into simpler pieces
• Improving clarity of the code
• Reuse of code
• Information hiding

1
3
Syntax of
Function
def function_name (parameters):
 Therestatement(s)
are two basic types of functions.
 Built-in functions and user defined ones.
 The built-in functions are part of the Python language.
 Examples are: min(),max(), len() or abs().

1
3
2. User Defined Functions
• A function defined by the user in a program is known as
user defined function.
• Any name can be given to a user defined function, except
python keywords.
• we define the user-defined function using def keyword,
followed by the function name.
Here are simple rules to define a function in Python:
• Function blocks begin with the keyword def followed by the function
name and parentheses ( ).
• Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these parentheses.
• 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.

1
3
Ex.-1

def displayHello():
print(‘***********************’)
print(‘Hello World’)
print(‘**********************’)

displayHello() #function call , program


starts here

1
4
PARMETERS AND ARGUMENTS IN FUNCTION
Parameters are used to give inputs to function. They are specified with a pair of parenthesis
in the functions definition.
Arguments are values actually passed to functions when it is calling it. It will appear in
function call.
#wrong. Find why
Ex-2 def my_func(x, y, z):
def my_func(x, y, z): a=x+y
a=x+y b=a*z
return b
b=a*z
print(my_func(10,20,30))
return b
print(my_func(10.3,20.4,30))
print(my_f
unc(10,20,
30))
print(my_f
unc(10.3,2
0.4,30))
1
4
Arguments
Arguments can be passed to functions following the order in which they appear
in the function definition.
Ex-3
def print_parameters(a,b,c,d):
print("1st param:", a)
print("2nd param:", b) Output
print("3rd param:", c) 1st param: A
print("4th param:", d) 2nd param: B
3rd param: C
print_parameters("A", "B", "C",
4th param: D
"D")

1
4
Specifying default
values
During the definition of a function it is possible to specify default values.
Ex-4
def print_parameters(a="defaultA", b="defaultB",c="defaultC"):
print("a:",a)
print("b:",b)
print("c:",c)
print_parameters("param_A")
O
u
t
# Try another example with integer/float values p
c: defaultC
u
t
a: param_A
b: defaultB

1
4
Defining and Calling Value-Returning Functions
and Functions returning multiple values
• A call to a value returning function is an expression
• value is returned using a return statement.
Ex:
def avg(n1,n2,n3):
return (n1+n2+n3)/3.0
#function call
result = avg(10,20,30)
print(result)
Positional, Keyword and default
Arguments in Python
• A positional argument is an argument that is
assigned to a particular parameter on its position
in the argument list as given below
• Example 1: Positional Arguments
• def mortgageRate(amount, rate, term)
• ……………………………………………………………
• >>>monthly_payment = mortagageRate(35000,
• 0.06, 20)
Keyword Argument
• A keyword argument is an argument that is
specified by parameter name. There is no space
before and after the equal sign in a keyword
argument.
• Example : Keyword Arguments
• def mortgageRate(amount, rate, term)
• ……………………………………………………………
• >>>monthly_payment = mortagageRate(rate=0.06,
term = 20, amount =35000)
• A default argument is an argument that can be
optionally provided in a given function call. The
parameter is assigned a default value if not
provided in the calling statement.
• Example 5 Default Arguments
• def mortgageRate(amount, rate, term = 20)
• ……………………………………………………………
• >>>monthly_payment = mortagageRate(35000,
0.06)
Program 22a: Write a Program in Python to Find the factorial
of a given number using a function
# function to find the factorial of a given number n
def fact(num):
if num==0 or num==1:
return(1)
else:
factorial=1
for i in range(1,num+1):
factorial=factorial*i
return factorial
num = int(input('Enter a number’))
print(f'Factorial of {num} is {fact(num)}')

148
Program 22b:Write a Python function that takes a list of temperatures
in a given week from Monday to Sunday and returns the highest and
lowest temperature in that week
def maxmintemp(temps):
return(max(temps), min(temps))
temps=[]
while True:
t = float(input('Enter a temperature: '))
if t > 0:
temps.append(t)
else:
break
print(temps)
highlow = maxmintemp(temps)
print('The highest Temperature is', highlow[0])
print('The lowest Temperature is', highlow[1])
10
Lambda function
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can only have one
expression.
• Syntax of Lambda Function in pyhton lambda
arguments: expression
Example:
x = lambda a, b : a * b print(x(5, 6))

1
5
Thank You

151

You might also like