SlideShare a Scribd company logo
PYTHON APPLICATION PROGRAMMING -
18EC646
MODULE 1
Prof. Krishnananda L
Department of ECE
Govt SKSJTI
Bengaluru
INTRODUCTION
❑Python is a high level ,object-oriented programming language. It was created by
Guido van Rossum and released in 1991.
❑Python is a general purpose, dynamic, high-level, and interpreted programming
language. It supports Object Oriented programming approach to develop
applications. It is simple and easy to learn and provides lots of high-level data
structures.
❑It supports multiple programming pattern, including object-oriented, imperative
and functional or procedural programming styles and also interpreted scripting
language.
❑Python’s syntax and dynamic typing with its interpreted nature makes it an ideal
language for scripting and rapid application development.
2
❑An interpreter reads the source code of the program as written by the programmer, parses
the source code, and interprets the instructions on the fly.
❑ Python is an interpreted programming language. 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.
❑Even though we are typing these commands into Python one line at a time, Python is treating
them as an ordered sequence of statements with later statements able to retrieve data created
in earlier statements.
❑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.
3
INTRODUCTION
PYTHON FEATURES
• Python provides many useful features to the programmer. These features
make it most popular and widely used language. Essential features of
Python are:
• Easy to use and Learn
• Platform (Hardware) independent
• Interpreted Language
• Object-Oriented Language
• Free and Open Source Language
• GUI Programming Support
• Integrated/ Embeddable/Extensible
• Dynamic Memory Allocation
• Wide Range of Libraries and Frameworks 4
PYTHON APPLICATIONS
• Data Science
• Date Mining
• GUI Development
• Mobile Applications
• Software Development
• Artificial Intelligence
• Web Applications
• 3D CAD Applications
• Machine Learning
• Computer Vision/ Image Processing Applications.
• Speech Recognition, ChatBots
• Natural Language Processing (NLP)
• Scientific and Numeric programming
5
• The definition of a Program at its most basic is a sequence of Python statements that
have been crafted to do something. Even our simple hello.py script is a program.
• It is a one-line program and is not particularly useful, but in the strictest definition, it
is a Python program.
• When we want to write a program, we use a text editor to write the Python
instructions into a file, which is called a Script.
• By convention, Python scripts have names that end with .py.
• To execute the script, you have to tell the Python interpreter the name of the file.
6
• 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.
• 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.
7
Syntax error
• These are the first errors you will make and the easiest to fix. A syntax error means that you
have violated the “grammar” rules of Python.
• Python does its best to point right at the line and character where it noticed it was
confused.
Logic error
• 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.
• A good example of a logic error might be, “take a drink from your water bottle, put it in
your backpack, walk to the library, and then put the top back on the bottle.”
Semantic error
• A semantic error is when your description of the steps to take is syntactically perfect and
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.
8
9
• A variable is named place in the memory where a user can store data and later retrieve the
data using the variable “name”.
• User get to choose the names of variable and the contents of available can be changed in a
later statement.
• .In Python, variables are created when you assign a value to it: Python has no command for
declaring a variable
• Example:
• x = 5
y = "Hello, World!"
• In Python, variables are a symbolic name that is a reference or pointer to an object. The
variables are used to denote objects by that name.
10
VARIABLES/IDENTIFIERS
The rules to define an identifier are:
• The first character of the variable must be an alphabet or underscore ( _ ).
• Variable may contain alphabet of lower-case(a-z), upper-case (A-Z), underscore,
or digit (0-9).
• Identifier name must not contain any white-space, or special character (!, @, #,
%, ^, &, *).
• Identifier name must not be any keyword defined in the language.
• Identifier names are case sensitive; Ex: num, Num, NUM are different.
• Examples of valid identifiers: a123, _data, data_1, etc.
• Examples of invalid identifiers: 1a, n%4, n 9, etc.
11
TYPES OF VARIABLES IN PYTHON
Local Variables
• Local variables are the variables that declared inside the function and have scope within the
function.
• def add():
• # Defining local variables. They has scope only within a function
• a = 20
• b = 30
• c = a + b
• print("The sum is:", c)
• # Calling a function
• add()
• we declared a function named add() and assigned a few variables within the function. These
variables will be referred to as the local variables which have scope only inside the function.
If we try to use local variable outside their scope; it throws the NameError
12
Global Variables
• Global variables can be used throughout the program, and its scope is in the entire program. We can use global
variables inside or outside the function.
• Python provides the global keyword to use global variable inside the function. If we don't use the global keyword,
the function treats it as a local variable.
• # Declare a variable and initialize it
• x = 101
• # Global variable in function
• def fun1():
• # printing a global variable
• global x
• print(x)
• # modifying a global variable
• x = 'Welcome To python'
• print(x)
•
• fun1() ## calling a function
• print(x)
•
• output:
• 101
• Welcome To Python
• Welcome To Python
13
• Keywords are the reserved words in Python. They have a predefined meaning
• We cannot use a keyword as a variable name, function name or any other identifier.
• There are 33 keywords in python.
14
DATA TYPES IN PYTHON
15
• Integers:-In pyton,there is effectively no limit to how long an integer value can be. Of course,
it is constrained by the amount of memory your system has.
Ex: >>>n=5
>>>Type(n)
<Class ’Int’>
• Floating-point numbers:-The float type in python designates a floating point numbers.
Floating values are specified with a decimal point.
Ex:>>>n=2.6
>>>Type(n)
<Class ’float’>
• Complex numbers:-These are specified as <real_part>+<imaginary_part>.
Ex:>>>n=6+8j
>>>Type(n)
<Class ’complex’>
16
• Boolean type:-Python provides a Boolean data type. Objects of Boolean type may
have one of two values ,true or false.
Ex:>>>b ,k=4,7
>>>C=b>k
>>> C
false
>>>Type(c)
<Class ’bool’>
>>>Type(true)
<Class ’bool’>
• Strings:-Strings are sequence of character data. Strings literals may be delimited using
either single or double quotes.
Ex:>>>print(“Hello python”)
Hello python
>>>type(“Hello python”)
<Class ’str’>
17
• Ex1:>>>a=input(“enter a value:”)
enter a value:36
>>>type(a)
<class ’str’>
>>>b=int(a)+4
>>>b
40
>>>type(b)
<class’int’>
• Ex2:>>>y=34
>>>x=float(y)+7.94
>>>x
41.94
>>>type(x)
<class ’float’>
18
Python Provides built-in functions to convert
one data type to another
We use assignment statement to assign objects to names. The target of assignment statement
is written on left side of the equal sign ’+’,and the object on right can be an arbitrary
expression that computes an object.
Ex: x=x+2
‘x’ is the variable name.
‘=‘ is the assignment operator.
‘x+2’ is the expression.
Properties:
• Assignment creates object references instead of copying the objects.
• Python creates a variable name first time when they are assigns a value.
• Names must be assigned before being referenced.
• There are some operations that perform assignments implicitly.
19
• An Expression is a combination of values, variables, and operators. An expression is the
basic building block of python code that has a value.
• A value all by itself is considered an expression, and so is a variable.
• If you type an expression in interactive mode, the interpreter evaluates it and displays the
result:
>>> 1 + 1
2
• RHS of an Assignment operator is also an expression.
Ex: Literals: 5, 23.67, ‘python’ etc
Variable names: my_name, count etc
3+(5*x) where 5*x itself is an expression; so are x and 5.
•A statement is a unit of code that the Python interpreter can execute. Made up of
expressions.
•A script usually contains a sequence of statements.
• 20
• Operators are special symbols that represent computations like addition and multiplication.
• The values the operator is applied to are called Operands.
• The operators +, -, *, /, and ** perform addition, subtraction, multiplication, division, and
exponentiation, as in the following examples:
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.
• In Python 3.x, the result of this division is a floating point result:
>>> minute = 59
>>> minute/60
0.9833333333333333
0 21
Operator is a symbol that performs an operation on one or more operands.
An operand is a variable or a value on which we perform the operation.
There are 7 types of operators
22
Operators Meaning Example Output
Addition(+) Adds the values on either side of the operator. a+b 7
Subtraction(-) Subtracts the value on the right from the one on
the left.
a-b -1
Multiplication(*) Multiplies the values on either side of the
operator.
a*b 12
Division(/) Divides the value on the left by the one on the
right. (provide fractional quotient also)
b/a 1.3333
Exponentiation(**) Raises the first number to the power of the
second.
a**b 81
Floor Division(//) Divides and returns the integer value of the
quotient. It dumps the digits after the decimal.
b//a 1
Modulus(%) Divides and returns the value of the remainder. a%b 3
a=3
b=4
23
Operators Meaning Example Output
Less than(<) This operator checks if the value on the left of the
operator is lesser than the one on the right.
a<b True
Greater than(>) It checks if the value on the left of the operator is
greater than the one on the right.
a>b false
Less than or equal
to(<=)
It checks if the value on the left of the operator is lesser
than or equal to the one on the right.
a<=b True
Greater than or
equal to(>=)
It checks if the value on the left of the operator is
greater than or equal to the one on the right.
a>=b true
Equal to(= =) This operator checks if the value on the left of the
operator is equal to the one on the right.
a==b true
Not equal to(!=) It checks if the value on the left of the operator is not
equal to the one on the right.
a//b false
a=3
b=4
24
Operators Meaning Example Output
Assign(=) Assigns a value to the expression on the left. a=7 7
Add and Assign(+=) Adds the values on either side and assigns it to the expression on the
left.
a+=2 9
Subtract and
Assign(-=)
Subtracts the value on the right from the value on the left. a-=2 7
Divide and
Assign(/=)
Divides the value on the left by the one on the right. a/=7 1.0
Multiply and
Assign(*=)
Multiplies the values on either sides. a*=8 8.0
Modulus and
Assign(%=)
Performs modulus on the values on either side. a%=3 2.0
Exponent and
Assign(**=)
Performs exponentiation on the values on either side. a**=5 32.0
Floor-Divide and
Assign(//=)
Performs floor-division on the values on either side. a//=3 10.0
a=7
25
Operators Description Example Output
and If the conditions on both sides of the operator are true, then the
expression as a whole is true.
a=7>7
and 2>-1
false
or The expression is false only if both the statements around the
operator are false. Otherwise, it is true.
a=7>7
and 2>-1
True
not This inverts the Boolean value of an expression. It converts True to
False, and False to True.
a=not(0) True
26
27
Operator Description Example
in Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y
❑ Membership operators are used to test if a sequence is present in an object:
❑ Python membership operators are used to check the membership of value inside a Python
data structure. If the value is present in the data structure, then the resulting value is true
otherwise it returns false.
Operators Meaning Example Output
is If two operands have the same identity, it returns True.
Otherwise, it returns False.
‘2’ is “2” true
is not 2 is a number, and ‘2’ is a string. So, it returns a True. 2 is not ‘2’ True
28
Operators Meaning Example Output
Binary AND(&) It performs bit by bit AND operation on the two values. 2&3 2
Binary OR(|) It performs bit by bit OR on the two values. 2|3 3
Binary XOR(^) It performs bit by bit XOR(exclusive-OR) on the two
values.
2^3 1
Binary One’s
Complement(~)
It returns the one’s complement of a number’s binary. ~-3 2
Binary Left-
Shift(<<)
It shifts the value of the left operand the number of places
to the left that the right operand specifies. zeros are
inserted from the right, in the vacant position
2<<2 8
Binary Right-
Shift(>>)
it shifts the value of the left operand the number of places
to the right that the right operand specifies. Zeros are
inserted from the left, in the vacant position.
3>>2 1
29
30
• When more than one operator appears in an expression, the order of evaluation
depends on the rules of precedence.
• For mathematical operators, Python follows mathematical convention.
• The acronym PEMDAS is a useful way to remember the rules:
Parentheses
• have the highest precedence can be used to force an expression to evaluate in the order
you want.
• Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is
8.
• You can also use parentheses to make an expression easier to read, as in (minute * 100) /
60, even if it doesn’t change the result.
31
• Exponentiation has the next highest
precedence, so 2**1+1 is 34 and
3*1**3 is 3, not 27.
• Exponentiation has associativity
from right-to-left
• Multiplication and Division have
the same precedence, higher than
Addition and Subtraction, which
also have the same precedence.
• So 2*3-1 is 5 and 6+4/2 is 8.0
• Operators with the same precedence
are evaluated from left to right.
• So the expression 5-3-1 is 1, not 3,
because the 5-3 happens first and
then 1 is subtracted from 2.
32
• A program needs to interact with the user to accomplish the desired task; this can be achieved
using Input-Output functions.
• Python provides a built-in function called input that gets input from the 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.
• Before getting input from the user, it is a good idea to print a prompt telling the user what to
input.
• You can pass a string to input to be displayed to the user before pausing for input:
>>> msg = input('What is your name?’)
What is your name?
Krishna
>>> print(name)
Krishna 33
The input() function helps to enter data at run time by the user and the output function print() is
used to display the result of the program on the screen after execution.
The syntax for input()
Variable = input (“prompt string”)
where, prompt string in the syntax is a statement or message to the user, to know what
input can be given.
Example 1:input( ) with prompt string
>>>city=input (“Enter Your City: ”)
Enter Your City: Bengaluru
>>>print (“I am from “, city)
Output:
I am from Bengaluru
34
Example:
>>>x = 5
>>>y = 6
>>>z = x + y
>>>print (z)
11
>>> print (“The sum = ”, z)
The sum = 11
>>> print (“The sum of ”, x, “ and ”, y, “ is ”, z)
Output:
The sum of 5 and 6 is 11
35
The print() function
In Python, the print() function is used to display
result on the screen.
The syntax for print()
print (“string to be displayed as output ” )
print (variable )
print (“String to be displayed as output ”, variable)
print (“String1 ”, variable, “String 2”, variable,
“String 3” ……)
Note: In Python, single line comments start with # symbol. For multiline/block comment,
Start wth three double quotes (“””) and end with the same after the block (“””)
36
""""
formatted output using print"""
a, b, c= 10, 20, 30
print (a)
print (b)
print (c)
print (a, b, c)
print (a, b, c, sep='-')
print ("n")
print ("a=" , a, "b=", b, "c=", c)
print (' the value of a, b, c is :', a, b, c)
print (a, 2*a, 3*a, 4*a, sep='-')
print ("%d %d %d " %(a,b,c))
print ("value of a = %d, value of b= %d, value of c = %d "
%(a, b, c))
print()
print ("value of a = {}, value of b={}, value of
c={}".format(a,b,c))
print()
print ("value of a={2}, value of b={1}, value of
c={0}".format (a,b,c))
print ()
print (f"value of a={a}, b={b} and c={c}")
print()
print (f"value of a={c}, b={a} and c ={a}")
print ()
• At this point, the syntax error you are most likely to make is an illegal variable name.
• If you put a space in a variable name, Python thinks it is two operands without an operator:
>>> bad name = 5
SyntaxError: invalid syntax
>>> month = 09
File "<stdin>", line 1
month = 09
• SyntaxError: invalid token
• For syntax errors, the error messages don’t help much. The most common messages are
Syntax Error: invalid syntax and Syntax Error: invalid token, neither of which is very
informative.
37
Why is it worth the trouble to divide a program into functions??? There are several reasons:
• Creating a new function gives an opportunity to name a group of statements, which
makes your program easier to read, understand, and debug.
• Functions can make a program smaller by eliminating repetitive code. Later, if you make
a change, you only have to make it in one place.
• Dividing a long program into functions allows you to debug the parts one at a time and
then assemble them into a complete unit.
• Well-designed functions are very useful. Once you write and debug one, you can reuse it.
• Functions provide a “structure” to a complex program/program having hundreds of lines
of code. Its easier to break the program into constituent functions or modules for better
understanding, editing, debugging, testing and so on.
38
• Some of the functions we are using, such as the math functions, yield results; they are called
fruitful functions. Other functions, perform an action but don’t return a value. They are called
void functions.
• When you call a fruitful function, you almost always want to do something with the result;
for example,
x= math.cos(radians)
When you call a function in interactive mode
result: >>> math.sqrt(5)
2.23606797749979
❑Void functions might display something on the screen or have some other effect, but
they don’t have a return value. If you try to assign the result to a variable, you get a
special value called None. Ex: print (“welcome to Python”) 39
1.To check whether a person is eligible to vote in the election. Accept appropriate
input and display message accordingly
age=int(input(" enter age:"))
if(age>=18):
print("eligible for voting")
else:
print("not eligible for voting")
output:
enter age:24
eligible for voting
enter age:14
not eligible for voting
40
2.To find sum of natural numbers
num = 16
if num < 0:
print("Enter a positive number")
else:
sum = 0
print("The sum is", sum)
output:
The sum is 136
3.To find area of a circle
import math
r=int(input("enter the radius:"))
area=r*pi*pi
print("the area of circle is ",area)
output:
enter the radius:4
the area of circle is 50.24
41
4.Program to Check if a Number is Odd or Even
num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even number". Format(num))
else:
print("{0} is Odd number". Format(num))
output:
15 is the odd number
16 is the even number
42
5.Program to Check Prime Number
num = int(input("Enter a number: "))
if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
output: Enter a number:313
313 is a prime number
5.Program to Find the Factorial of a Number
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative nu
mbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
output: Enter a number:5
the factorial of 5 is 120
43
6.Test whether a passed letter is a vowel or not
def is_vowel(char):
all_vowels = 'aeiou’
return char in all_vowels
print(is_vowel('c’))
print(is_vowel('e’))
output:
False
True
7.Python Program to find ASCII Value of a
Character
ch = input(" enter any Character:")
print("The ASCII Value of %c = %d" %(ch, ord(ch)))
output:
enter any Character : a
The ASCII Value of a = 97
8.Program to Swap Two Numbers using a temporary variable
a = float(input(" Enter the First Value a: "))
b = float(input(" Enter the Second Value b: "))
print("Before Swapping two Number: a = {0} and b = {1}".format(a, b))
temp = a
a = b
b = temp
print("After Swapping two Number: a = {0} and b = {1}".format(a, b))
output:
Enter the First Value a: 10
Enter the Second Value b: 20
Before Swapping two Number: a = 10.0 and b = 20.0
After Swapping two Number: a = 20.0 and b = 10.0
44
9.Program to Check Leap Year using if Statement
year = int(input("Enter the Year Number : "))
if (((year%400==0)) or (( year%4 == 0 ) and ( year%100 != 0))):
print("%d is a Leap Year" %year)
else:
print("%d is Not the Leap Year" %year)
output:
Enter the Year Number you wish: 1200
1200 is a Leap Year
45
10.Program to find GCD/HCF of Two Numbers
a = float(input(" Enter the First Value a: "))
b = float(input(" Enter the Second Value b: "))
i = 1
while(i <= a and i <= b):
if(a % i == 0 and b % i == 0):
gcd = i
i = i + 1
print("n HCF of {0} and {1} = {2}".format(a, b, gcd))
output:
Enter the First Value a: 8
Enter the Second Value b: 12
HCF of 8.0 and 12.0 = 4
46
11. Program to Calculate Electricity Bill ( nested if-else)
units = int(input(" enter Number of Units you Consumed : "))
if units < 50:
amount = units * 2.60
surcharge = 25
elif units <= 100:
amount = 130 + ((units - 50) * 3.25)
surcharge = 35
elif units <= 200:
amount = 130 + 162.50 + ((units - 100) * 5.26)
surcharge = 45
else:
amount = 130 + 162.50 + 526 + ((units - 200) * 8.45)
surcharge = 75
total = amount + surcharge
print("nElectricity Bill = %.2f" %total)
output: enter Number of Units you Consumed :75
Electricity Bill =246.25
47

More Related Content

Similar to Python Module-1.1.pdf

web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
Bhavsingh Maloth
 
Python Programming
Python ProgrammingPython Programming
Python Programming
Saravanan T.M
 
bhaskars.pptx
bhaskars.pptxbhaskars.pptx
bhaskars.pptx
NaveenShankar34
 
Introduction to Python Programing
Introduction to Python ProgramingIntroduction to Python Programing
Introduction to Python Programing
sameer patil
 
Advance Python programming languages-Simple Easy learning
Advance Python programming languages-Simple Easy learningAdvance Python programming languages-Simple Easy learning
Advance Python programming languages-Simple Easy learning
sherinjoyson
 
Python Programming.pptx
Python Programming.pptxPython Programming.pptx
Python Programming.pptx
DineshThakur911173
 
Python PPT.pptx
Python PPT.pptxPython PPT.pptx
Python PPT.pptx
JosephMuez2
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
IruolagbePius
 
Python_Introduction&DataType.pptx
Python_Introduction&DataType.pptxPython_Introduction&DataType.pptx
Python_Introduction&DataType.pptx
HaythamBarakeh1
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptx
lemonchoos
 
Python Programming 1.pptx
Python Programming 1.pptxPython Programming 1.pptx
Python Programming 1.pptx
Francis Densil Raj
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
michaelaaron25322
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their ownBASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ayshwarya Baburam
 
Python 01.pptx
Python 01.pptxPython 01.pptx
Python 01.pptx
AliMohammadAmiri
 
prakash ppt (2).pdf
prakash ppt (2).pdfprakash ppt (2).pdf
prakash ppt (2).pdf
ShivamKS4
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ranjith kumar
 
Python indroduction
Python indroductionPython indroduction
Python indroduction
FEG
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
ParveenShaik21
 

Similar to Python Module-1.1.pdf (20)

web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
bhaskars.pptx
bhaskars.pptxbhaskars.pptx
bhaskars.pptx
 
Introduction to Python Programing
Introduction to Python ProgramingIntroduction to Python Programing
Introduction to Python Programing
 
Advance Python programming languages-Simple Easy learning
Advance Python programming languages-Simple Easy learningAdvance Python programming languages-Simple Easy learning
Advance Python programming languages-Simple Easy learning
 
Python Programming.pptx
Python Programming.pptxPython Programming.pptx
Python Programming.pptx
 
Python PPT.pptx
Python PPT.pptxPython PPT.pptx
Python PPT.pptx
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
 
Python_Introduction&DataType.pptx
Python_Introduction&DataType.pptxPython_Introduction&DataType.pptx
Python_Introduction&DataType.pptx
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptx
 
Python Programming 1.pptx
Python Programming 1.pptxPython Programming 1.pptx
Python Programming 1.pptx
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their ownBASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their own
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python 01.pptx
Python 01.pptxPython 01.pptx
Python 01.pptx
 
prakash ppt (2).pdf
prakash ppt (2).pdfprakash ppt (2).pdf
prakash ppt (2).pdf
 
INTERNSHIP REPORT.docx
 INTERNSHIP REPORT.docx INTERNSHIP REPORT.docx
INTERNSHIP REPORT.docx
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python indroduction
Python indroductionPython indroduction
Python indroduction
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 

Recently uploaded

Expert Accessory Dwelling Unit (ADU) Drafting Services
Expert Accessory Dwelling Unit (ADU) Drafting ServicesExpert Accessory Dwelling Unit (ADU) Drafting Services
Expert Accessory Dwelling Unit (ADU) Drafting Services
ResDraft
 
一比一原版(Glasgow毕业证书)格拉斯哥大学毕业证成绩单如何办理
一比一原版(Glasgow毕业证书)格拉斯哥大学毕业证成绩单如何办理一比一原版(Glasgow毕业证书)格拉斯哥大学毕业证成绩单如何办理
一比一原版(Glasgow毕业证书)格拉斯哥大学毕业证成绩单如何办理
n0tivyq
 
一比一原版(LSE毕业证书)伦敦政治经济学院毕业证成绩单如何办理
一比一原版(LSE毕业证书)伦敦政治经济学院毕业证成绩单如何办理一比一原版(LSE毕业证书)伦敦政治经济学院毕业证成绩单如何办理
一比一原版(LSE毕业证书)伦敦政治经济学院毕业证成绩单如何办理
jyz59f4j
 
一比一原版(MMU毕业证书)曼彻斯特城市大学毕业证成绩单如何办理
一比一原版(MMU毕业证书)曼彻斯特城市大学毕业证成绩单如何办理一比一原版(MMU毕业证书)曼彻斯特城市大学毕业证成绩单如何办理
一比一原版(MMU毕业证书)曼彻斯特城市大学毕业证成绩单如何办理
7sd8fier
 
Common Designing Mistakes and How to avoid them
Common Designing Mistakes and How to avoid themCommon Designing Mistakes and How to avoid them
Common Designing Mistakes and How to avoid them
madhavlakhanpal29
 
原版定做(penn毕业证书)美国宾夕法尼亚大学毕业证文凭学历证书原版一模一样
原版定做(penn毕业证书)美国宾夕法尼亚大学毕业证文凭学历证书原版一模一样原版定做(penn毕业证书)美国宾夕法尼亚大学毕业证文凭学历证书原版一模一样
原版定做(penn毕业证书)美国宾夕法尼亚大学毕业证文凭学历证书原版一模一样
gpffo76j
 
Research 20 slides Amelia gavryliuks.pdf
Research 20 slides Amelia gavryliuks.pdfResearch 20 slides Amelia gavryliuks.pdf
Research 20 slides Amelia gavryliuks.pdf
ameli25062005
 
Portfolio.pdf
Portfolio.pdfPortfolio.pdf
Portfolio.pdf
garcese
 
projectreportnew-170307082323 nnnnnn(1).pdf
projectreportnew-170307082323 nnnnnn(1).pdfprojectreportnew-170307082323 nnnnnn(1).pdf
projectreportnew-170307082323 nnnnnn(1).pdf
farazahmadas6
 
一比一原版(RHUL毕业证书)伦敦大学皇家霍洛威学院毕业证如何办理
一比一原版(RHUL毕业证书)伦敦大学皇家霍洛威学院毕业证如何办理一比一原版(RHUL毕业证书)伦敦大学皇家霍洛威学院毕业证如何办理
一比一原版(RHUL毕业证书)伦敦大学皇家霍洛威学院毕业证如何办理
9a93xvy
 
Transforming Brand Perception and Boosting Profitability
Transforming Brand Perception and Boosting ProfitabilityTransforming Brand Perception and Boosting Profitability
Transforming Brand Perception and Boosting Profitability
aaryangarg12
 
7 Alternatives to Bullet Points in PowerPoint
7 Alternatives to Bullet Points in PowerPoint7 Alternatives to Bullet Points in PowerPoint
7 Alternatives to Bullet Points in PowerPoint
Alvis Oh
 
20 slides of research movie and artists .pdf
20 slides of research movie and artists .pdf20 slides of research movie and artists .pdf
20 slides of research movie and artists .pdf
ameli25062005
 
Design Thinking Design thinking Design thinking
Design Thinking Design thinking Design thinkingDesign Thinking Design thinking Design thinking
Design Thinking Design thinking Design thinking
cy0krjxt
 
Borys Sutkowski portfolio interior design
Borys Sutkowski portfolio interior designBorys Sutkowski portfolio interior design
Borys Sutkowski portfolio interior design
boryssutkowski
 
Mohannad Abdullah portfolio _ V2 _22-24
Mohannad Abdullah  portfolio _ V2 _22-24Mohannad Abdullah  portfolio _ V2 _22-24
Mohannad Abdullah portfolio _ V2 _22-24
M. A. Architect
 
Book Formatting: Quality Control Checks for Designers
Book Formatting: Quality Control Checks for DesignersBook Formatting: Quality Control Checks for Designers
Book Formatting: Quality Control Checks for Designers
Confidence Ago
 
PORTFOLIO FABIANA VILLANI ARCHITECTURE.pdf
PORTFOLIO FABIANA VILLANI ARCHITECTURE.pdfPORTFOLIO FABIANA VILLANI ARCHITECTURE.pdf
PORTFOLIO FABIANA VILLANI ARCHITECTURE.pdf
fabianavillanib
 
一比一原版(UCB毕业证书)伯明翰大学学院毕业证成绩单如何办理
一比一原版(UCB毕业证书)伯明翰大学学院毕业证成绩单如何办理一比一原版(UCB毕业证书)伯明翰大学学院毕业证成绩单如何办理
一比一原版(UCB毕业证书)伯明翰大学学院毕业证成绩单如何办理
h7j5io0
 
一比一原版(Brunel毕业证书)布鲁内尔大学毕业证成绩单如何办理
一比一原版(Brunel毕业证书)布鲁内尔大学毕业证成绩单如何办理一比一原版(Brunel毕业证书)布鲁内尔大学毕业证成绩单如何办理
一比一原版(Brunel毕业证书)布鲁内尔大学毕业证成绩单如何办理
smpc3nvg
 

Recently uploaded (20)

Expert Accessory Dwelling Unit (ADU) Drafting Services
Expert Accessory Dwelling Unit (ADU) Drafting ServicesExpert Accessory Dwelling Unit (ADU) Drafting Services
Expert Accessory Dwelling Unit (ADU) Drafting Services
 
一比一原版(Glasgow毕业证书)格拉斯哥大学毕业证成绩单如何办理
一比一原版(Glasgow毕业证书)格拉斯哥大学毕业证成绩单如何办理一比一原版(Glasgow毕业证书)格拉斯哥大学毕业证成绩单如何办理
一比一原版(Glasgow毕业证书)格拉斯哥大学毕业证成绩单如何办理
 
一比一原版(LSE毕业证书)伦敦政治经济学院毕业证成绩单如何办理
一比一原版(LSE毕业证书)伦敦政治经济学院毕业证成绩单如何办理一比一原版(LSE毕业证书)伦敦政治经济学院毕业证成绩单如何办理
一比一原版(LSE毕业证书)伦敦政治经济学院毕业证成绩单如何办理
 
一比一原版(MMU毕业证书)曼彻斯特城市大学毕业证成绩单如何办理
一比一原版(MMU毕业证书)曼彻斯特城市大学毕业证成绩单如何办理一比一原版(MMU毕业证书)曼彻斯特城市大学毕业证成绩单如何办理
一比一原版(MMU毕业证书)曼彻斯特城市大学毕业证成绩单如何办理
 
Common Designing Mistakes and How to avoid them
Common Designing Mistakes and How to avoid themCommon Designing Mistakes and How to avoid them
Common Designing Mistakes and How to avoid them
 
原版定做(penn毕业证书)美国宾夕法尼亚大学毕业证文凭学历证书原版一模一样
原版定做(penn毕业证书)美国宾夕法尼亚大学毕业证文凭学历证书原版一模一样原版定做(penn毕业证书)美国宾夕法尼亚大学毕业证文凭学历证书原版一模一样
原版定做(penn毕业证书)美国宾夕法尼亚大学毕业证文凭学历证书原版一模一样
 
Research 20 slides Amelia gavryliuks.pdf
Research 20 slides Amelia gavryliuks.pdfResearch 20 slides Amelia gavryliuks.pdf
Research 20 slides Amelia gavryliuks.pdf
 
Portfolio.pdf
Portfolio.pdfPortfolio.pdf
Portfolio.pdf
 
projectreportnew-170307082323 nnnnnn(1).pdf
projectreportnew-170307082323 nnnnnn(1).pdfprojectreportnew-170307082323 nnnnnn(1).pdf
projectreportnew-170307082323 nnnnnn(1).pdf
 
一比一原版(RHUL毕业证书)伦敦大学皇家霍洛威学院毕业证如何办理
一比一原版(RHUL毕业证书)伦敦大学皇家霍洛威学院毕业证如何办理一比一原版(RHUL毕业证书)伦敦大学皇家霍洛威学院毕业证如何办理
一比一原版(RHUL毕业证书)伦敦大学皇家霍洛威学院毕业证如何办理
 
Transforming Brand Perception and Boosting Profitability
Transforming Brand Perception and Boosting ProfitabilityTransforming Brand Perception and Boosting Profitability
Transforming Brand Perception and Boosting Profitability
 
7 Alternatives to Bullet Points in PowerPoint
7 Alternatives to Bullet Points in PowerPoint7 Alternatives to Bullet Points in PowerPoint
7 Alternatives to Bullet Points in PowerPoint
 
20 slides of research movie and artists .pdf
20 slides of research movie and artists .pdf20 slides of research movie and artists .pdf
20 slides of research movie and artists .pdf
 
Design Thinking Design thinking Design thinking
Design Thinking Design thinking Design thinkingDesign Thinking Design thinking Design thinking
Design Thinking Design thinking Design thinking
 
Borys Sutkowski portfolio interior design
Borys Sutkowski portfolio interior designBorys Sutkowski portfolio interior design
Borys Sutkowski portfolio interior design
 
Mohannad Abdullah portfolio _ V2 _22-24
Mohannad Abdullah  portfolio _ V2 _22-24Mohannad Abdullah  portfolio _ V2 _22-24
Mohannad Abdullah portfolio _ V2 _22-24
 
Book Formatting: Quality Control Checks for Designers
Book Formatting: Quality Control Checks for DesignersBook Formatting: Quality Control Checks for Designers
Book Formatting: Quality Control Checks for Designers
 
PORTFOLIO FABIANA VILLANI ARCHITECTURE.pdf
PORTFOLIO FABIANA VILLANI ARCHITECTURE.pdfPORTFOLIO FABIANA VILLANI ARCHITECTURE.pdf
PORTFOLIO FABIANA VILLANI ARCHITECTURE.pdf
 
一比一原版(UCB毕业证书)伯明翰大学学院毕业证成绩单如何办理
一比一原版(UCB毕业证书)伯明翰大学学院毕业证成绩单如何办理一比一原版(UCB毕业证书)伯明翰大学学院毕业证成绩单如何办理
一比一原版(UCB毕业证书)伯明翰大学学院毕业证成绩单如何办理
 
一比一原版(Brunel毕业证书)布鲁内尔大学毕业证成绩单如何办理
一比一原版(Brunel毕业证书)布鲁内尔大学毕业证成绩单如何办理一比一原版(Brunel毕业证书)布鲁内尔大学毕业证成绩单如何办理
一比一原版(Brunel毕业证书)布鲁内尔大学毕业证成绩单如何办理
 

Python Module-1.1.pdf

  • 1. PYTHON APPLICATION PROGRAMMING - 18EC646 MODULE 1 Prof. Krishnananda L Department of ECE Govt SKSJTI Bengaluru
  • 2. INTRODUCTION ❑Python is a high level ,object-oriented programming language. It was created by Guido van Rossum and released in 1991. ❑Python is a general purpose, dynamic, high-level, and interpreted programming language. It supports Object Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-level data structures. ❑It supports multiple programming pattern, including object-oriented, imperative and functional or procedural programming styles and also interpreted scripting language. ❑Python’s syntax and dynamic typing with its interpreted nature makes it an ideal language for scripting and rapid application development. 2
  • 3. ❑An interpreter reads the source code of the program as written by the programmer, parses the source code, and interprets the instructions on the fly. ❑ Python is an interpreted programming language. 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. ❑Even though we are typing these commands into Python one line at a time, Python is treating them as an ordered sequence of statements with later statements able to retrieve data created in earlier statements. ❑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. 3 INTRODUCTION
  • 4. PYTHON FEATURES • Python provides many useful features to the programmer. These features make it most popular and widely used language. Essential features of Python are: • Easy to use and Learn • Platform (Hardware) independent • Interpreted Language • Object-Oriented Language • Free and Open Source Language • GUI Programming Support • Integrated/ Embeddable/Extensible • Dynamic Memory Allocation • Wide Range of Libraries and Frameworks 4
  • 5. PYTHON APPLICATIONS • Data Science • Date Mining • GUI Development • Mobile Applications • Software Development • Artificial Intelligence • Web Applications • 3D CAD Applications • Machine Learning • Computer Vision/ Image Processing Applications. • Speech Recognition, ChatBots • Natural Language Processing (NLP) • Scientific and Numeric programming 5
  • 6. • The definition of a Program at its most basic is a sequence of Python statements that have been crafted to do something. Even our simple hello.py script is a program. • It is a one-line program and is not particularly useful, but in the strictest definition, it is a Python program. • When we want to write a program, we use a text editor to write the Python instructions into a file, which is called a Script. • By convention, Python scripts have names that end with .py. • To execute the script, you have to tell the Python interpreter the name of the file. 6
  • 7. • 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. • 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. 7
  • 8. Syntax error • These are the first errors you will make and the easiest to fix. A syntax error means that you have violated the “grammar” rules of Python. • Python does its best to point right at the line and character where it noticed it was confused. Logic error • 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. • A good example of a logic error might be, “take a drink from your water bottle, put it in your backpack, walk to the library, and then put the top back on the bottle.” Semantic error • A semantic error is when your description of the steps to take is syntactically perfect and 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. 8
  • 9. 9
  • 10. • A variable is named place in the memory where a user can store data and later retrieve the data using the variable “name”. • User get to choose the names of variable and the contents of available can be changed in a later statement. • .In Python, variables are created when you assign a value to it: Python has no command for declaring a variable • Example: • x = 5 y = "Hello, World!" • In Python, variables are a symbolic name that is a reference or pointer to an object. The variables are used to denote objects by that name. 10
  • 11. VARIABLES/IDENTIFIERS The rules to define an identifier are: • The first character of the variable must be an alphabet or underscore ( _ ). • Variable may contain alphabet of lower-case(a-z), upper-case (A-Z), underscore, or digit (0-9). • Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *). • Identifier name must not be any keyword defined in the language. • Identifier names are case sensitive; Ex: num, Num, NUM are different. • Examples of valid identifiers: a123, _data, data_1, etc. • Examples of invalid identifiers: 1a, n%4, n 9, etc. 11
  • 12. TYPES OF VARIABLES IN PYTHON Local Variables • Local variables are the variables that declared inside the function and have scope within the function. • def add(): • # Defining local variables. They has scope only within a function • a = 20 • b = 30 • c = a + b • print("The sum is:", c) • # Calling a function • add() • we declared a function named add() and assigned a few variables within the function. These variables will be referred to as the local variables which have scope only inside the function. If we try to use local variable outside their scope; it throws the NameError 12
  • 13. Global Variables • Global variables can be used throughout the program, and its scope is in the entire program. We can use global variables inside or outside the function. • Python provides the global keyword to use global variable inside the function. If we don't use the global keyword, the function treats it as a local variable. • # Declare a variable and initialize it • x = 101 • # Global variable in function • def fun1(): • # printing a global variable • global x • print(x) • # modifying a global variable • x = 'Welcome To python' • print(x) • • fun1() ## calling a function • print(x) • • output: • 101 • Welcome To Python • Welcome To Python 13
  • 14. • Keywords are the reserved words in Python. They have a predefined meaning • We cannot use a keyword as a variable name, function name or any other identifier. • There are 33 keywords in python. 14
  • 15. DATA TYPES IN PYTHON 15
  • 16. • Integers:-In pyton,there is effectively no limit to how long an integer value can be. Of course, it is constrained by the amount of memory your system has. Ex: >>>n=5 >>>Type(n) <Class ’Int’> • Floating-point numbers:-The float type in python designates a floating point numbers. Floating values are specified with a decimal point. Ex:>>>n=2.6 >>>Type(n) <Class ’float’> • Complex numbers:-These are specified as <real_part>+<imaginary_part>. Ex:>>>n=6+8j >>>Type(n) <Class ’complex’> 16
  • 17. • Boolean type:-Python provides a Boolean data type. Objects of Boolean type may have one of two values ,true or false. Ex:>>>b ,k=4,7 >>>C=b>k >>> C false >>>Type(c) <Class ’bool’> >>>Type(true) <Class ’bool’> • Strings:-Strings are sequence of character data. Strings literals may be delimited using either single or double quotes. Ex:>>>print(“Hello python”) Hello python >>>type(“Hello python”) <Class ’str’> 17
  • 18. • Ex1:>>>a=input(“enter a value:”) enter a value:36 >>>type(a) <class ’str’> >>>b=int(a)+4 >>>b 40 >>>type(b) <class’int’> • Ex2:>>>y=34 >>>x=float(y)+7.94 >>>x 41.94 >>>type(x) <class ’float’> 18 Python Provides built-in functions to convert one data type to another
  • 19. We use assignment statement to assign objects to names. The target of assignment statement is written on left side of the equal sign ’+’,and the object on right can be an arbitrary expression that computes an object. Ex: x=x+2 ‘x’ is the variable name. ‘=‘ is the assignment operator. ‘x+2’ is the expression. Properties: • Assignment creates object references instead of copying the objects. • Python creates a variable name first time when they are assigns a value. • Names must be assigned before being referenced. • There are some operations that perform assignments implicitly. 19
  • 20. • An Expression is a combination of values, variables, and operators. An expression is the basic building block of python code that has a value. • A value all by itself is considered an expression, and so is a variable. • If you type an expression in interactive mode, the interpreter evaluates it and displays the result: >>> 1 + 1 2 • RHS of an Assignment operator is also an expression. Ex: Literals: 5, 23.67, ‘python’ etc Variable names: my_name, count etc 3+(5*x) where 5*x itself is an expression; so are x and 5. •A statement is a unit of code that the Python interpreter can execute. Made up of expressions. •A script usually contains a sequence of statements. • 20
  • 21. • Operators are special symbols that represent computations like addition and multiplication. • The values the operator is applied to are called Operands. • The operators +, -, *, /, and ** perform addition, subtraction, multiplication, division, and exponentiation, as in the following examples: 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. • In Python 3.x, the result of this division is a floating point result: >>> minute = 59 >>> minute/60 0.9833333333333333 0 21
  • 22. Operator is a symbol that performs an operation on one or more operands. An operand is a variable or a value on which we perform the operation. There are 7 types of operators 22
  • 23. Operators Meaning Example Output Addition(+) Adds the values on either side of the operator. a+b 7 Subtraction(-) Subtracts the value on the right from the one on the left. a-b -1 Multiplication(*) Multiplies the values on either side of the operator. a*b 12 Division(/) Divides the value on the left by the one on the right. (provide fractional quotient also) b/a 1.3333 Exponentiation(**) Raises the first number to the power of the second. a**b 81 Floor Division(//) Divides and returns the integer value of the quotient. It dumps the digits after the decimal. b//a 1 Modulus(%) Divides and returns the value of the remainder. a%b 3 a=3 b=4 23
  • 24. Operators Meaning Example Output Less than(<) This operator checks if the value on the left of the operator is lesser than the one on the right. a<b True Greater than(>) It checks if the value on the left of the operator is greater than the one on the right. a>b false Less than or equal to(<=) It checks if the value on the left of the operator is lesser than or equal to the one on the right. a<=b True Greater than or equal to(>=) It checks if the value on the left of the operator is greater than or equal to the one on the right. a>=b true Equal to(= =) This operator checks if the value on the left of the operator is equal to the one on the right. a==b true Not equal to(!=) It checks if the value on the left of the operator is not equal to the one on the right. a//b false a=3 b=4 24
  • 25. Operators Meaning Example Output Assign(=) Assigns a value to the expression on the left. a=7 7 Add and Assign(+=) Adds the values on either side and assigns it to the expression on the left. a+=2 9 Subtract and Assign(-=) Subtracts the value on the right from the value on the left. a-=2 7 Divide and Assign(/=) Divides the value on the left by the one on the right. a/=7 1.0 Multiply and Assign(*=) Multiplies the values on either sides. a*=8 8.0 Modulus and Assign(%=) Performs modulus on the values on either side. a%=3 2.0 Exponent and Assign(**=) Performs exponentiation on the values on either side. a**=5 32.0 Floor-Divide and Assign(//=) Performs floor-division on the values on either side. a//=3 10.0 a=7 25
  • 26. Operators Description Example Output and If the conditions on both sides of the operator are true, then the expression as a whole is true. a=7>7 and 2>-1 false or The expression is false only if both the statements around the operator are false. Otherwise, it is true. a=7>7 and 2>-1 True not This inverts the Boolean value of an expression. It converts True to False, and False to True. a=not(0) True 26
  • 27. 27 Operator Description Example in Returns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object x not in y ❑ Membership operators are used to test if a sequence is present in an object: ❑ Python membership operators are used to check the membership of value inside a Python data structure. If the value is present in the data structure, then the resulting value is true otherwise it returns false.
  • 28. Operators Meaning Example Output is If two operands have the same identity, it returns True. Otherwise, it returns False. ‘2’ is “2” true is not 2 is a number, and ‘2’ is a string. So, it returns a True. 2 is not ‘2’ True 28
  • 29. Operators Meaning Example Output Binary AND(&) It performs bit by bit AND operation on the two values. 2&3 2 Binary OR(|) It performs bit by bit OR on the two values. 2|3 3 Binary XOR(^) It performs bit by bit XOR(exclusive-OR) on the two values. 2^3 1 Binary One’s Complement(~) It returns the one’s complement of a number’s binary. ~-3 2 Binary Left- Shift(<<) It shifts the value of the left operand the number of places to the left that the right operand specifies. zeros are inserted from the right, in the vacant position 2<<2 8 Binary Right- Shift(>>) it shifts the value of the left operand the number of places to the right that the right operand specifies. Zeros are inserted from the left, in the vacant position. 3>>2 1 29
  • 30. 30
  • 31. • When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. • For mathematical operators, Python follows mathematical convention. • The acronym PEMDAS is a useful way to remember the rules: Parentheses • have the highest precedence can be used to force an expression to evaluate in the order you want. • Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. • You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn’t change the result. 31
  • 32. • Exponentiation has the next highest precedence, so 2**1+1 is 34 and 3*1**3 is 3, not 27. • Exponentiation has associativity from right-to-left • Multiplication and Division have the same precedence, higher than Addition and Subtraction, which also have the same precedence. • So 2*3-1 is 5 and 6+4/2 is 8.0 • Operators with the same precedence are evaluated from left to right. • So the expression 5-3-1 is 1, not 3, because the 5-3 happens first and then 1 is subtracted from 2. 32
  • 33. • A program needs to interact with the user to accomplish the desired task; this can be achieved using Input-Output functions. • Python provides a built-in function called input that gets input from the 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. • Before getting input from the user, it is a good idea to print a prompt telling the user what to input. • You can pass a string to input to be displayed to the user before pausing for input: >>> msg = input('What is your name?’) What is your name? Krishna >>> print(name) Krishna 33
  • 34. The input() function helps to enter data at run time by the user and the output function print() is used to display the result of the program on the screen after execution. The syntax for input() Variable = input (“prompt string”) where, prompt string in the syntax is a statement or message to the user, to know what input can be given. Example 1:input( ) with prompt string >>>city=input (“Enter Your City: ”) Enter Your City: Bengaluru >>>print (“I am from “, city) Output: I am from Bengaluru 34
  • 35. Example: >>>x = 5 >>>y = 6 >>>z = x + y >>>print (z) 11 >>> print (“The sum = ”, z) The sum = 11 >>> print (“The sum of ”, x, “ and ”, y, “ is ”, z) Output: The sum of 5 and 6 is 11 35 The print() function In Python, the print() function is used to display result on the screen. The syntax for print() print (“string to be displayed as output ” ) print (variable ) print (“String to be displayed as output ”, variable) print (“String1 ”, variable, “String 2”, variable, “String 3” ……) Note: In Python, single line comments start with # symbol. For multiline/block comment, Start wth three double quotes (“””) and end with the same after the block (“””)
  • 36. 36 """" formatted output using print""" a, b, c= 10, 20, 30 print (a) print (b) print (c) print (a, b, c) print (a, b, c, sep='-') print ("n") print ("a=" , a, "b=", b, "c=", c) print (' the value of a, b, c is :', a, b, c) print (a, 2*a, 3*a, 4*a, sep='-') print ("%d %d %d " %(a,b,c)) print ("value of a = %d, value of b= %d, value of c = %d " %(a, b, c)) print() print ("value of a = {}, value of b={}, value of c={}".format(a,b,c)) print() print ("value of a={2}, value of b={1}, value of c={0}".format (a,b,c)) print () print (f"value of a={a}, b={b} and c={c}") print() print (f"value of a={c}, b={a} and c ={a}") print ()
  • 37. • At this point, the syntax error you are most likely to make is an illegal variable name. • If you put a space in a variable name, Python thinks it is two operands without an operator: >>> bad name = 5 SyntaxError: invalid syntax >>> month = 09 File "<stdin>", line 1 month = 09 • SyntaxError: invalid token • For syntax errors, the error messages don’t help much. The most common messages are Syntax Error: invalid syntax and Syntax Error: invalid token, neither of which is very informative. 37
  • 38. Why is it worth the trouble to divide a program into functions??? There are several reasons: • Creating a new function gives an opportunity to name a group of statements, which makes your program easier to read, understand, and debug. • Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place. • Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a complete unit. • Well-designed functions are very useful. Once you write and debug one, you can reuse it. • Functions provide a “structure” to a complex program/program having hundreds of lines of code. Its easier to break the program into constituent functions or modules for better understanding, editing, debugging, testing and so on. 38
  • 39. • Some of the functions we are using, such as the math functions, yield results; they are called fruitful functions. Other functions, perform an action but don’t return a value. They are called void functions. • When you call a fruitful function, you almost always want to do something with the result; for example, x= math.cos(radians) When you call a function in interactive mode result: >>> math.sqrt(5) 2.23606797749979 ❑Void functions might display something on the screen or have some other effect, but they don’t have a return value. If you try to assign the result to a variable, you get a special value called None. Ex: print (“welcome to Python”) 39
  • 40. 1.To check whether a person is eligible to vote in the election. Accept appropriate input and display message accordingly age=int(input(" enter age:")) if(age>=18): print("eligible for voting") else: print("not eligible for voting") output: enter age:24 eligible for voting enter age:14 not eligible for voting 40
  • 41. 2.To find sum of natural numbers num = 16 if num < 0: print("Enter a positive number") else: sum = 0 print("The sum is", sum) output: The sum is 136 3.To find area of a circle import math r=int(input("enter the radius:")) area=r*pi*pi print("the area of circle is ",area) output: enter the radius:4 the area of circle is 50.24 41
  • 42. 4.Program to Check if a Number is Odd or Even num = int(input("Enter a number: ")) if (num % 2) == 0: print("{0} is Even number". Format(num)) else: print("{0} is Odd number". Format(num)) output: 15 is the odd number 16 is the even number 42 5.Program to Check Prime Number num = int(input("Enter a number: ")) if num > 1: for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") else: print(num,"is not a prime number") output: Enter a number:313 313 is a prime number
  • 43. 5.Program to Find the Factorial of a Number num = int(input("Enter a number: ")) factorial = 1 if num < 0: print("Sorry, factorial does not exist for negative nu mbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) output: Enter a number:5 the factorial of 5 is 120 43 6.Test whether a passed letter is a vowel or not def is_vowel(char): all_vowels = 'aeiou’ return char in all_vowels print(is_vowel('c’)) print(is_vowel('e’)) output: False True 7.Python Program to find ASCII Value of a Character ch = input(" enter any Character:") print("The ASCII Value of %c = %d" %(ch, ord(ch))) output: enter any Character : a The ASCII Value of a = 97
  • 44. 8.Program to Swap Two Numbers using a temporary variable a = float(input(" Enter the First Value a: ")) b = float(input(" Enter the Second Value b: ")) print("Before Swapping two Number: a = {0} and b = {1}".format(a, b)) temp = a a = b b = temp print("After Swapping two Number: a = {0} and b = {1}".format(a, b)) output: Enter the First Value a: 10 Enter the Second Value b: 20 Before Swapping two Number: a = 10.0 and b = 20.0 After Swapping two Number: a = 20.0 and b = 10.0 44
  • 45. 9.Program to Check Leap Year using if Statement year = int(input("Enter the Year Number : ")) if (((year%400==0)) or (( year%4 == 0 ) and ( year%100 != 0))): print("%d is a Leap Year" %year) else: print("%d is Not the Leap Year" %year) output: Enter the Year Number you wish: 1200 1200 is a Leap Year 45
  • 46. 10.Program to find GCD/HCF of Two Numbers a = float(input(" Enter the First Value a: ")) b = float(input(" Enter the Second Value b: ")) i = 1 while(i <= a and i <= b): if(a % i == 0 and b % i == 0): gcd = i i = i + 1 print("n HCF of {0} and {1} = {2}".format(a, b, gcd)) output: Enter the First Value a: 8 Enter the Second Value b: 12 HCF of 8.0 and 12.0 = 4 46
  • 47. 11. Program to Calculate Electricity Bill ( nested if-else) units = int(input(" enter Number of Units you Consumed : ")) if units < 50: amount = units * 2.60 surcharge = 25 elif units <= 100: amount = 130 + ((units - 50) * 3.25) surcharge = 35 elif units <= 200: amount = 130 + 162.50 + ((units - 100) * 5.26) surcharge = 45 else: amount = 130 + 162.50 + 526 + ((units - 200) * 8.45) surcharge = 75 total = amount + surcharge print("nElectricity Bill = %.2f" %total) output: enter Number of Units you Consumed :75 Electricity Bill =246.25 47