0% found this document useful (0 votes)
172 views

Ln. 3 - Brief Overview of Python

The document provides an overview of the Python programming language. It discusses that Python was created in 1991 and is used for web applications, software development, mathematics, game development, and database applications. It then lists some advantages of Python like being cross-platform, having a simple syntax, and being easy to debug. Limitations include not being as fast as other languages and not catching type mismatches. The document describes how to download and install Python and work in both interactive and script modes. It also covers basic Python concepts like variables, data types, strings, numbers, comments, and functions.

Uploaded by

Abel Varughese
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
172 views

Ln. 3 - Brief Overview of Python

The document provides an overview of the Python programming language. It discusses that Python was created in 1991 and is used for web applications, software development, mathematics, game development, and database applications. It then lists some advantages of Python like being cross-platform, having a simple syntax, and being easy to debug. Limitations include not being as fast as other languages and not catching type mismatches. The document describes how to download and install Python and work in both interactive and script modes. It also covers basic Python concepts like variables, data types, strings, numbers, comments, and functions.

Uploaded by

Abel Varughese
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

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

How to download Python?


✓ Python can be downloaded from www.python.org
✓ It is available in two versions- Python 2.x and Python 3.x
✓ Open www.python.org on any browser.
✓ IDLE is Python’s Integrated Development and Learning Environment.
✓ After installation, open Python IDLE 3.6.5, and a window will be opened which will look like-

How to work in Python?


• We can work in Python in two ways- Interactive Mode , Script Mode
• To work in both of these , you need to open Python IDLE.

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.

To work in a script mode, you have to do the following-


Step 1 : Create module/ script / program file
Click File → New in the IDLE python shell. A new window pops up.
Type the commands.
Click File → Save with an extension .py
Step 2 : Run module/ script / program file
Open the file created. File → Open
Run → Run module command or F5
Commands are executed and the o/p is seen in the interactive 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.

Rules to follow for naming Identifiers :


May be combination of letters and numbers.
Must begin with an alphabet or an underscore( _ ).
It is case sensitive.
Length of an Identifier is unlimited.
Keywords can not be used as an identifier.
Space and special symbols are not permitted in an identifier name except an underscore( _ ) sign.
Eg: Myfile, Date9_7_17, Z2T0Z9, _DS, _CHK FILE13.
Some invald identifiers are – DATA-REC, 29COLOR, break, My.File.

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

A Python Program Structure


A python program contains various components like- Expressions , Comments , Blocks and
indentation , Statements , Function
a. Expression: -which is evaluated and produce result. E.g. (20 + 4) / 4
b. Statement:-instruction that does something.
Eg:- a = 20
c. Comments: which is readable for programmer but ignored by python interpreter
i.Single line comment: Which begins with # sign.
ii.Multi line comment (docstring): either write multiple line beginning with # sign or use triple
quoted multiple line. E.g.
‘’’this is my first
python multiline comment
‘’’
d.Function
a code that has some name and it can be reused.
e. Block & indentation: group of statements is block. Indentation at same level create a block.

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

Variable Naming Rules


It can begin with the underscore "_" or a letter.
The rest of the characters can be a letter, number or any other characters.
Keywords cannot be used.

Examples of Multiple Assignments:


a=b=c=125
a, b, c = 1, 2, “john”
x,y = y,x
print (x,y)
a, b, c = 10, 20, 30
Which means, a= 10 b=20 c=30
Program 1 : # Get the values of two numbers in 2 variables , Swap the values , Display the results
x=100
y=200
x,y=y,x
x,y
O/p→ (200, 100)

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)

Program: 3 (using –Input statement)


eng = int(input("Enter English Mark:"))
mat = int(input(" Enter Math Mark:"))
sci = int(input (" Enter Science Mark: "))
sst = int(input(" Enter Social Studies Mark:"))
seclan = int(input (" Enter Sec. Lang Mark:"))
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

Numbers To hold only numeric values 1000


String Consists of a set of characters. Dave

Boolean The two data values are TRUE and FALSE, TRUE
represented by 1 or 0.

List An ordered sequence of items. Mutable. [1, 2.2, 'python']

Tuple An ordered sequence of items same as list. The only (5,'program',


difference is that tuples are immutable. Tuples once 1+3j)
created cannot be modified.

Set An unordered collection of unique items. {1,2,2,3,3,3}

Dictionary An unordered collection of key-value pairs. {1:'value','key':2}

String Data Types


• String is a group of characters.
• These characters may be alphabets, digits or special characters including spaces.
• String values are enclosed either in single quotation marks (for example ‘Hello’) or in double
quotation marks (for example “Hello”).
• We cannot perform numerical operations on strings, even when the string contains a numeric
value.
>>> str1 = 'Hello Friend'
>>> str2 = "452"
• String is of 2 types- Single line string , Multi line string

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)

Boolean Data Types


• It is a unique data type, consisting of two constants, True and False.
• The equality operator = = compares 2 values and produces a boolean value related to whether the
2 values are equal to one another.
Eg:- print(5= = 5) O/P à True
print(5= = 6) O/P à False
• The bool ( ) method will return or convert a value to a boolean value.
• Syntax, bool( [x])
Eg:- x= True
bool(x) O/P à True
• If no parameter is passed then by default it returns False.

List & Tuples


• A list in Python represents a list of comma-separated values of any datatype between square
brackets. Eg:- colors=['red','blue','green']
• Lists can be changed /modified
• A tuple is a collection of values, and we declare it using parentheses.
• Eg:- numbers=(1,2,'three')
• Tuple cannot be changed.

Set & Dictionary


• Set is an unordered collection of unique items that cannot be changed.
• e.g. set1={11,22,33,22}
• print(set1)
• Output {33, 11, 22}
• The dictionary is an unordered set of comma-separated key: value pairs, within { }
• e.g. name = {'Navneet': 35, 'Gaurav': 42,‘Sunit’: 36, ‘Vikas’:40}
print(name)

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)

Program - Find the area of a triangle-


s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))
a=5b=6c=7
a = float(input('Enter first side: ‘))
b = float(input('Enter second side: ‘))
c = float(input('Enter third side: ‘))
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

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.

/ - Divide left operand by the right one and returns quotient.


% - Modulus - Divides left hand operand by right hand operand and returns remainder
// - Floor division Divide left operand by the right one and returns quotient without the
decimal value.
** - Exponent – returns the result of a number raised to the power.

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.

Add and Assign(+=)


Adds the values on either side and assigns it to the expression on the left.
a+=10 is the same as a=a+10.
The same goes for all the next assignment operators.
Subtract and Assign(-=) Divide and Assign(/=)
Multiply and Assign(*=) Modulus and Assign(%=)
Exponent and Assign(**=) Floor-Divide and Assign(//=)

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

# Python Program to find Volume & Surface Area of a Cylinder


PI = 3.14
radius = float(input('Please Enter the Radius of a Cylinder: '))
height = float(input('Please Enter the Height of a Cylinder: '))
sa = 2 * PI * radius * (radius + height)
Volume = PI * radius * radius * height
print("\n The Surface area of a Cylinder = " sa)
print(" The Volume of a Cylinder = " Volume)

Mutable & Immutable Types


• An object’s mutability is determined by its type.
• The value of some objects can change.
• Objects whose value can change are said to be mutable; list, set, dict) are mutable.
• Objects whose value will not change are said to be immutable. Eg:- int, float, bool, str, tuple
• When an object is initiated, it is assigned a unique object id.
• Mutability means that in the same memory address, new values can be stored as and when you
want.

end parameter in print( )


• To print in one line use, [Use script mode]
PRINT ( “Hello World”, end=“”)
PRINT ( “This is me ”) Output => Hello WorldThis is me
Or
PRINT ( “Hello World”, end=“ , ”)
PRINT ( “This is me ”) Output => Hello World , This is me
Note: The end=' ' is just to say that you want a space after the end of the statement instead of a new
line character.

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.

Accessing String Elements OUTPUT-


str='Computer Science'
print('str -', str) str - Computer Science
print('str[0] -', str[0]) str[0] - C
print('str[1:4] -', str[1:4]) str[1:4] - omp
print('str[2:] -', str[2:]) str[2:] - mputer Science
print('str *2 -', str *2 )
str *2 - Computer ScienceComputer Science
print("str +'yes' -", str +'yes')
str +' yes' - Computer Science yes

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)

Ordinal value / Unicode value of a character


ord() function: It gives ASCII value of a single character.
chr() function: It takes the ordinal value in integer form and returns the character corresponding to
that ordinal value.
ord ("a") : 97 chr(97) : “a"
Ord (“A”) : 65 chr(90) : “Z"
ord ("Z") : 90 chr(48) : “0”
ord("0") : 48 chr(65) : “A”

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

Program – [To print the reverse of a string – PALINDROME ]


a=str(input("Enter a string: "))
print("Reverse of the string is: ")
print(a[ : :-1])
Enter a string: WELCOME
Reverse of the string is: EMOCLEW

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

String Functions and methods


1. str.capitalize() To capitalize the first character in the string
>>> 'true'.capitalize() 'True’
>>> 'i love my india'.capitalize() 'I love my india'

2. string.find(subString [,start [,end]):


It returns the lowest index in the string where the subString is found with in the slice range of start
& end, returns -1 if subString is not found.
e.g. t="We are learning Strings. Strings are used in Python"
k="Strings"
t.find(k) gives : 16 (index no.)
t.find(k,20) gives : 25 (index no.)
t.find(“Hello”) gives : -1 ( as string is not found)

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

17. len(string): This function gives the length of given string.


len(“Top Brand”) gives 9

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)

Logical errors / Semantic error


• Errors that occur due to the mistake on the part of the user are called logical errors.
• You won't get an error message, because no syntax or runtime error has occurred.
• These are the most difficult errors to find and debug.
• It does not stop execution but the program behaves incorrectly and produces undesired /wrong
output.
Ex :
Typing a +b + c / 3
instead of (a + b+ c) /3

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 Logic Development Tool


A program has following development stages-
✓ Identification of the problem
✓ Analysis of problem
✓ Writing Algorithm or Designing Flowchart
✓ Writing Code
✓ Testing and Debugging
✓ Implementation
✓ Maintenance

Working with math Module


• It is a standard module in Python.
• To use mathematical functions of this module, we have to import the module using import math.
Function Description Example
ceil(n) It returns the smallest integer greater math.ceil(4.2) returns 5
than or equal to n.
floor(n) It returns the largest integer less than or math.floor(4.2) returns 4
equal to n
sqrt(n) It returns the square root of n math.sqrt(100) returns 10.0
exp(n) It returns e**n math.exp(1) return
2.718281828459045
fabs Returns the absolute value math.fabs(1.0) → 1.0
Math.fabs(-1.0) → 1.0
log10(n) It returns the base-10 logarithm of n math.log10(4) returns
0.6020599913279624
pow(n, y) It returns n raised to the power y math.pow(2,3) returns 8.0
Function Description Example
factorial(n) It returns the factorial of value n math.factorial(4) returns 24
fmod(x, y) It returns the remainder when n is math.fmod(10.5,2) returns
divided by y 0.5
log2(n) It returns the base-2 logarithm of n math.log2(4) return 2.0
cos(n) It returns the cosine of n math.cos(100) returns
0.8623188722876839
sin(n) It returns the sine of n math.sin(100) returns -
0.5063656411097588
tan(n) It returns the tangent of n math.tan(100) returns -
0.5872139151569291
pi It is pi value (3.14159...) It is (3.14159...)
e It is mathematical constant e It is (2.71828...)
(2.71828...)
Programs

Program 1-

Program 2- Using arithmetic operators


num1 = float(input(" Please Enter the First Value Number 1: "))
num2 = float(input(" Please Enter the Second Value Number 2: "))
add = num1 + num2
sub = num1 - num2
mul = num1 * num2
div = num1 / num2
floor_div = num1 // num2
mod = num1 % num2
expo = num1 ** num2
print('Sum of ', num1 ,'and' ,num2 ,'is :', add)
print('Difference of ',num1 ,'and' ,num2 ,'is :',sub)
print('Product of' ,num1 ,'and' ,num2 ,'is :',mul)
print('Division of ',num1 ,'and' ,num2 ,'is :',div)
print('Floor Division of ',num1 ,'and' ,num2 ,'is :',floor_div)
print('Exponent of ',num1 ,'and' ,num2 ,'is :',expo)
print('Modulus of ',num1 ,'and' ,num2 ,'is :',mod)

Program 3 - Compound interest - Compound Interest = P (1 + r/100) n


p = float(input(" Please Enter the Principal Amount : "))
r = float(input(" Please Enter the Rate Of Interest : "))
n = float(input(" Please Enter number of times : "))
ci = p * ((1 + (r/100) ** n
print("Compound Interest = “, ci)

Program 4 - Temp conversion


Fahrenheit = int(input("Enter a temperature in Fahrenheit: "))
Celsius = (Fahrenheit - 32) * 5.0/9.0
print ("Temperature:", Fahrenheit, "Fahrenheit = ", Celsius, " C" )

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.

Common Flowchart Symbols


Process
Start/End Symbol

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

The if-else statement


The if - else statement tests a condition and in case the condition is True, it carries out statements
indented below if and in case the condition is False, it carries out statement below else.
Syntax
if <condition> :
statement
else :
statement

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.

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


print(i)
Output- 5 4

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

1) range( 1 , 7): will produce 1, 2, 3, 4, 5, 6.


2) range( 1 , 9, 2): will produce 1, 3, 5, 7.
3) range( 5, 1, -1): will produce 5, 4, 3, 2.
4) range(5): will produce 0,1,2,3,4. Default start value is 0

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)

For loop with string


2 methods of using for loop with strings- OUTPUT-
• for ch in “Hello” :
print(ch) H
e
• T = “Hello” l
for ch in T :
l
print(ch)
o
Both produces the same output.

Program - Accept a number and check if it is positive, negative or zero.


num= float(input("Enter a number: "))
if num>= 0:
if num== 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Program - Find the largest of 3 numbers.


X = int (input(“Enter Num1 : ” ))
Y = int (input(“Enter Num2 : ” ))
Z = int (input(“Enter Num3 : ” ))
if X >= Y and X >= Z:
Largest = X
elif Y>=X and Y>=Z:
Largest = Y
else:
Largest = Z
print(“Largest Number :”, Largest)
while loop
• It is used to execute a block of statement as long as a given condition is true.
• The control comes out of the loop when the condition is false.
• The condition is checked every time at the beginning of the loop.
• Syntax-
while (condition) :
statement
Eg:-
x=1
while ( x <= 4) :
print (x)
x = x+1

Program- sum of series Output:


k=1 1
sum=0 2
while k<= 5 : 3
sum=sum+k 4
k=k+1 Sum of series: 10
print("Sum of series:", sum)

TIP: To cancel the running of an endless loop, use CTRL + C


Find the output :
number =1
while number < 5:
print(number * number)
number = number + 1
Output:
1
4
9
16

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)

Program 2- Prog to find if a number is even or odd


num = int(input("Enter a number: "))
if (num % 2) == 0:
print("Even number”)
else:
print(“Odd number”)

Program 3- Ticket eligibility


age = 38
if (age >= 11):
print ("You are eligible to see the Football match.")
if (age <= 20 or age >= 60):
print("Ticket price is $12")
else:
print("Ticket price is $20")
else:
print ("You're not eligible to buy a ticket.")

Program 4 – Arithmetic operations


num1 = input (“Please enter a number”)
num2 = input (“Please enter a second number”)
op = input (“Select an operation: 1. Add 2. Subtract 3. Multiply”)
if op == 1:
add = num1 + num2
print add
elif op == 2:
sub = num1 – num2
print sub
elif op == 3:
mul = num1*num2
print mul

Program 5 - Sum of Series


Sum=0
for i in range(1, 11):
print(i)
Sum=Sum + i
print(“Sum of Series”, Sum)
Output:
1 2 3 4 5 6 7 8 9 10
Sum of Series 55

Program 6 – Multiplication Table


num=5
for a in range (1,11) :
print(num, ‘x’ , a, ‘=‘, num * a

Output:
5x1=5 5 x 2 = 10 ………………………………….. 5 x 9 = 45 5 x 10 = 50

Program 10 - To find sum of the digits


num = int(input(“Enter the number :”))
ds = 0
while num>0 :
ds = ds +num % 10
num = num // 10
print(“Digit Sum :”, ds)

You might also like