0% found this document useful (0 votes)
3 views24 pages

Python Basics

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 24

Pseudocode

● Pseudocode is a way of representing an algorithm in readable and easy language.


● Pseudocode is not an actual program. So, it cannot be executed.
● Some of the frequently used keywords while writing pseudocode are INPUT, COMPUTE, PRINT
IF/ELSE, START, STOP

Advantages of Pseudo-Code:
1. Easily convertible to a Programming Language
2. Easy to understand and read

Write a pseudocode for identifying if a number is even or odd?


INPUT number A
COMPUTE remainder as r = A%2
IF r ==0 PRINT 'Even'
ELSE PRINT 'Odd'

Decomposition
Decomposition is the process of breaking a complex computer problem into smaller parts that are easily
manageable and solvable.

Familiarization with the basics of Python programming

Computer Program:
A computer program is a set of instructions that can be executed by the computer to perform and solve a
certain task. These programs are written in a special language known as Programming Language.

Computer Programming:
It is the process to create a computer program.

Python Programming Language:


Python is an interpreted, high-level programming language. It was developed by Guido van Rossum. It is
user-friendly and is most popular for its easy-to-use syntax and readable code.

Features of Python
● High-level Programming language.
● Interpreted language (as Python programs are executed by an interpreter)

52
● Easy to use
● Simple Syntax
● Python programs are generally written with fewer Lines of Code as compared to other
programming languages.
● Case-sensitive. For example, 'NUMBER' and 'number' are treated differently in Python.
● Portable programming language - has ability run programs on many computer architectures and
operating systems.

Syntax: Set of rules for framing a valid statement in a programming language.

Working in Python
● Install Python on the computer (https://www.python.org/downloads/). Refer Appendix for
installation instructions.
● Use Python IDLE (Integrated Development and Learning Environment) for developing python
Programs.

How to Display Data


print( ) function is used to print a message on the screen.

A Simple Hello World Program


print("Hello World")

Modes of working in Python


● Interactive Mode
● Script Mode

Interactive Mode
In Interactive Mode, a python statement is executed in a command-line shell. It provides instant feedback
for each statement while keeping prior statements in memory.

Script Mode
In script mode, the instructions are saved in a file with a '.py' extension and executed from the beginning of
the file. This mode is suitable for creating and running large programs. In script mode, all commands are
stored in the form of a program or a script.

Character Set:
A character set is a collection of valid characters that can be recognized by a language. Python Language
recognises the following characters as valid:

53
Letters : A-Z, a-z
Digits : 0-9
Special Symbol : + / @ ! - = <> == etc.
Whitespaces : '\n', '\t' etc.

Tokens
Tokens are the smallest individual units of a program.

Keywords
Keywords are reserved words with special meaning (known to the interpreter). These can not be used as
identifiers in a program.
Example: for, while, else, if

Identifier
A variable, function, class, module, or other objects are identified by a name known as identifier.
Rules for naming an identifier:
1. First character of a variable can be an alphabet(A-Z or a-z) or an underscore(_).
2. Next characters of a variable can be an alphabet(A-Z or a-z), an underscore(_) or a digit.
3. Keywords cannot be used as variables.
4. First character cannot be a digit.
5. Special characters including white spaces are not allowed.

Literals:
Literals are data-items that have a fixed value of a certain data type, such as a number, string, boolean, or
None. They are also known as Constants.
Example :
String literals (Text) : 'Hello World'
Numeric literals (Numbers) : 3.14
Boolean literals (Truth Value) : True/False
None Literal : The None keyword is used to define a null value
or absence of a value. None is different from 0.

54
Operators and Operands
Operators are symbols (or keywords) that perform various operations on the operands. An operand is a
variable or a literal on which the operation is performed.
Example: 50 + 20
Here 50 and 20 are operands, and + is the operator.

Arithmetic Operators : Arithmetic operators perform mathematical operations like addition, subtraction,
multiplication, division, floor division, exponent and modulus. (+,-,*,/,//,**,%)

Relational Operators:

Relational operators perform comparison between values. An expression having relational operators
evaluates to either True or False. Example >, <, >=, <=, ==, !=

Python Comments

Comments are descriptions about the code. They help other programmers understand the functionality of
the code. Comments are ignored by the Python interpreter, and are only relevant to the programmer.

Variable

Variables refer to an object (data items like int, float, list, dictionary etc) stored in the memory. Value stored
in a variable can be changed during the program execution.
Rules for naming a variable are the same as the rules for naming an Identifier.
Example: pri = 5
Here pri is a variable with value 5.

Valid variable name examples : name, Age, _total


Invalid variable name examples : print value (whitespace not allowed), 1_gender (cannot start
with a digit)

Concept of L Value and R Value


In Python, the l-value refers to the left-hand side of an assignment operator, while the r-value refers to the
right-hand side of an assignment operator.
The l-value is associated with a valid memory location in the computer. The memory location can be
checked by using the id( ) function.
The r-value may be any valid expression which is executed by the interpreter.
Consider the following assignment statement:

55
x = 5+2
In the statement above, the l-value is 'x' as it is on the left-hand side of the = operator.
The r-value is 7 as it is on the right-hand side of the = operator, and is generated by performing the addition
operation on 5 and 2.
The memory location of x may be checked by executing the command id(x).

Knowledge of Data Types


Data Type
Data type represents the type of data a Variable or a Literal is referring to. Each data type has specific
characteristics and operations associated with it. In Python, there are various data types, including number,
string, boolean, list, tuple, and dictionary.

Mutable and Immutable Data Objects

Python variables are memory references. It may be required to change or update the value of an object
referenced by a variable. However, for certain data objects, Python does not allow us to change the value
of an object.

Mutable Objects:

Mutable data objects are objects that can be changed after they are created. It is possible to add, remove, or
modify elements within these data types. Example of mutable data types: List, Set and Dictionary.

Immutable Objects :

Objects whose values cannot be changed after they are created are called immutable objects. To change the
value, a new object is created. Example of immutable data types: Number (Integer, Float), String, and Tuple.

56
Numeric Data Types (Number)
Python has three numeric data types:
1. Integer
2. Float
3. Complex

Integer
● Numbers with No Fractional Part
● Can be Positive or Negative
● In Python 3, the int type has no max limit. Values can be as large as the available memory allows.
● Example 100, 0o55 (octal number), 0x68(hexadecimal number)

Float
● Numbers with Fractional Part
● Example 3.14, .314E01

Complex
● Numbers with both real and imaginary components
● A complex number is represented by "x + yj". Example 10 + 9j

Boolean
A boolean data type can assume one of the two possible values : True or False.

57
Sequence: Sequence is an ordered collection of items or elements which includes several built-in types
as String, List, and Tuple. Values in the sequence are called elements/items. Each element in a sequence
has a unique index.

String:
● A string is an ordered sequence of characters enclosed in single/double/triple quotes.
● Single Line String : Terminates in a single line. Example – 'This is an example of single line'
● Multi Line String : Does not terminate in a single line. A multiline string may be created using three
quotes

Example -
'''This is a
Multiline
string'''

List:
● List is an ordered sequence data type which can store values of any data type.
● List is mutable.
● List is enclosed in square brackets [ ]
● Example : [ ] is an empty List,
[5, 6.5, True, 'Hello'] is a List having 5, 6.5, True and 'Hello' as four
elements.

Tuple:
● Tuple is an ordered sequence which can store values of any data type.
● They are immutable, i.e the items of a Tuple cannot be updated after creation.
● Tuple is enclosed in parenthesis ( )
● Example : t=( ) is an empty Tuple
t=(9,) is a Tuple with 9 as an item
t=(8, 5, 9.5, False) is a Tuple with 8, 5, 9.5, False as four items

Dictionary:
● Dictionary in Python stores items in the form of key-value pairs
● Syntax is dict_variable = {key1:value1, key2:value2, …, key-n:value-n}
● Items in a dictionary are enclosed in curly brackets { } and are separated by commas
● In a key-value pair, the key is separated from the value using a colon (:)
● To access any value in the dictionary, specify the key as the index using square brackets [ ].
● Example : { } is an empty dictionary,
D = {'name':'Python','version':'3.7.2', 'OS': 'Windows'}
print(D['version']) # shows 3.7.2 as output

58
Special Data-type: None
The None data type/keyword is used to indicate absence of a value (No value or Missing Value).

Operand: Value(s) required for operation of operator.


Operators: Operators can manipulate the value of operands (variables or values). Various symbols are
used as operators.
a = 5
b = 6
sum = a + b
In above example, + and = are the operators, a, b are operands and sum is a variable.

Expression
An expression is combination of operators, operands, literals and parenthesis. An expression produces a
value when evaluated.
Python Statement
In Python, a statement is an instruction that the interpreter can execute.
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Identity Operators
6. Membership Operators
Arithmetic operators: Arithmetic operators perform mathematical operations such as addition,
subtraction, multiplication, division, and modulus.

59
Modulo Operator
The modulo operator (%) evaluates the remainder of the operation when the operand on the left is divided
by the operand on the right of the modulo operator.
Example
15 % 7 = 1
13 % 7 = 6

Relational Operators: Relational operators compare the operands. They evaluate to either True or
False.

Logical operators:
Logical operators combine logical values of true or false into a logical expression. They evaluate to either
True or False. There are three basic types of logical operators: 'NOT', 'AND', and 'OR'.

Assignment operators:
Variables are assigned values using assignment operators.

Example :
sum = 5 + x
result += 5

60
Here, the sum variable is assigned the sum of 5 and x. And, the result variable is assigned the sum of
result and 5.

Identity Operators

The identity operators in Python are "IS" and "IS NOT". They check whether the two objects are of the
same data type and share the same memory address.
Example :
x = 5
y = 5
if x is y:
print("x and y are the same object")
else:
print("x and y are different object")

Output will display x and y are the same object because both of them reference the same memory location.

Membership Operators

The membership operators in Python are 'IN' and 'NOT IN'. They check whether the operand on the left
side of the operator is a member of a sequence (such as a list or a string) on the right side of the operator.

Example :

x = ['Red', 2, 'Green']
if 'Red' in x:
print("Found")
else:
print("Not Found")

Output will display Found because the item 'Red' is a member of the List x.

Operator Precedence

Operator precedence determines the priority of operators in an expression. The precedence of various
operators is shown in the Precedence Table.

61
For example, x = 7 + 3 * 2; will result in 13, not 20, because operator * has higher precedence than +. The
expression is evaluated as 7 + 6.

Associativity of Python Operators

Associativity refers to the order in which operators of the same precedence are evaluated. The associativity
of an operator may be left-to-right or right-to-left.
Precedence Table

Evaluation of Expression
1. Evaluate the expression 50 + 20 * 30
Evaluation:
= 50 + (20 * 30) #precedence of * is more than that of +
= 50 + 600
= 650
2. Evaluate the expression 100 - 20 + 50
Evaluation:
The two operators (–) and (+) have equal precedence and the associativity is from left to right so the left
operator (i.e. -) will be evaluated first.
= (100 – 20) + 50
= 80 + 50
= 130

3. Evaluate the expression 9 + 3 ** 2 * 4 // 3


Evaluation:
= 9 + (3 ** 3) * 4 // 3

62
= 9 + 27 * 4 // 3 (* and // has left to right associativity)
= 9 + 108 // 3
= 9 + 36
= 45

Type conversion
It is the process of converting the value from one data type into another. Python supports two ways of Type
conversion:
● Implicit conversion
● Explicit conversion

Implicit conversion
This type of conversion is performed by Python Interpreter automatically without the user's intervention.
Example:
num1 = 20 # num1 is integer
num2 = 30.5 # num2 is float
sum1 = num1 + num2 # sum1 will use float to avoid
# loss of fractional part during addition
print(sum1)
print(type(sum1))

Output:
50.5
<class 'float'>

Explicit Conversion:
This type of conversion is performed by the user manually. It is also known as type-casting. Explicit type-
casting is performed using functions such as int( ), float( ), str( ) etc.
Syntax : new_data_type (expression)
Example
num1 = input("Enter a number : ") # takes a string input by default
var1 = int(num1) #converts string to integer
var1 = var1 * 3
print(var)

Output
Enter a number : 2
6

63
Input and Output in Python
Data Input:
input( ) function is used for getting input from the user. It returns the input as a String data type by default.
Explicit type casting is required to convert the input string into any other data type if required.

Data Output:
print( ) function is used for displaying output on the screen.

Example-1
num1 = int(input("Enter a Number : ")) # type casting the input from
String to Int
print("The Number is : ", num1)

Example-2
num = int(input("Enter a Number : "))
num_cube = num*num*num
print("The cube is : ",num_cube)

Errors

An error is a problem that occurs in a program. Error sometimes halt the program execution, or produce
unexpected results, and cause the program to behave abnormally.
● Syntax error
● Logical error
● Runtime error

Syntax Error

Syntax are the rules for framing statements in a programming language. Any violations in the rules while
writing a program are known as Syntax Errors. They prevent the code from executing and are detected by
the Python interpreter before the execution of the program begins.
Some of the Common Syntax Errors are

64
● Parenthesis Mismatch
● Misspelled keyword
● Incorrect Indentation

Logical Error
Logical errors occur when the code runs without any errors, but the output is not as expected. Logical errors
are caused by a problem in the logic of the code.
Example : Average = mark_1 + mark_2 / 2 # incorrect calculation of average marks
Corrected Code : Average = (mark_1 + mark_2 ) / 2

Runtime Error
A runtime error causes abnormal termination of the program during the execution. Runtime error occurs
when the statement is correct syntactically, but the interpreter cannot execute it.

Example: 'division by zero'

num1 = 5.0
num2 = int(input("num2 = ")) #if the user inputs zero, a runtime error
will occur
print(num1/num2)

Flow of Control

Flow of Control refers to the order in which statements are executed in a program.

Sequential Flow

The default control flow in a program is sequential flow, in which statements are executed line-by-line one
after the other in a sequence in which they are written.

Example

x = 6
y = 7
z = y - x
print(z)

65
Conditional Flow

Conditional flow refers to execution of certain statements only if a specific condition is met. This is
accomplished by the use of conditional statements such as if, if-else, and if-elif-else.

Example
num = int(input("Enter a number : "))
if(num>5):
print("Number is greater than 5")
else:
print("Number is less than 5")

Output
Enter a number : 55
Number is greater than 5

Iterative Flow

Iteration means 'repetition'.


Iterative flow repeats statements in a block of code. Repetition or looping can be performed a fixed number
of times or until a certain condition is met. This is accomplished through the use of iterative statements: for
and while.

Example-1
name = input("Enter your name : ")
for x in range(5): # range function creates a sequence of integers from 0 to 4
print("Hello", name)

Example-2
name = input("Enter your name : ")
i=1
while i<=5:
print("Hello", name)
i +=1

66
Conditional Statements

Conditional statements execute specific blocks of code based on certain conditions. In Python, conditional
statements are implemented using the keywords if, if-else, and if-elif-else.

Terminology
Indentation
Indentation refers to the spaces at the beginning of a line.
Example
if a<5:
print(a)
print('Inner Block')
print('Outside block')

Block of code
A block of code is a set of statements that are grouped together and executed as a single unit. A block of
code is identified by the indentation of the lines of code.

if statement
The if statement is used to execute a block
of code only if a certain condition is true.

Syntax:
if <condition>:
Set of Statements

Flow Chart of if-statement

Example-

age = int(input("Enter your age : "))


if age>=18:
print('Congratulations')
print('You are allowed to vote')

67
Program
Write a python Program to find the absolute value of the number entered by the user.
num = int(input("Enter any number : "))
if num>=0:
abs_num = num
else:
abs_num= -num
print(abs_num)

Output
Enter any number : -5
5

Program
Write a python Program to sort three numbers entered by a user.
a = float(input("Enter the first number : "))
b = float(input("Enter the second number : "))
c = float(input("Enter the third number : "))
if a > b:
a,b = b,a
if a > c:
a,c = c,a
if b > c:
b,c = c,b
print (a, "<", b, "<", c)
Output
Enter the first number : 30
Enter the second number : 25
Enter the third number : 20
20.0 < 25.0 < 30.0

if-else statement

The if-else statement is used to execute one block of code if a certain condition is true, and another block
of code if the condition is false.

68
Syntax of if-else

if <condition>:
set of statements
else:
set of statements

Example

age = int(input("Enter your age : "))


if age>=18:
print('Congratulations')
print('You are allowed to vote')
else:
print('You are not allowed to vote')
print('Thanks')

Flowchart of if-else statement

69
Program
Write a python Program to check if a number entered by a user is divisible by 3.
num=int(input("Enter a number : "))
if num % 3 == 0:
print(num,"is divisible by 3")
else:
print(num,"is not divisible by 3")
Output
Enter a number : 601
601 is not divisible by 3

if-elif-else statement
if-elif-else statement is used to check multiple conditions.
Program

per = int(input("Enter Percentage : "))


if per >= 75:
print("Distinction")
elif per >= 60:
print("Grade-A")
elif per >= 50:
print("Grade-B")
elif per >= 40:
print("Grade-C")
else:
print("Grade-D")

Flowchart of if-elif-else statement

70
Iterative Statement
Iterative statements execute a set of instructions multiple times. 'for' and 'while' loops are the iterative
statements in Python.

while Loop
The while loop repeatedly executes a block of code as long as the specified condition is true.
The while loop is an exit controlled loop, i.e. the user is responsible for exiting the loop by changing the
value of the condition to False. While loop may run infinitely if the condition remains true.
Syntax:
while (condition):
block of statements

Flowchart of while loop

Example
Write a Python Program (using a while loop) to Find the Sum of First 10 Natural Numbers.
num=1
sum=0
while (num <= 10):
sum = sum + num
num = num+1
print ("Sum of Natural Numbers : ", sum)

Example
Write a Python Program (using the while loop) to Find the Sum of First N Natural Numbers where N is
entered by the user.
num=1
sum=0
n = int(input("Enter the value of n : "))
while (num <= n):
sum = sum + num
num = num+1
print ("Sum of Natural Numbers : ", sum)

71
range( ) Function
range( ) is a built-in function that returns a sequence of numbers.
Syntax
range(start, stop, step)
start: The starting value of the sequence (inclusive). If not specified, it defaults to 0.
stop: The ending value of the sequence (exclusive).
step: The difference between two consecutive elements. Its default value is 1.
The range( ) function can be used in for loops to iterate over a sequence of numbers.

Case-1 Case-2 Case-3 Case-4


x = list(range(5)) x = list(range(3,6)) x = list(range(3,20,2)) x = list(range(0, -9, -1))
print(x) print(x) print(x) print(x)
Output Output Output Output
[0, 1, 2, 3, 4] [3, 4, 5] [3, 5, 7, 9, 11, 13, 15, 17, [0, -1, -2, -3, -4, -5, -6, -7, -
19] 8]

for Loop
The for loop is used to iterate over a sequence (such as a list, tuple, string, etc.) and execute a block of code
for each item in the sequence.

Syntax
for <control_variable> in <sequence>:
Block of code

Flowchart of for loop

72
Example-1 Example-2
list1 = [1,2,3,4,5,6,7,8,9,10] str1 = 'India'
for var1 in list1: for each_character in str1:
print(var1) print(each_character)

Program-1
Write a Python Program (using for loop) to Find the Sum of First 10 Natural Numbers.
sum=0
for num in range(1,11):
sum = sum + num
print ("Sum of Natural Numbers : ", sum)
Output:
Sum of Natural Numbers : 55

Program-2
Write a Python Program (using for loop) to Find the Sum of First N Natural Numbers where N is entered by the
user.
sum=0
n = int(input("Enter the value of n : "))
for num in range(1, n+1):
sum = sum + num
print ("Sum of Natural Numbers : ", sum)

Output:
Enter the value of n : 20
Sum of Natural Numbers : 210

Program-3
Write a Python Program (using for loop) 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 numbers")
else:
for i in range(1, num + 1):
factorial *= i
print("The factorial of", num, "is", factorial)

Output
Enter a number: 5
The factorial of 5 is 120

73
Break and Continue Statement
Break Statement: The break statement is used to terminate a loop immediately. It is typically used with
conditional statements.
Continue Statement: The continue statement skips all the remaining statements in the current iteration of
the loop and moves the control to the beginning of the next iteration.
Example :
fruits = ['apple', 'banana', 'cherry']
for x in fruits:
if x == 'banana':
break
print(x)

Example :
Write a program in Python to check if a number entered by a user is a prime number or not.
num = int(input("Enter a number: "))
flag=False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flag=True
break
if flag==True:
print(num, "is not a prime number")
else:
print(num, "is a prime number")

Example :
Write a program in Python to print all natural numbers from 1 to 10 except 7.
for i in range(1,11):
if i==7:
continue
print(i)

Example :
Write a program in Python to print all natural numbers between 1 and 50 (both inclusive) which are not
multiple of 3.
for x in range(1, 51):
if x % 3 ==0 :
continue
print(x)

74
Nested loops
Nested loops refers to a loop within a loop.
Example: Generating a pattern
n = int(input("Enter the number of rows: "))
for i in range(n):
for j in range(i+1):
print("*", end="")
print()

Output
Enter the number of rows: 5
*
**
***
****
*****

String
String: String is a sequence of UNICODE characters. A string can be created by enclosing one or more
characters in single, double or triple quotes (' ' or '' '' or ''' ''').
Example
>>> str1 = 'Python'
>>> str2 = "Python"
>>> str3 = '''Multi Line
String'''
>>> str4 = """Multi Line
String"""

Terminology

Whitespace Characters: Those characters in a string that represent horizontal or vertical space.
Example: space (' '), tab ('\t'), and newline ('\n')

75

You might also like