Ln. 3 - Brief Overview of Python
Ln. 3 - Brief Overview of Python
Introduction-
Python is a popular high level programming language.
It was created in 1991 by Guido van Rossum.
It is used for: Web applications , software development , mathematics , Game development ,
Database applications , System Administrators
Advantages of Python-
• Python works on different platforms (Windows, Mac, Linux, etc).
• Python has a simple syntax and is easy to learn it.
• It is possible to get desired output in minimum instructions.
• Python is an interpreted language. This means that Python interprets and executes the code
line by line.
• It is an easy to debug language and is suitable for beginners and advanced users.
• It is a platform independent and portable language.
• It is easy to download and install.
Limitations of Python-
• It is not a fast language.
• Libraries are very less.
• It is not easy to convert it to some other language.
• Not strong on ‘Type Binding’ ie.. It does not catch type mismatch issues.
• It is case sensitive.
Interactive mode-
• It works like a Command Interpreter or as a Shell Prompt.
• Here we can type the command – one at a time and then Python executes it then and there.
• The command has to be typed after the command prompt ( >>>).
• Click Start → Programs→ Python 3.6 x→ IDLE (Python GUI)
• It opens up the Python shell where you can type the commands.
Script mode:
• Here we can save the commands entered by the user in the form of a program.
• We can run a complete program by writing in Script mode.
PRINT command:
The Python print statement is used to print or display results.
Syntax:
print (“string”)
Eg: print("Hello, World!")
The string can be in double or single quotes.
COMMENTS:
Comments are used to add a remark or a note in the source code.
Comments are not executed by the interpreter.
They are added with the purpose of making the source code easier for humans to understand.
In Python, a single line comment starts with # (hash sign).
Everything following the # till the end of that line is treated as a comment and the interpreter
simply ignores it while executing the statement.
Eg:
#This is a comment.
print("Hello, World!")
Keywords :
Keywords are reserved words that has a specific meaning to the Python interpreter.
Cannot be used as identifiers, variable name or any other purpose.
Eg: False, class, None, True, and, as, break, if, in try, with, is etc.
Identifiers :
• Identifiers are names used to identify a variable, function, or other entities in a program.
Input Function :
• The input() function allows user input.
Syntax: input()
Note:
The input( ) always returns a value of String type.
When the output is displayed it encloses the values within quotes.
Try to perform some operation on the command.
Eg: age + 1
An error occurs as an integer cannot be added to a string.
sep argument
• The sep argument specifies the separator character.
• If no value is given for sep, then by default, print( ) will add a space in between items when
printing.
Example:
Print(“Hi”,”My”,”name”,”is”,”Jeny”)
This gives the output
My name is Jeny
Here since sep character is a space, here the words will have spaces between them.
print("My","name","is",“Jeny",sep='...')
The output is-
My...name...is...Jeny
My.*.*.*.*.*name.*.*.*.*.*is.*.*.*.*.*Jeny
Variables
Variables are reserved memory locations to store values.
A variable is like a box that can be used to store a piece of information.
We give each box (a variable) a name, so we can use the data stored with it when needed. We can
put different types of data into a box.
This value can be accessed or changed when needed.
A program can have as many variables as we want or need.
To create a variable, you just assign it a value and then start using it.
Assignment is done with a single equals sign (=)
Eg:-
gender = 'M'
message = "Keep Smiling"
price = 987.9
Program 2 :
Write a Python program to find the area of a rectangle given that its length is 10 units and breadth is
20 units.
#To find the area of a rectangle
length = 10
breadth = 20
area = length * breadth
print(area)
Program 3 :
# Get the marks of 5 subjects , Calculate the sum & average , Display the results
# Get five subject marks
eng = 56
mat = 59
sci = 64
sst = 78
seclan = 89
average = (eng+mat+sci+sst+seclan) / 5
print ("the average score is: ", average)
id( ) Function
• The id () function is the object's memory address.
• It returns a unique id for the specified object.
• All objects in Python has its own unique id.
• The id is assigned to the object when it is created.
Examples
n = 300
print (n)
O/p: 300
print (id(n))
O/p : 157379912
Data Types
» Data Type specifies which type of value a variable can store.
» Python has a predefined set of data types to handle the data in a program.
» type() function is used to find a variable's type in Python.
Data Type Definition Example
Boolean The two data values are TRUE and FALSE, TRUE
represented by 1 or 0.
Numbers
• It is used to store numeric values
• Python has three numeric types: Integers, floating point, complex
int : This type is used to store positive or negative numbers with no decimal points.
Example: a = 10 b = 20
Ø float : If we want to take decimal points also than we go with the float data type.
Example: a = 10.5 b = 5.3
Ø complex : Complex data types are used to store real and imaginary values.
Example: a = x+yj Where x is called real part and y is called imaginary part.
a = 5+10j
Type Conversion
Type Conversion of Integer: Output :-
int() function converts any data type to integer.
e.g. a = "101“ # string 101
b=int(a) # converts string data type to integer. 122
c=int(122.4) # converts float data type to integer.
print(b)
print(c)
Type Conversion of Floating point:
float() function converts any data type to floating point number.
e.g. a='301.4‘ #string Output :-
b=float(a) #converts string to floating point. 301.4
c=float(121) #converts integer to floating point
121.0
print(b)
print(c)
type () function
• type() function is used to find a variable's type in Python.
>>> quantity = 10
>>> type(quantity)
<class 'int'>
>>> Price = -1921.9
>>> type(price)
<class 'float'>
Type Error:
When you try to perform an operation on a data type which is not suitable for it, then Python raises an
error called Type Error.
Note:
• Function int ( ) around input( ) converts the read value into int type.
• Function float ( ) around input( ) converts the read value into float type.
• You can check the type of read value by using the type ( ) function after the input ( ) is
executed.
>>> type(age_new)
<class 'int'>
Program to find SI
principle=float(input("Enter the principle amount:"))
time=int(input("Enter the time(years):"))
rate=float(input("Enter the rate:"))
simple_interest=(principle*time*rate)/100
print("The simple interest is: ",simple_interest)
Operators
Operators are special symbols in Python that carry out operations on variables and values.
The value that the operator operates on is called the operand.
Types of operators are - Arithmetic operators , Assignment operators , Comparison operators ,
Logical operators , Membership operators
Arithmetic operators-
Arithmetic operators are used with numeric values to perform common mathematical
operations.
Operator Precedence
• In Python, as in mathematics, we need to keep in mind that operators will be evaluated in
order of precedence, not from left to right or right to left.
Assignment Operators
Assignment operators are used to assign values to the variables.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on
the left.
Assign(=)
Assigns a value to the expression on the left.
Note:
= = is used for comparing, but = is used for assigning.
Relational Operators
Relational operators compares the values.
It either returns True or False according to the condition.
It works with nearly all types of data like numbers, list, string etc.
While comparing these points are to be kept in mind-
• For numeric types, the values are compared after removing the zeroes after decimal point from a
floating point number. So 3.0 and 3 are equal.
• In strings, capital letters are lesser than small letters.
• For eg:- ‘A’ is less than ‘a’ because ASCII value of A=65 and a=97.
Note:
To get the ASCII code of a character, use the ord() function.
>>> ord('a') 97
>>> ord('.') 46
Logical Operators
Logical operators refer to the ways in which the relations among values can be connected.
x = True
y = False Output
print('x and y is',x and y) ('x and y is', False)
print('x or y is',x or y) ('x or y is', True)
print('not x is',not x) ('not x is', False)
x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10
Membership Operators
Membership operators in Python are used to test whether a value is found within a sequence such as
strings, lists, or tuples.
Operator Description
in Evaluates to true if it finds a variable in the specified sequence
and false otherwise.
not in Evaluates to true if it does not finds a variable in the specified
sequence and false otherwise.
Example-
>>> 'Hello' in 'Hello world!' True
>>> 'house' in 'Hello world!' False
>>> 'car' not in 'Hello world!' True
>>> 'house' not in 'Hello world!' True
haystack = "The quick brown fox jumps over the lazy dog."
needle = "fox"
result = needle in haystack
print("result:", result) O/p - True
Operator Precedence
Highest precedence to lowest precedence table
Operator Description
() Parentheses
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'td>
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= Assignment operators
+= *= **=
is , is not Identity operators
In, not in Membership operators
not or and Logical operators
Strings
❑ The string type in Python is represented by str.
❑ A sequence of characters enclosed in single quotes, double quotes or triple quotes (‘ ‘ , “ “, ‘’’ ‘’’) is
called a string.
❑ In a String, each character remains at a unique position number or index number which goes from
0 to n-1 (n is the total number of characters in the string).
❑ An empty string is a string that has 0 characters.
CREATING A STRING
Strings can be created in the following ways-
1. By assigning the value directly to the variable
str = “I love my India”
print (str)
Output- I love my India
2. By taking input-
str1 =input(“Enter a string - ”)
print(str1)
Output – Enter a string - I love my school
I love my school
Index
❑ The characters in a string can be accessed using its index.
❑ The Characters are given in two-way indices:
❑ 0 , 1 , 2 , …… in the forward direction
❑ -1 , -2 , -3 ,…… in the backward direction.
TRAVERSING A STRING
Traversing means iterating through the elements of a string one character at a time.
We can traverse a string character by character using the index.
name = “superb”
for ch in name:
print(ch , “-”, end=“ “)
Program OUTPUT-
str= "SCHOOL"
for i in str: S
print(i) C
H
O
String Operators O
Concatenation operator + L
Replication operator *
Membership operators in , not in
Comparison operators < <= > >= == !=
Concatenation Operator
The + operator creates a new string by joining the 2 operand strings.
Eg:- “tea” + “pot” Output - teapot
“1” + “1” Output - 11
“123” + “abc” Output - 123abc
“a” + “0” Output - a0
Note: The statement “2” + 3 will give an error because we cannot combine numbers and strings
Replication Operator
This operator when used with a string replicates same string multiple times.
e.g. "XY" * 3 will give: "XYXYXY"
"3" * 4 will give: "3333“
"5" * "7" is invalid
5* ”@” will give “@@@@@”
“go!” * 3 will give“go!go!go!”
Note: operands must be one string & other Number
Membership Operator
• in – Returns true if a character or a substring exists in the given string and false otherwise.
• not in - Returns true if a character or a substring doesn’t exist in the given string and false
otherwise.
Note: Both the operands must be strings.
“a” in “Sanjeev” will result into True.
“ap” in “Sanjeev” will result into False.
“anj” not in “Sanjeev” will result into False.
Comparison Operators
Python’s comparison operators are –
< <= > >= == !=
“a” == “a” True
“abc”==“abc” True
“a”!=“abc” True
“A”==“a” False
‘a’<‘A’ False (because Unicode value of lower case is higher than upper case)
String slices
It is a part of a string where strings are sliced using a range of indices.
Let word=“WelCome”
word [0:7] will give : WelCome
word [0:3] will give : Wel
word [-6:-3] will give : elC
word [ :5] will give : WelCo
word [3: ] will give : Come
word='amazing'
>>> word[1:6:2] → 'mzn'
>>> word[-7:-3:3] → 'az'
>>> word[ : :-2] → 'giaa'
s="Hello"
>>> print(s[5]) → Out of range error
Note:
• For any index n, s[:n] + s[n:] will give the original string s.
• String [ : : -1] is an easy way to reverse a string using string slice mechanism.
Eg:-
s="AMAZING"
print(s[:3]+s[3:])
O/p - AMAZING
OUTPUT-
Program – To print pattern
string="#" #
pattern="" ##
for a in range(5): ###
pattern+=string ####
print(pattern) #####
3. str.isalnum() Returns True if the characters in the string are alphanumeric [has only numbers
or alphabets but no symbols]
e.g. t ="Hello123” t.isalnum() gives True
t ="Hello 123” t.isalnum() gives False
4. str.isalpha() Returns True if the characters in the string are only alphabets, False otherwise.
e.g. t ="Hello123” t.isalnum() gives False
t = "Hello” t.isalnum() gives True
5. string.isdigit(): Returns True if the characters in the string are only digits, False otherwise.
t ="Hello123“ t.isalnum() gives False
t= "123” t.isalnum() gives True
6. string.islower(): Returns True, if all letters in given string are in lowercase, otherwise it gives
False.
t="sunday" t.islower() gives True
t="Sunday" t.islower() gives False
7. string.isupper(): Returns True, if all letters in given string are in uppercase, otherwise it gives
False.
t=“WELCOME" t.isupper() gives True
t="SU123" t.isupper() gives True
8. string.lower(): Returns the string with all the characters converted to Lowercase.
t=“SUNDAY" t.lower() gives Sunday
9. string.upper(): Returns the string with all the characters converted to uppercase.
t=“sunday" t.upper() gives SUNDAY
10. string.isspace(): Returns True if there are only whitespace characters in the string, False
otherwise.
t=" " t.isspace() gives True
t=" S" t.isspace() gives False
t="" t.isspace() gives False
11. Str.istitle() - Checks if each word starts with an upper case letter:
txt = "Hello, And Welcome To My World!“ txt.istitle() → True
12. The center() method will center align the string, using a specified character (space is default) as
the fill character.
txt ="banana“ txt.center(20) → ' banana '
13. The count() method returns the number of times a specified value appears in the string.
txt = "I love apples, apple are my favorite fruit"
txt.count("apple") → 2
14. The join() method takes all items in an iterable and joins them into one string.
myTuple = ("John", "Peter", "Vicky")
"#".join(myTuple) → John#Peter#Vicky
15. The replace() method replaces a specified phrase with another specified phrase.
txt = "I like bananas"
txt.replace("bananas", "apples") → I like apples
16. The swapcase() method returns a string where all the upper case letters are lower case and vice
versa.
txt = "Hello My Name Is PETER"
txt.swapcase() → hELLO mY nAME iS peter
18. The lstrip() method removes any leading characters (characters at the beginning of a string), space
is the default leading character to remove.
txt="I love india"
txt.lstrip("Ilo") → ' love india'
txt.lstrip("I lo") → 've india‘
19. The rstrip() method removes any trailing characters (characters at the end a string), space is the
default trailing character to remove.
txt = " mango “
txt.rstrip() → " mango”
txt2 = "banana,,,,,ssaaww....."
txt2.rstrip(",.asw") → 'banan'
Debugging
• The process of identifying and removing logical errors and runtime errors is called debugging.
• We need to debug a program so that is can run successfully and generate the desired output.
• Due to errors, a program may not execute or may generate wrong output.
❖ Syntax errors
❖ Logical errors
❖ Runtime errors
Syntax errors
• The formal set of rules defined for writing any statement in a language is known as syntax.
• When the syntax rules of a programming language are violated, syntax errors will arise.
• Syntax errors are the most basic type of error.
• If any syntax error is present, the interpreter shows error message(s) and stops the execution
there.
• Such errors need to be removed before execution of the program.
Examples:
missing parenthesis,
incompatible data types
print "hello world
a = 3 + ‘5 7’
Runtime errors
• A runtime error causes abnormal termination of program while it is executing.
• Runtime error occurs when the statement is correct syntactically, but the interpreter can not
execute it.
• Also called exceptions because they usually indicate that something exceptional (and bad) has
happened.
• A syntax error happens when Python can't understand what you are saying. A run-time error
happens when Python understands what you are saying, but runs into trouble when following your
instructions.
Eg:-
• division by zero
• print(greeting)
Function
• A function refers to a set of statements or instructions grouped under a name that perform
specified tasks.
• For repeated or routine tasks, we define a function.
• A function is defined once and can be reused at multiple places in a program by simply writing the
function name, i.e., by calling that function.
Built in Function
• Python has many predefined functions called built-in functions.
• Eg:- print() and input().
• Use of built-in functions makes programming faster and efficient.
• A module is a python file in which multiple functions are grouped together.
• These functions can be easily used in a Python program by importing the module using import
command.
• To use a built-in function we must know the following about that function:
• Function Name.
• Arguments
• Return Value
#Calculate square of a number
num = int(input("Enter the first number"))
square = num * num
print("the square of", num, " is ", square)
Program 1-
Algorithm
A process or set of rules to be followed in problem-solving operations is an algorithm.
Algorithm 1- To buy something from a grocery store:
Step 1- Go to the grocery store
Step 2- Find the product
Step 3 -Add to cart
Step 4 - Make payment
Algorithm to add two numbers is -
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Flowcharts
A flowchart is a graphical representation of an algorithm or process.
The flowchart shows the steps as boxes of various kinds, and their order by connecting the boxes
with arrows.
Sub process
Decision Symbol
Input/Output Symbol
FLOWCHART EXAMPLES-
To find simple interest To find if no. is even or odd
To find if pass or fail To find sum
Types of statements-
✓ Sequential statements
✓ Selection or Control statements
✓ Iteration or Looping statements
Sequential Statements
• Till now we were dealing with statements that only consisted of sequential execution, in which
statements are always performed one after the next, in exactly the order specified.
• These are sequential statements.
• But at times, a program needs to skip over some statements, execute a series of statements
repetitively, or choose between alternate sets of statements to execute.
• That is where control structures come in.
Control statements
❑ Control statements are used to control the flow of execution depending upon the specified
condition/logic.
❑ Also known as decision making statements.
The if statement is the conditional statement in Python. There are 3 forms of if statement:
1. Simple if statement
2. The if..else statement
3. The if..elif..else statement
If statements-
An if statement consists of a boolean expression followed by one or more statements.
The block of code in an if statement only executes code when the expression value is True.
It allows for conditional execution of a statement or group of statements based on the value of an
expression.
Simple if statement
The if statement tests a condition. If the condition is True, it carries out some instructions and does
nothing in case the condition is False.
Syntax
if <condition>:
statement
eg: -
if x >1000:
print(“x is more”)
e.g.
if amount>1000:
disc = amount * 0.10
else:
disc = amount * 0.05
if……elif…….else statement
An elif statement can be combined with an if statement.
It can check multiple expressions and executes a block of code as soon as one of the conditions
evaluates to True.
If the condition1 is True, it executes statements in block1, and in case the condition1 is False, it
moves to condition2, and in case the condition2 is True, executes statements in block2, so on.
In case none of the given conditions is true, then it executes the statements under else block
The else statement is optional and there can only be a maximum of one else statement following
an if.
Syntax is-
if <condition1> :
statement
elif <condition2> :
statement
elif <condition3> :
statement
………………………..
........………………….
else :
statement
Example:
mark = int(input("What mark did you get? "))
if mark > 60:
print("You got a distinction!")
elif mark > 50:
print("You received a merit")
elif mark > 40:
print("You passed")
else
print("Please try the test again")
Iteration statements
• Iteration statements (loop) are used to execute a block of statements as long as the condition is
true.
• Loops statements are used when we need to run same code again and again.
• Python Iteration(Loops) statements are of 2 types :-
1. While Loop – It is the conditional loop that repeats until a certain condition happens.
2. For Loop – It is the counting loop that repeats a certain number of times.
for loop
• It is used to iterate over items of any sequence, such as a list or a string.
• Syntax-
for variables in sequence:
statements
Eg:-
for i in [3,5,10]:
print(i)
print(i * i) Output- 3 9 5 25 10 100
Range function
The range() function generates a list. Its parameters are-
Start: Starting number of the sequence
Stop: Generates numbers upto this number, excluding it.
Step(optional) : Determines the increment between each number in the sequence.
range( 1 , n): will produce a list having values starting from 1,2,3… upto n-1. The default step size
is 1
range( 1 , n, 2): will produce a list having values starting from 1,3,5… upto n-1. The step size is 2
for loop
For x in range(5):
print(‘This is iteration number: ‘, x)
Output-
This is iteration number: 0
This is iteration number: 1
This is iteration number: 2
This is iteration number: 3
This is iteration number: 4
Program
Python Program to calculate the number of digits and letters in a string
s = input("Input a string")
d=let=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
let=let+1
else:
pass
print("Letters", l)
print("Digits", d)
Jump Statements
These statements are used to transfer the programs control from one location to another.
They alter the flow of a loop – like to skip part of a loop or terminate it.
3 types of jump statements used –Break , Continue, pass
Break Statements
It enables a program to skip over a part of a code.
It terminates the loop it lies within.
for i in range(10):
print(i)
if(i == 7):
print('break')
break
Continue Statements
Continue Statement in Python is used to skip all the remaining statements in the loop and move
controls back to the top of the loop.
The current iteration of the loop will be disrupted, but the program will return to the top of the
loop.
It causes a program to skip certain factors that come up within a loop, but then continue through
the rest of the loop.
for i in range(6):
if(i==3):
continue
print(i)
Output :-
0
1
2
4
5
Pass Statements
pass Statement in Python does nothing.
It makes a controller to pass by without executing any code.
The pass statement tells the program to disregard that condition and continue to run the program
as usual.
Eg:- for i in 'LastNightStudy':
if(i == 'i'):
pass
else:
print(i)
Output :-
L
a
s
t
N
g
h
t
S
t
u
d
y
Pass and continue
Continue forces the loop to start at the next iteration while pass means “ there is no code to execute
here” and will continue through the remainder of the loop body.
PROGRAMS
Program 1- To find discount (10%) if amount is more than 1000, otherwise (5%).
Price = float (input(“Enter Price ? ” ))
Qty = float (input(“Enter Qty ? ” ))
Amt = Price* Qty
print(“ Amount :” , Amt)
if Amt >1000 :
disc = Amt * .10
print(“Discount :”, disc)
else :
disc = Amt * .05
print(“Discount :”, disc)
Output:
5x1=5 5 x 2 = 10 ………………………………….. 5 x 9 = 45 5 x 10 = 50