Chapter 10 : Tuples and Dictionaries | class 11th | revision notes computer science

Tuples Manipulation in Python – Notes


Topics:

  • Tuples:
    • Introduction,
    • indexing,
    • tuple operations (concatenation, repetition, membership & slicing),
    • built-in functions: len(), tuple(), count(), index(), sorted(), min(), max(), sum();
    • tuple assignment,
    • nested tuple,
  • Suggested programs:
    • finding the minimum,
    • maximum, mean of values stored in a tuple;
    • linear search on a tuple of numbers,
    • counting the frequency of elements in a tuple

What is Tuple?

A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list or even a tuple.

Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by commas.

Like list and string, elements of a tuple can be accessed using index values, starting from 0.

# tuple1 is the tuple of integers
       >>> tuple1 = (1,2,3,4,5)
       >>> tuple1
       (1, 2, 3, 4, 5)
# tuple2 is the tuple of mixed data types
       >>> tuple2 =('Economics',87,'Accountancy',89.6)
       >>> tuple2
       ('Economics', 87, 'Accountancy', 89.6)
# tuple3 is the tuple with list as an element
       >>> tuple3 = (10,20,30,[40,50])
       >>> tuple3
       (10, 20, 30, [40, 50])
# tuple4 is the tuple with tuple as an element i.e. tuple inside the tuple
       >>> tuple4 = (1,2,3,4,5,(10,20))
       >>> tuple4
       (1, 2, 3, 4, 5, (10, 20))         

Tuple having Single Element:

If there is only a single element in a tuple then the element should be followed by a comma.

Note : If we assign the value without comma it is treated as integer.

# tuple5 is assigned a single element
      >>> tuple5 = (20)        
      >>> tuple5
      20
      >>> type(tuple5)    #tuple5 is not of type tuple 
      <class 'int'>       #it is treated as integer 

# tuple6 is assigned a single element
      >>> tuple6 = (20,) #element followed by comma
      >>> tuple6
       (20,)
      >>> type(tuple5)   #tuple6 is of type tuple
      <class 'tuple'>    #it is treated as tuple                

Tuple created without parenthesis ( ) :

A sequence of without parenthesis i.e. values separated with comma is treated as tuple by default.

# A sequence without parentheses is treated as tuple by default
    >>> seq = 1,2,3      #comma separated elements
    >>> type(seq)        #treated as tuple
    <class 'tuple'>   
    >>> print(seq)       #seq is a tuple
    (1, 2, 3)  

# A sequence having different types of values
    >>> seq = 1, "www.anjeevsinghacademy.com", 2, "www.mycstutorial.in"
    >>> type(seq)
    <class 'tuple'>   
    >>> print(seq)
    (1, 'www.anjeevsinghacademy.com', 2, 'www.mycstutorial.in')                

Accessing Elements in a Tuple

Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing.

 # Creating / Initializes a tuple tuple1       
 >>> tuple1 = (2,4,6,8,10,12)          
 # Accessing the first element of tuple1
 >>> tuple1[0]
 2
 # Accessing the fourth element of tuple1
 >>> tuple1[3]
 8
# an expression resulting in an integer index
 >>> tuple1[1+4]
 12

 # Backward Accessing 
 
 # Accessing the first element from right
 >>> tuple1[-1]
 12 
 # Accessing the third element from right
 >>> tuple1[-3]
 8       
 # Index out of range : If invalid index is given then python raise an error message - IndexError : Index out of      
   range. 

#returns error as index is out of range
 >>> tuple1[15]
 IndexError: tuple index out of range       

Tuple is Immutable

Tuple is an immutable data type. It means that the elements of a tuple cannot be changed after it has been created. An attempt to do this would lead to an error.

  >>> tuple1 = (1,2,3,4,5)         
  >>> tuple1[4] = 10
  TypeError: 'tuple' object does not support item assignment         

Elements of Tuple is Mutable (If element is a list)

An element of a tuple may be of mutable type, e.g., a list.

# 4th element of the tuple2 is a list
  >>> tuple2 = (1,2,3,[8,9])
# modify the list element of the tuple tuple2
  >>> tuple2[3][1] = 10
# modification is reflected in tuple2
  >>> tuple2
  (1, 2, 3, [8, 10])         

List vs Tuple:

  • List is mutable but tuple is immutable. So iterating through a tuple is faster as compared to a list.
  • If we have data that does not change then storing this data in a tuple will make sure that it is not changed accidentally.

Tuple Operations

1. Concatenation (+)

Python allows us to join tuples using concatenation operator depicted by symbol +.

 # concatenates two tuples
  >>> tuple1 = (1,3,5,7,9)
  >>> tuple2 = (2,4,6,8,10)
  >>> tuple1 + tuple2
  (1, 3, 5, 7, 9, 2, 4, 6, 8, 10)        

Create a new tuple which contains the result of this concatenation operation.

  >>> tuple3 = ('Red','Green','Blue')
  >>> tuple4 = ('Cyan', 'Magenta', 'Yellow' ,'Black')
  # tuple5 stores elements of tuple3 and tuple4
  >>> tuple5 = tuple3 + tuple4
  >>> tuple5
  ('Red','Green','Blue','Cyan','Magenta','Yellow','Black')         

Concatenation operator can also be used for extending an existing tuple. When we extend a tuple using concatenation a new tuple is created.

# single element is appended to tuple6
 >>> tuple6 = (1,2,3,4,5)
 >>> tuple6 = tuple6 + (6,)
 >>> tuple6
 (1, 2, 3, 4, 5, 6)
 
# more than one elements are appended
 >>> tuple6 = tuple6 + (7,8,9)
 >>> tuple6
 (1, 2, 3, 4, 5, 6, 7, 8, 9)         

2. Repetition / Replication Operator *

Repetition operation is depicted by the symbol *. It is used to repeat elements of a tuple. We can repeat the tuple elements. The repetition operator requires the first operand to be a tuple and the second operand to be an integer only.

  >>> tuple1 = ('Hello','World')
  >>> tuple1 * 3
  ('Hello', 'World', 'Hello', 'World', 'Hello', 'World')
# tuple with single element
  >>> tuple2 = ("Hello",)
  >>> tuple2 * 4
  ('Hello', 'Hello', 'Hello', 'Hello')         

3. Membership operator [ in and not in ]

in : The in operator checks if the element is present in the tuple and returns True, else it returns False.

   >>> tuple1 = ('Red','Green','Blue')
   >>> 'Green' in tuple1
   True         

not in : The not in operator returns True if the element is not present in the tuple, else it returns False.

   >>> tuple1 = ('Red','Green','Blue')
   >>> 'Green' not in tuple1
   False         

4. Slicing

Slicing means extracting the parts of list. Like string and list, slicing can be applied to tuples in the same way.

Forward Slicing

 # tuple1 is a tuple
   >>> tuple1 = (10,20,30,40,50,60,70,80)

 # elements from index 2 to index 6
   >>> tuple1[2:7]
   (30, 40, 50, 60, 70)

 # all elements of tuple are printed
   >>> tuple1[0:len(tuple1)]
   (10, 20, 30, 40, 50, 60, 70, 80)

 # slice starts from zero index
   >>> tuple1[:5]
   (10, 20, 30, 40, 50)

 # slice is till end of the tuple
   >>> tuple1[2:]
   (30, 40, 50, 60, 70, 80) 
 # step size 2
   >>> tuple1[0:len(tuple1):2]
   (10, 30, 50, 70)         

Backward Slicing / Negative Indexing

 # slice in reverse of the tuple
   >>> tuple1[::-1]
   (80, 70, 60, 50, 40, 30, 20, 10) 
   
   >>> tuple1[-1: -(len(tuple)+1):-1]
   (80, 70, 60, 50, 40, 30, 20, 10) 
 # slice in reverse alternate element of the tuple
   >>> tuple1[-1: -(len(tuple)+1):-2]
   (80,60,40,20)  
 # negative indexing
   >>> tuple1[-6:-4]
   (30, 40)          

Tuple Methods and Built-in Functions

1. len() : Returns the length or the number of elements of the tuple passed as the argument

>>> tuple1 = (10,20,30,40,50)
>>> len(tuple1)
5

2. tuple() : Creates an empty tuple if no argument is passed. Creates a tuple if a sequence is passed as argument

>>> tuple1 = tuple()
>>> tuple1
( )
>>> tuple1 = tuple(‘aeiou’) #string
>>> tuple1
(‘a’, ‘e’, ‘i’, ‘o’, ‘u’)
>>> tuple2 = tuple([1,2,3]) #list
>>> tuple2
(1, 2, 3)
>>> tuple3 = tuple(range(5))
>>> tuple3
(0, 1, 2, 3, 4)

3. count() : Returns the number of times the given element appears in the tuple.

>>> tuple1 = (10,20,30,10,40,10,50)
>>> tuple1.count(10)
3
>>> tuple1.count(90)
0

4. index() : Returns the index of the first occurrence of the element in the given tuple.

>>> tuple1 = (10,20,30,40,50)
>>> tuple1.index(30)
2
>>> tuple1.index(90)
ValueError: tuple.index(x): x not in tuple

5. sorted() : Takes elements in the tuple and returns a new sorted list. It should be noted that, sorted() does not make any change to the original tuple

tuple1 = (“Rama”,”Heena”,”Raj”,
“Mohsin”,”Aditya”)
sorted(tuple1)
[‘Aditya’, ‘Heena’, ‘Mohsin’, ‘Raj’,
‘Rama’]

6. min() : Returns minimum or smallest element of the tuple.

7. max() : Returns maximum or largest element of the tuple.

8. sum() : Returns sum of the elements of the tuple.

tuple1 = (19,12,56,18,9,87,34)
min(tuple1)
9
max(tuple1)
87
sum(tuple1)
235

Tuple Assignment :

Assignment of tuple is allows a tuple of variables on the left side of the assignment operator to be assigned respective values from a tuple on the right side. The number of variables on the left should be same as the number of elements in the tuple.

# The first element 10 is assigned to num1 and the second element 20 is assigned to num2.

>>> (num1,num2) = (10,20)
>>> print(num1)
10
>>> print(num2)
20
>>> record = ( “Pooja”,40,”CS”)
>>> (name,rollNo,subject) = record
>>> name
‘Pooja’
>>> rollNo
40
>>> subject
‘CS’
>>> (a,b,c,d) = (5,6,8)
ValueError: not enough values to unpack (expected 4, got 3)

Tuple Unpacking :

Tuple Unpacking means, assigning values of tuple elements to different variables. Variables are written left of assignment operator separated by comma and tuple is written on the right side of assignment operator.

Be ensure, number of variables must be equal to the number of elements of tuple. Otherwise Python raise ValueError: not enough values to unpack.

>>> num1,num2 = (10,20)
>>> print(num1)
10
>>> print(num2)
20
>>> record = ( “Pooja”,40,”CS”)
>>> name, rollNo, subject = record
>>> name
‘Pooja’
>>> rollNo
40
>>> subject
‘CS’
>>> (a,b,c,d) = (5,6,8)
ValueError: not enough values to unpack (expected 4, got 3)

Nested Tuples

A tuple inside another tuple is called a nested tuple.

>>> nestedtuple = ( (1,2,3), (4,5,6), (7,8,9))
>>> nestedtuple
((1, 2, 3), (4, 5, 6), (7, 8, 9))
>>> nestedtuple[0]
(1, 2, 3)
>>> nestedtuple[1]
(4, 5, 6)
>>> nestedtuple[2]
(7, 8, 9)
>>> nestedtuple[0][0]
1
>>> nestedtuple[0][1]
2
>>> nestedtuple[2][1]
8
>>> print(nestedtuple)
((1, 2, 3), (4, 5, 6), (7, 8, 9))

Program : A program to create a nested tuple to store roll number, name and marks of students.

 st=((101,"Aman",98),(102,"Geet",95),(103,"Sahil",87),(104,"Pawan",79))
 
 print("S_No"," Roll_No"," Name"," Marks")
 for i in range(0,len(st)):
     print((i+1),'\t',st[i][0],'\t',st[i][1],'\t',st[i][2])

Output:

 S_No  Roll_No Name  Marks
 1     101     Aman   98
 2     102     Geet   95
 3     103     Sahil  87
 4     104     Pawan  79

Tuple Handling

Program Write a program to swap two numbers without using a temporary variable.

 # Program : Program to swap two numbers
 num1 = int(input('Enter the first number: '))
 num2 = int(input('Enter the second number: '))
 print("\nNumbers before swapping:")
 print("First Number:",num1)
 print("Second Number:",num2)
 (num1,num2) = (num2,num1)
 print("\nNumbers after swapping:")
 print("First Number:",num1)
 print("Second Number:",num2)

Output:
Enter the first number: 5
Enter the second number: 10
Numbers before swapping:
First Number: 5
Second Number: 10
Numbers after swapping:
First Number: 10
Second Number: 5

Program : Write a program to compute the area and circumference of a circle using a function.

 # Function to compute area and circumference of the circle.
 def circle(r):
     area = 3.14rr
     circumference = 23.14r
     return (area,circumference) 
     #returns a tuple having two elements area and circumference
 #end of function
 
 radius = int(input('Enter radius of circle: '))
 
 area,circumference = circle(radius)
 
 print('Area of circle is:',area)
 print('Circumference of circle is:',circumference)

Output:
Enter radius of circle: 5
Area of circle is: 78.5
Circumference of circle is: 31.400000000000002

Program : Write a program to input n numbers from the user. Store these numbers in a tuple. Print the maximum and minimum number from this tuple.

 numbers = tuple() #create an empty tuple 'numbers'
 n = int(input("How many numbers you want to enter?: "))
 for i in range(0,n):
     num = int(input())
     # it will assign numbers entered by user to tuple 'numbers'
     numbers = numbers +(num,)
 print('\nThe numbers in the tuple are:')
 print(numbers)
 print("\nThe maximum number is:")
 print(max(numbers))
 print("The minimum number is:")
 print(min(numbers))

Output:

How many numbers do you want to enter?: 5
98
10
12
15
The numbers in the tuple are:
(9, 8, 10, 12, 15)
The maximum number is:
15
The minimum

Read More

Chapter 9 : Lists | class 11th | revision notes computer science

Class 11 Computer Science List in Python Notes and Questions

7.1 Introduction:

  • List is a collection of elements which is ordered and changeable (mutable).
  • Allows duplicate values.
  • A list contains items separated by commas and enclosed within square brackets ([ ]).
  • All items belonging to a list can be of different data type.
  • The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list.

Difference between list and string:

List in Python Class 11 Computer Science Notes And Questions

7.2 Creating a list:
To create a list enclose the elements of the list within square brackets and separate the elements by commas.
Syntax: list-name= [item-1, item-2, …….., item-n]
Example:
mylist = [“apple”, “banana”, “cherry”] # a list with three items
L = [ ] # an empty list

7.2.1 Creating a list using list( ) Constructor:
o It is also possible to use the list( ) constructor to make a list.
mylist = list((“apple”, “banana”, “cherry”)) #note the double round-brackets print(mylist)
L=list( ) # creating empty list

7.2.2 Nested Lists:
>>> L=[23,’w’,78.2, [2,4,7],[8,16]]
>>> L
[23, ‘w’, 78.2, [2, 4, 7], [8, 16]]

7.2.3 Creating a list by taking input from the user:
>>> List=list(input(“enter the elements: “))
enter the elements: hello python
>>> List
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

>>> L1=list(input(“enter the elements: “))
enter the elements: 678546
>>> L1 [‘6’, ‘7’, ‘8’, ‘5’, ‘4’, ‘6’]
# it treats elements as the characters though we entered digits

To overcome the above problem, we can use eval( ) method, which identifies the data type and evaluate them automatically.
>>> L1=eval(input(“enter the elements: “))
enter the elements: 654786
>>> L1
654786 # it is an integer, not a list
>>> L2=eval(input(“enter the elements: “))
enter the elements: [6,7,8,5,4,3] # for list, you must enter the [ ] bracket
>>> L2
[6, 7, 8, 5, 4, 3]
Note: With eval( ) method, If you enter elements without square bracket[ ], it will be considered as a tuple.
>>> L1=eval(input(“enter the elements: “))
enter the elements: 7,65,89,6,3,4 >>> L1
(7, 65, 89, 6, 3, 4) #tuple

7.3 Accessing lists:

  • The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes.
  • List-name[start:end] will give you elements between indices start to end-1.
  • The first item in the list has the index zero (0).

    Example: >>> number=[12,56,87,45,23,97,56,27]
List in Python Class 11 Computer Science Notes And Questions

number[2]
87 >>>
number[-1]
27
>>> number[-8]
12 >>> number[8]
IndexError: list index out of range
>>> number[5]=55 #Assigning a value at the specified index

number [12, 56, 87, 45, 23, 55, 56, 27]

7.4 Traversing a LIST:
Traversing means accessing and processing each element.
Method-1:
>>> day=list(input(“Enter elements :”))
Enter elements : sunday
>>> for d in day:
print(d)
Output:
s
u
n
d
a
y

Method-2
>>> day=list(input(“Enter elements :”))
Enter elements : wednesday
>>> for i in range(len(day)): print(day[i])
Output:
w
e
d
n
e
s
d
a
y

7.5 List Operators:

  • Joining operator +
  • Repetition operator *
  • Slice operator [ : ]
  • Comparison Operator <, <=, >, >=, ==, !=
  • Joining Operator: It joins two or more lists.
    Example: >>> L1=[‘a’,56,7.8] >>> L2=[‘b’,’&’,6] >>> L3=[67,’f’,’p’] >>> L1+L2+L3 [‘a’, 56, 7.8, ‘b’, ‘&’, 6, 67, ‘f’, ‘p’]
  • Repetition Operator: It replicates a list specified number of times.
    Example: >>> L13 [‘a’, 56, 7.8, ‘a’, 56, 7.8, ‘a’, 56, 7.8] >>> 3L1 [‘a’, 56, 7.8, ‘a’, 56, 7.8, ‘a’, 56, 7.8]
  • Slice Operator:
    List-name[start:end] will give you elements between indices start to end-1.
    >>> number=[12,56,87,45,23,97,56,27]
    >>> number[2:-2]
    [87, 45, 23, 97]
    >>> number[4:20]
    [23, 97, 56, 27]
    >>> number[-1:-6]
    [ ]
    >>> number[-6:-1]
    [87, 45, 23, 97, 56]

number[0:len(number)]
[12, 56, 87, 45, 23, 97, 56, 27]
List-name[start:end:step] will give you elements between indices start to end-1 with skipping elements as per the value of step.
>>> number[1:6:2]
[56, 45, 97]
>>> number[: : -1]
[27, 56, 97, 23, 45, 87, 56, 12]
#reverses the list

List modification using slice operator:
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:4]=[“hello”,”python”]
>>> number
[12, 56, ‘hello’, ‘python’, 23, 97, 56, 27]
>>> number[2:4]=[“computer”] >>> number [12, 56, ‘computer’, 23, 97, 56, 27]
Note: The values being assigned must be a sequence (list, tuple or string)
Example: >>> number=[12,56,87,45,23,97,56,27]
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:3]=78 # 78 is a number, not a sequence
TypeError: can only assign an iterable

  • Comparison Operators:
    o Compares two lists
    o Python internally compares individual elements of lists in lexicographical order.
    o It compares the each corresponding element must compare equal and two sequences must be of the same type.
    o For non-equal comparison as soon as it gets a result in terms of True/False, from corresponding elements’ comparison. If Corresponding elements are equal, it goes to the next element and so on, until it finds elements that differ.

Example:

L1, L2 = [7, 6, 9], [7, 6, 9]
L3 = [7, [6, 9] ]

For Equal Comparison:

List in Python Class 11 Computer Science Notes And Questions

For Non-equal comparison:

List in Python Class 11 Computer Science Notes And Questions

List Methods:
Consider a list:
company=[“IBM”,”HCL”,”Wipro”]

List in Python Class 11 Computer Science Notes And Questions
List in Python Class 11 Computer Science Notes And Questions
List in Python Class 11 Computer Science Notes And Questions
List in Python Class 11 Computer Science Notes And Questions
List in Python Class 11 Computer Science Notes And Questions

Deleting the elements from the list using del statement:
Syntax:
del list-name[index] # to remove element at specified index del list-name[start:end] # to remove elements in list slice

Example:
>>> L=[10,20,30,40,50]
>>> del L[2] # delete the element at the index 2
>>> L
[10, 20, 40, 50]

>>> L= [10,20,30,40,50]
>>> del L[1:3]
# deletes elements of list from index 1 to 2.
>>> L
[10, 40, 50]
>>> del L # deletes all elements and the list object too.
>>> L
NameError: name ‘L’ is not defined

Difference between del, remove( ), pop( ), clear( ):

List in Python Class 11 Computer Science Notes And Questions

Difference between append( ), extend( ) and insert( ) :

List in Python Class 11 Computer Science Notes And Questions

ACCESSING ELEMENTS OF NESTED LISTS:
Example:

L=[“Python”, “is”, “a”, [“modern”, “programming”], “language”, “that”, “we”, “use”]
L[0][0]
‘P’
L[3][0][2]
‘d’
https://pythonschoolkvs.wordpress.com/ Page 73
L[3:4][0]
[‘modern’, ‘programming’]
L[3:4][0][1]
‘programming’
L[3:4][0][1][3]
‘g’
L[0:9][0]
‘Python’
L[0:9][0][3]
‘h’
L[3:4][1]
IndexError: list index out of range

Programs related to lists in python:
Program-1
 Write a program to find the minimum and maximum number in a list.
L=eval(input(“Enter the elements: “))
n=len(L)
min=L[0]
max=L[0]
for i in range(n):
if min>L[i]:
min=L[i]
if max<L[i]:
max=L[i]
print(“The minimum number in the list is : “, min)
print(“The maximum number in the list is : “, max)

Program-2 Find the second largest number in a list.
L=eval(input(“Enter the elements: “))
n=len(L)
max=second=L[0]
for i in range(n):
if maxsecond:
max=L[i]
seond=max
print(“The second largest number in the list is : “, second)

Program-3: Program to search an element in a list. (Linear Search).
L=eval(input(“Enter the elements: “))
n=len(L)
item=eval(input(“Enter the element that you want to search : “))
for i in range(n):
if L[i]==item:
print(“Element found at the position :”, i+1)
break
else:
print(“Element not Found”)

Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4

Read More

Chapter 8 : Strings | class 11th | revision notes computer science

String Manipulation in Python

Topics:

  • Strings – introduction,
  • Indexing
  • String operations – concatenation, repetition, membership & slicing,
  • Traversing a string using loops,
  • Built-in functions: len(), capitalize(), title(), lower(), upper(), count(), find(), index(), endswith(), startswith(), isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), lstrip(), rstrip(), strip(), replace(), join(), partition(), split()

Strings in Python – Introduction

Python strings are characters enclosed in quotes of any type – single quotation marks, double quotation marks, triple quotation marks.

S = ‘Anjeev Singh Academy’ ,    

T =  “Singh@123”

Mline = ‘‘‘Anjeev Singh Academy

is the best free online academy on YouTube ’’’

Python strings is an immutable data type, i.e. not allowed to change in place. S[0] =‘R’ not allowed

String Indexing – Forward and Backward Indexing in Python

Strings are sequence of characters, where each character has a unique index number.

string = “mycstutorial.in”

>>> string[0]

‘m’

>>> string[-1]

‘n’

Two types of Indexing is supported in python.

(A) Forward Indexing and (B) Backward Indexing

The indexes of strings begin from 0 to length-1, in forward direction and  -1, -2, -3, …. , -length in backward direction.

String operations – concatenation, repetition, membership & slicing,

Strings can be manipulated by using string operators. String operators are

OperatorNameDescription
+ConcatenationAdd two strings i.e. concatenate two strings. e.g.      S = “Hello” + “Shyam”
*Replication  / RepetitionReplicate the string upto n times.
In / not inMembershipTo check given character exists in the string or not.
[index]Element AccessorExtract the character from the given index position.
[ : ]Slicing [start:end:step]Extracts the characters from the given range i.e start to stop
==, !=, < , > , <=, >=Relational / Comparison OperatorThese relational operators can do comparison between strings, based on character by character  comparison rules for Unicode or Ordinal Value

Traversing a string using loops

Traversing a String or Text means accessing all characters of string, character by character, through its index position.

#Traversal of a string using loop
name = "mycstutorial.in"
for char in name:
    print (char, end=' ')

Output

m y c s t u t o r i a l . i n

Traversing a String using index position

#Traversal of a string using index - forward indexing
name = "mycstutorial.in"
for index in range(len(name)):
    print (name[index], end=' ')

Output

m y c s t u t o r i a l . i n
#Traversal of a string using index - backward indexing
name = "mycstutorial.in"
for index in range(-1, -len(name)-1, -1):
    print (name[index], end=' ')

Output

n i . l a i r o t u t s c y m 

String Slicing

Slice means ‘a part of’.  In Python, string slice refers to a part of string containing some contiguous characters from the string.

Syntax: string[start : end : step]

  • where start and end are integers with legal indices.
  • will return the characters falling between indices start and end. i.e. start, start+1, start+2,…, till end-1.
  • By default value of step is 1. It is an optional argument.
SliceOutput, if str = “Hello Anjeev
str[ 2 : ]‘llo Anjeev”
str[ : 5]“Hello”
str[4 : 8]“o Anj”
str[ : : 2]“HloAje”
str[ : : -1]“veejnA olleH”
str[-6 : -2 ]“Anje”

String Built-in functions

Python provides several built-in-methods to manipulate string. 

Syntax : stringvariable.methodName( )

Example: isalnum(), isalpha(), isdigit(), islower(), isupper(), isspace(), etc

MethodsDescriptionExample
isalpha( )Returns True, if the string contains only letters, otherwise returns False.>>>”abc”.isalpha()
True
>>>”1abc”.isalpha()
False
isalnum()Returns True, if the string contains alphanumeric (i.e. alphabets or number or both), otherwise returns False>>>”abc”.isalnum()
True
>>>”123″.isalnum()
True
>>>”a123″.isalnum()
True
>>>”@#2″.isalnum()
False
>>>”@#12ab”.isalnum()
False
isdigit( )Return True, if the string contains only digits, otherwise returns False.>>>”123″.isdigit()
True
>>>”abc123″.isdigit()
False
isspace( )Returns True, if the string contains only spaces, otherwise returns False.>>>” “.isspace()
True
>>>”a “.isspace()
False
>>>” a”.isspace()
False
islower( )Returns True if the string contains all lowercase characters, otherwise returns False.>>>”mycstutorial.in”.islower()
True
>>>”MYCSTUTORIAL.IN”.islower()
False
isupper()Returns True, if the string contains all uppercase characters, otherwise returns False>>>”MYCSTUTORIAL.IN”.isupper()
True
>>>”mycstutorial.in”.isupper()
False
istitle( )Returns True, if string is properly “TitleCasedString”, otherwise returns False.>>>”Anjeev Singh Academy”.istitle()
True
>>>”Anjeev singh academy”.istitle()
False
>>>”Anjeevsinghacademy”.istitle()
True
endswith()Returns Ture, if string is ends with the given substring.>>> name=”tanmay singh”
>>> name.endswith(‘singh’)
True
>>> name.endswith(‘nh’)
False
startswith()Returns True, if string is starts with the given substring.>>> name=”tanmay singh”
>>> name.startswith(‘tan’)
True
>>> name.startswith(‘tannu’)
False
len(string)Returns the length of string, i.e. number of characters.>>> name=”tanmay singh”
>>> len(name)
12
capitalize()Returns a copy of string with its first character capitalized.>>> name=”tanmay singh”
>>> name.capitalize()
‘Tanmay singh’
lower()Returns a copy of string converted to lowercase.>>> name=”TANMAY SINGH”
>>> name.lower()
‘tanmay singh’
upper()Returns a copy of string converted to uppercase.>>> name=”tanmay singh”
>>> name.upper()
‘TANMAY SINGH’
title()Returns a copy of string converted to title case.>>> name=”tanmay singh”
>>> name.title()
‘Tanmay Singh’
swapcase()Converts and returns all uppercase characters to lowercase and vice-versa.>>> name=”Tanmay Singh”
>>> name.swapcase()
‘tANMAY sINGH’
count()Returns the number of times a specified value occurs in a string>>> name=”tanmay singh”
>>> name.count(‘a’)
2
find()Returns the first occurrence of given string/character in the string.>>> name=”tanmay singh”
>>> name.find(‘y’)
5
index(char)Search and returns the first occurrence of given character or substring.>>> name=”tanmay singh”
>>> name.index(‘y’)
5
lstrip() / lstrip(char)Returns a copy of the string with leading characters removed. By default removed space.>>> data = ‘ hello ‘
>>> data.lstrip()
‘hello ‘
>>> mesg = ‘aaaRAMaaa’
>>> mesg.lstrip(‘a’)
‘RAMaaa’
rstrip()/ rstrip(char)Returns a copy of the string with trailing characters removed. By default removed space.>>> data = ‘ hello ‘
>>> data.rstrip()
‘ hello’
>>> mesg = ‘aaaRAMaaa’
>>> mesg.rstrip(‘a’)
‘aaaRAM’
strip()Returns a copy of the string with leading and trailing characters removed.>>> data = ‘ hello ‘
>>> data.strip()
‘hello’
>>> mesg = ‘aaaRAMaaa’
>>> mesg.strip(‘a’)
‘RAM’
replace()Returns a copy of the string with replaced old substring with new substring.>>> name=”tanmay singh”
>>> name.replace(‘singh’, ‘verma’)
‘tanmay verma’
split()Splits the string at the specified separator, and returns a list.
Default separator is space ‘ ‘.
Separator character is ignored, i.e not available in the list.
>>> name=”tanmay singh”
>>> name.split(‘n’)
[‘ta’, ‘may si’, ‘gh’]

>>> message = “Hello dear welcome to mycstutorial.in”
>>> message.split()
[‘Hello’, ‘dear’, ‘welcome’, ‘to’, ‘mycstutorial.in’]
partition()Splits the string at the specified separator, and returns a tuple.
Tuple is having only three elements, characters before separator, separator and characters after separator.
>>> name=”tanmay singh”
>>> name.partition(‘n’)
(‘ta’, ‘n’, ‘may singh’)

>>> message = “Hello dear welcome to mycstutorial.in”
>>> message.partition(‘ ‘)
(‘Hello’, ‘ ‘, ‘dear welcome to mycstutorial.in’)
join()Returns a string in which the string elements have been joined by a string separator.  Eg. ‘-’.join(‘anjeev” => ‘a-n-j-e-e-v’>>> name=”tanmay singh”
>>> ‘#’.join(name)
‘t#a#n#m#a#y# #s#i#n#g#h’

>>> “–He–“.join(name)
‘t–He–a–He–n–He–m–He–a–He–y–He– –He–s–He–i–He–n–He–g–He–h’
ord(char)Returns the ordinal value (ASCII) of given character.>>> ord(‘a’)
97
>>> ord(‘A’)
65
>>> ord(‘#’)
35
chr(num)Returns character represented by inputted ASCII number.>>> chr(35)
‘#’
>>> chr(65)
‘A’
>>> chr(97)
‘a’
Read More

Chapter 7 : Functions | class 11th | revision notes computer science

Class 11 Computer Science Chapter 7 Functions in Python Notes

5.1 Definition: Functions are the subprograms that perform specific task. Functions are the small modules.

5.2 Types of Functions:
There are two types of functions in python:

  1. Library Functions (Built in functions)
  2. Functions defined in modules
  3. User Defined Functions
Functions in Python Class 11 Notes
  1. Library Functions: These functions are already built in the python library.
  2. Functions defined in modules: These functions defined in particular modules. When you want to use these functions in program, you have to import the corresponding module of that function.
  3. User Defined Functions: The functions those are defined by the user are called user defined functions.
  1. Library Functions in Python:
    These functions are already built in the library of python.
    For example: type( ), len( ), input( ) etc.
  2. Functions defined in modules:
    a. Functions of math module:

    To work with the functions of math module, we must import math module in program.

    import math
Functions in Python Class 11 Notes

b. Function in random module:
random module has a function randint( ).

  • randint( ) function generates the random integer values including start and end values.
  • Syntax: randint(start, end)
  • It has two parameters. Both parameters must have integer values.

Example:
import random
n=random.randint(3,7)
*The value of n will be 3 to 7.

USER DEFINED FUNCTIONS:
The syntax to define a function is:

Functions in Python Class 11 Notes

Where:

  • Keyword def marks the start of function header.
  • A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
  • Parameters (arguments) through which we pass values to a function. They are optional.
  • A colon (:) to mark the end of function header.
  • One or more valid python statements that make up the function body. Statements must have same indentation level.
  • An optional return statement to return a value from the function.

Example:
def display(name):
print(“Hello ” + name + ” How are you?”)

5.3 Function Parameters:
A functions has two types of parameters:

1. Formal Parameter: Formal parameters are written in the function prototype and function header of the definition. Formal parameters are local variables which are assigned values from the arguments when the function is called.

2. Actual Parameter: When a function is called, the values that are passed in the call are called actual parameters. At the time of the call each actual parameter is assigned to the corresponding formal parameter in the function definition.

Example :
def ADD(x, y):
#Defining a function and x and y are formal parameters
z=x+y print(“Sum = “, z)
a=float(input(“Enter first number: ” ))
b=float(input(“Enter second number: ” ))
ADD(a,b) #Calling the function by passing actual parameters
In the above example, x and y are formal parameters. a and b are actual parameters.

5.4 Calling the function:
Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.

Syntax:
function-name(parameter)

Example:
ADD(10,20)

OUTPUT:
Sum = 30.0

How function works?

Functions in Python Class 11 Notes

The return statement:
The return statement is used to exit a function and go back to the place from where it was called.
There are two types of functions according to return statement:

a. Function returning some value (non-void function) :
Syntax:
return expression/value
Example-1: Function returning one value
def my_function(x):
return 5 * x

Example-2 Function returning multiple values:
def sum(a,b,c):
return a+5, b+4, c+7
S=sum(2,3,4)
# S will store the returned values as a tuple
print(S)

OUTPUT:
(7, 7, 11)

Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7 s1, s2, s3=sum(2, 3, 4)
# storing the values separately print
(s1, s2, s3)

OUTPUT:
7 7 11

b. Function not returning any value (void function) : The function that performs some operations but does not return any value, called void function.
def message():
print(“Hello”)
m=message()
print(m)

OUTPUT:
Hello
None

5.5 Scope and Lifetime of variables:
Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function is not visible from outside. Hence, they have a local scope. There are two types of scope for variables:
1. Local Scope
2. Global Scope

1. Local Scope: Variable used inside the function. It can not be accessed outside the function. In this scope, The lifetime of variables inside a function is as long as the function executes. They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls.

2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a variable is the period throughout which the variable exits in the memory.

Example:
def my_func():
x = 10
print(“Value inside function:”,x)
x = 20
my_func()
print(“Value outside function:”,x)

OUTPUT:
Value inside function: 10
Value outside function: 20

Here, we can see that the value of x is 20 initially. Even though the function my_func()changed the value of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function) from the one outside. Although they have same names, they are two different variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a global scope.
We can read these values from inside the function but cannot change (write) them. In order to modify the value of variables outside the function, they must be declared as global variables using the keyword global.

5.6 RECURSION:
Definition: A function calls itself, is called recursion.
5.6.1Python program to find the factorial of a number using recursion:
Program:
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
num=int(input(“enter the number: “))
if num < 0:
print(“Sorry, factorial does not exist for negative numbers”)
elif num = = 0:
print(“The factorial of 0 is 1”)
else:
print(“The factorial of “,num,” is “, factorial(num))

OUTPUT:
enter the number: 5
The factorial of 5 is 120

5.6.2 Python program to print the Fibonacci series using recursion:
Program:
def fibonacci(n):
if n<=1:
return n
else:
return(fibonacci(n-1)+fibonacci(n-2))

num=int(input(“How many terms you want to display: “))
for i in range(num):
print(fibonacci(i),” “, end=” “)

OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13

5.6.3 Binary Search using recursion:
Note: The given array or sequence must be sorted to perform binary search.

Functions in Python Class 11 Notes

Program:
def Binary_Search(sequence, item, LB, UB):
if LB>UB:
return -5
# return any negative value
mid=int((LB+UB)/2)
if item==sequence[mid]:
return mid
elif item<sequence[mid]:
UB=mid-1
return Binary_Search(sequence, item, LB, UB)
else:
LB=mid+1
return Binary_Search(sequence, item, LB, UB)

L=eval(input(“Enter the elements in sorted order: “))
n=len(L)
element=int(input(“Enter the element that you want to search :”))
found=Binary_Search(L,element,0,n-1)
if found>=0:
print(element, “Found at the index : “,found)
else:
print(“Element not present in the list”)


5.7 lambda Function:
lambda keyword, is used to create anonymous function which doesn’t have any name.
While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword.
Syntax:
lambda arguments: expression

Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned.
Lambda functions can be used wherever function objects are required.
Example:
value = lambda x: x * 4
print(value(6))
Output:
24

In the above program, lambda x: x * 4 is the lambda function. Here x is the argument and x * 4 is the expression that gets evaluated and returned.

Programs related to Functions in Python topic:

  1. Write a python program to sum the sequence given below. Take the input n from the user.
Functions in Python Class 11 Notes

Solution:
def fact(x):
j=1
res=1
while j<=x:
res=res*j
j=j+1
return res
n=int(input(“enter the number : “))
i=1
sum=1
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)

  1. Write a program to compute GCD and LCM of two numbers
    def gcd(x,y):
    while(y):
    x, y = y, x % y
    return x
    https://pythonschoolkvs.wordpress.com/ Page 49
    def lcm(x, y):
    lcm = (x*y)//gcd(x,y)
    return lcm

    num1 = int(input(“Enter first number: “))
    num2 = int(input(“Enter second number: “))

    print(“The L.C.M. of”, num1,”and”, num2,”is”, lcm(num1, num2))
    print(“The G.C.D. of”, num1,”and”, num2,”is”, gcd(num1, num2))
Read More

Chapter 6 : Flow of Control | class 11th | revision notes computer science

Flow of Control


Topics:

  • Flow of control: Introduction, use of indentation, sequential flow, conditional and iterative flow control
  • Conditional statements: if, if-else, if-elif-else, flowcharts, simple programs: e.g.: absolute value, sort 3 numbers and divisibility of a number
  • Iterative statements: for loop, range function, while loop, flowcharts, nested loops, suggested programs: generating pattern, summation of series, finding the factorial of a positive number.
  • Jump Statement – break and continue statements

Introduction

The order of execution of the statements in a program is known as flow of control. The flow of control can be implemented using control structures. Python supports two types of control structures—Selection and Repetition.

Indentation

Leading whitespace (spaces and tabs) at the beginning of a statement is called indentation.

Python uses indentation for block as well as for nested block structures.

In Python, the same level of indentation associates statements into a single block of code. The interpreter checks indentation levels very strictly and throws up syntax errors if indentation is not correct. It is a common practice to use a single tab for each level of indentation.

Types of Flow of Control

There are three types of flow of control –

a) Sequential flow of control

In Sequential flow of control execution of statement takes place in a sequence i.e. top to bottom approach.

num = int (input ("Enter Number " ))

num = num * 5

print (num) 

b) Conditional flow of control

Conditional flow of control is use to execute set of statements on the basis of the conditions.

num = int(input("Enter a number : "))
if num % 5 == 0:
   print(num, "is divisible by 5")
else:
   print(num, "is not divisible by 5")

c) Iterative flow of control

iterative flow of control means repetition. It execute the set of statements till the condition is true.

Conditional statements:

The if Statement

An if statement tests a particular condition; if the condition evaluates to true, then set of statements executed otherwise does not.

 if <conditional expression > :
   statement
   [statements] 

# Write a program to check given character is an alphabet ‘A’.

ch = input("Enter a character : ")
if ch == 'A' :
   print("You entered alphabet A")
if ch != 'A' :
    print("You entered alphabet A")

The if-else Statement

An if statement tests a particular condition; if the condition evaluates to true, then it carries out the  statements indented below if and in case condition evaluate to false, it carries out statements indented below else.

 if <conditional expression > :
    statement
    [statements]
 else :
    statement
    [statements] 

# Write a program to check given character is an upper alphabet.

ch = input("Enter a character : ")
if ch >= 'A' and ch <= 'Z':
   print("You have entered Upper alphabet")
else:
    print("You have entered other than Upper Alphabet")

The if-elif-else

An if-elif statement provide a facility to tests a condition with else ;

Syntax – 1

 if <conditional expression > :
   statement
   [statements]
 elif <conditional-expression> :
   statement
   [statements] 

Syntax – 2

 if <conditional expression > :
   statement
   [statements]
 elif <conditional-expression>:
   statement
   [statements]
 else:
   statement
   [statements] 

# Write a program to check given character is an upper alphabet, lower alphabet, digits or other symbol.

ch = input("Enter a character : ")
if ch >= 'A' and ch <= 'Z':
   print("You have entered Upper alphabet")
elif ch >= 'a' and ch <= 'z':
   print("You have entered Lower alphabet")
elif ch >= '0' and ch <= '9':
   print("You have entered Digit")
else:
    print("You have entered Symbol")

Nested if statements

An if inside the another if, called Nested if’s statement.

An if-else inside the another if or else called nested if-else.

 if <conditional expression > :
   if <condition>:
       statements
   else:
       statements
 else :
   if <condition>:
       statements
   else:
       statements 

Sample Programs :

# Absolute value

num = int(input("Enter a Number : "))
if num > 0 :
   print("Absolute Value is ", num)
elif num < 0:
   print("Absolute Value is ", num * -1)
else:
    print("You have entered ", num)

# Sort 3 numbers

num1 = int(input("Enter a Number 1 : "))
num2 = int(input("Enter a Number 2 : "))
num3 = int(input("Enter a Number 3 : "))
if num1 < num2 and num1 < num3:
   if num2 < num3:
       print(num1, num2, num3)
   else:
       print(num1, num3, num2)
elif num2 < num1 and num2 < num3:
   if num1 < num3:
       print(num2, num1, num3)
   else:
       print(num2, num3, num1)
else:
   if num2 < num1:
       print(num3, num2, num1)
   else:
       print(num3, num1, num2)

# Divisibility of a number

num1 = int(input("Enter a Number 1 : "))
num2 = int(input("Enter a Number 2 : "))
if num1 % num2 == 0 :
   print(num1 "is divisible by", num2)
elif num2 % num1 == 0:
   print(num2, "is divisible by", num1)
else:
    print(num1, 'and', num2,'neighter factor nor multiples')

Iterative / Repetitive Statements / Looping

range() function

for loop

while loop,

Flow Charts

Nested loops,

Suggested Programs:

# Python programs for generating pattern

Pattern-1

*

* *

* * *

* * * *

* * * * *

# Python Programs for summation of series.

# Finding the factorial of a positive number.

Jump Statement – break and continue statements

break statement

continue statement

Read More

Chapter 5 : Getting Started with Python | class 11th | revision notes computer science

Getting Started with Python Programming Language


Topics:


  • Familiarization with the basics of Python programming:
    • Introduction to Python,
    • Features of Python
    • Advantages & Disadvantages
    • Installation of Python
  • Working with Python
  • Execution modes:
    • Interactive mode and
    • Script mode
    • Executing a simple “hello world” program

Introduction

Python is an open-source, object-oriented, high-level programming language developed by Guido Van Rossum in 1990, and released in 1991, at the National Research Institute for Mathematics, Netherlands.

Presently owned by Python Software Foundation (PSF).

Python is influenced by two programming languages:

ABC language, a teaching language created to replace the programming language BASIC.

Modula-3 is a language that preserves the power of a systems programming language

Python is a general-purpose programming language that can be used to build any kind of program that does not require direct access to the computer’s hardware.


Characteristics of Python

  • It supports functional and structured programming methods as well as OOP.
  • It can be used as a scripting language or can be compiled to byte-code for building large applications.
  • It provides very high-level dynamic data types and supports dynamic type checking.
  • It supports automatic garbage collection.
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
  • It can be used to develop a large application with small codes.

Python – Advantages

It has become popular because of its salient features –

  • Easy – loosely typed OOP language with few keywords and simple English like structure, and is easy to learn
  • Takes less time to develop the program, typically 3-5 times shorter than equivalent Java programs. Due to Built-in high-level data types, and dynamic typing.
  • Free and Open Source, High-Level, Portable, and Object-Oriented
  • Extensible & Embeddable
  • Interpreted – Python is interpreted, interactive, and directly executed with pre-compiled code. This means that it is processed at runtime by the interpreter and you need not compile your program before executing it.
  • Large Standard Library and support GUI Programming (using MFC, Tkinter)
  • Python is used for both scientific and non-scientific programming.
  • Python is a case-sensitive programming language.

Python – Disadvantages

It has some minus i.e. disadvantages –

  • Not the fastest Languages – Python is an interpreted language, not a compiled language. It converts python source code into the internal bytecode, which is then executed by the Python interpreter. It makes slower than fully compiled languages.
  • Not strong as Type Binding – Python does not strongly bind with data types i.e. type.
  • Not easy to convert code into other languages – It is not easy to translate a Python program into other programming languages because Python does not have strong syntax.

Installation of Python


Working with Python:

  1. Python Interpreter: Python interpreter must be installed on your computer, to write and execute a Python program. It is also called a Python shell.
  2. >>> : Symbol >>> is called Python prompt.
  3. Python prompt: Python prompt, which indicates that the interpreter is ready to receive instructions. We can type commands or statements on this prompt for execution.

Execution Mode

There are two ways to run a program using the Python interpreter:
a) Interactive mode and b) Script mode

(A) Interactive Mode
In the interactive mode, we can type a Python statement on the >>> prompt directly. As soon as we press enter, the interpreter executes the statement and displays the result(s)

Executing code in Interactive mode

Advantages of using interactive mode :

It is convenient for testing a single line code for instant execution.

The disadvantage of using Interactive mode :

In the interactive mode, we cannot save the statements for future use and we have to retype the statements to run them again.

(B) Script Mode
In the script mode, we can write a Python program in a file, save it and then use the interpreter to execute the program from the file.

  • Python program files have a .py extension.
  • Python programs are also known as scripts.
  • Python has a built-in editor called IDLE which can be used
    to create programs / scripts.

Python IDLE :

IDLE: Integrated Development and Learning Environment

To Create a Program

  • First open the IDLE,
  • Click File>New File to create a new file,
  • then write your program on that file and
  • save it with the desired name.
    By default, the Python scripts are saved in the Python installation folder.

To run/execute a program in script mode:

  • Open the program using an IDLE editor
  • In IDLE, go to [Run]->[Run Module] to execute the program
  • The output appears on the shell.
Executing program in Script Mode
Read More

Chapter 4 : Introduction to Problem Solving | class 11th | revision notes computer science

Introduction to Problem Solving

Notes

Topics:

  • Introduction to problem solving:
    • Steps for problem solving ( analysing the problem, developing an algorithm, coding, testing and debugging).
  • Representation of algorithms using
    • flow chart and
    • pseudo code,
  • Decomposition

Introduction

Computers is machine that not only use to develop the software. It is also used for solving various day-to-day problems.

Computers cannot solve a problem by themselves. It solve the problem on basic of the step-by-step instructions given by us.

Thus, the success of a computer in solving a problem depends on how correctly and precisely we –

  • Identifying (define) the problem
  • Designing & developing an algorithm and
  • Implementing the algorithm (solution) do develop a program using any programming language.

Thus problem solving is an essential skill that a computer science student should know.

Steps for Problem Solving-

1. Analysing the problem

Analysing the problems means understand a problem clearly before we begin to find the solution for it. Analysing a problem helps to figure out what are the inputs that our program should accept and the outputs that it should produce.

2. Developing an Algorithm

It is essential to device a solution before writing a program code for a given problem. The solution is represented in natural language and is called an algorithm.

Algorithm: A set of exact steps which when followed, solve the problem or accomplish the required task.

3. Coding

Coding is the process of converting the algorithm into the program which can be understood by the computer to generate the desired solution.

You can use any high level programming languages for writing a program.

4. Testing and Debugging

The program created should be tested on various parameters.

  • The program should meet the requirements of the user.
  • It must respond within the expected time.
  • It should generate correct output for all possible inputs.
  • In the presence of syntactical errors, no output will be obtained.
  • In case the output generated is incorrect, then the program should be checked for logical errors, if any.

Software Testing methods are

  • unit or component testing,
  • integration testing,
  • system testing, and
  • acceptance testing

Debugging – The errors or defects found in the testing phases are debugged or rectified and the program is again tested. This continues till all the errors are removed from the program.

Algorithm

Algorithm is a set of sequence which followed to solve a problem.

Algorithm for an activity ‘riding a bicycle’:
1) remove the bicycle from the stand,
2) sit on the seat of the bicycle,
3) start peddling,
4) use breaks whenever needed and
5) stop on reaching the destination.

Algorithm for Computing GCD of two numbers:

Step 1: Find the numbers (divisors) which can divide the given numbers.

Step 2: Then find the largest common number from these two lists.

A finite sequence of steps required to get the desired output is called an algorithm. Algorithm has a definite beginning and a definite end, and consists of a finite number of steps.

Characteristics of a good algorithm

  • Precision — the steps are precisely stated or defined.
  • Uniqueness — results of each step are uniquely defined and only depend on the input and the result of the preceding steps.
  • Finiteness — the algorithm always stops after a finite number of steps.
  • Input — the algorithm receives some input.
  • Output — the algorithm produces some output.

While writing an algorithm, it is required to clearly identify the following:

  • The input to be taken from the user.
  • Processing or computation to be performed to get the desired result.
  • The output desired by the user.

Representation of Algorithms

There are two common methods of representing an algorithm —

  • Flow chart
  • Pseudocode

Flowchart — Visual Representation of Algorithms

A flowchart is a visual representation of an algorithm. A flowchart is a diagram made up of boxes, diamonds and other shapes, connected by arrows. Each shape represents a step of the solution process and the arrow represents the order or link among the steps. There are standardised symbols to draw flowcharts.

Start/End – Also called “Terminator” symbol. It indicates where the flow starts and ends.

Process – Also called “Action Symbol,” it represents a process, action, or a single step.
Decision – A decision or branching point, usually a yes/no or true/ false question is asked, and based on the answer, the path gets split into two branches.

Input / Output – Also called data symbol, this parallelogram shape is used to input or output data.

Arrow – Connector to show order of flow between shapes.



Question: Write an algorithm to find the square of a number.
Algorithm to find square of a number.
Step 1: Input a number and store it to num
Step 2: Compute num * num and store it in square
Step 3: Print square

The algorithm to find square of a number can be represented pictorially using flowchart

Pseudocode

A pseudocode (pronounced Soo-doh-kohd) is another way of representing an algorithm. It is considered as a non-formal language that helps programmers to write algorithm. It is a detailed description of instructions that a computer must follow in a particular order.

  • It is intended for human reading and cannot be executed directly by the computer.
  • No specific standard for writing a pseudocode exists.
  • The word “pseudo” means “not real,” so “pseudocode” means “not real code”.

Keywords are used in pseudocode:

  • INPUT
  • COMPUTE
  • PRINT
  • INCREMENT
  • DECREMENT
  • IF/ELSE
  • WHILE
  • TRUE/FALSE

Question : Write an algorithm to calculate area and perimeter of a rectangle, using both pseudocode and flowchart.

Pseudocode for calculating area and perimeter of a rectangle.

INPUT length
INPUT breadth
COMPUTE Area = length * breadth
PRINT Area
COMPUTE Perim = 2 * (length + breadth)
PRINT Perim

The flowchart for this algorithm

Benefits of Pseudocode

  • A pseudocode of a program helps in representing the basic functionality of the intended program.
  • By writing the code first in a human readable language, the programmer safeguards against leaving out any important step.
  • For non-programmers, actual programs are difficult to read and understand, but pseudocode helps them to review the steps to confirm that the proposed implementation is going to achieve the desire output.

Flow of Control:

The flow of control depicts the flow of process as represented in the flow chart. The process can flow in

  • Sequence
  • Selection
  • Repetition

Sequence

In a sequence steps of algorithms (i.e. statements) are executed one after the other.

Selection

In a selection, steps of algorithm is depend upon the conditions i.e. any one of the alternatives statement is selected based on the outcome of a condition.

Conditionals are used to check possibilities. The program checks one or more conditions and perform operations (sequence of actions) depending on true or false value of the condition.

Conditionals are written in the algorithm as follows:
If is true then
steps to be taken when the condition is true/fulfilled
otherwise
steps to be taken when the condition is false/not fulfilled

Question : Write an algorithm to check whether a number is odd or even.
• Input: Any number
• Process: Check whether the number is even or not
• Output: Message “Even” or “Odd”

Pseudocode of the algorithm can be written as follows:
PRINT “Enter the Number”
INPUT number
IF number MOD 2 == 0 THEN
PRINT “Number is Even”
ELSE
PRINT “Number is Odd”

Repetition

Repetitions are used, when we want to do something repeatedly, for a given number of times.

Question : Write pseudocode and draw flowchart to accept numbers till the user enters 0 and then find their average.

Pseudocode is as follows:

Step 1: Set count = 0, sum = 0
Step 2: Input num
Step 3: While num is not equal to 0, repeat Steps 4 to 6
Step 4: sum = sum + num
Step 5: count = count + 1
Step 6: Input num
Step 7: Compute average = sum/count
Step 8: Print average

The flowchart representation is

flow_chart_repetition

Coding

Once an algorithm is finalised, it should be coded in a high-level programming language as selected by the programmer. The ordered set of instructions are written in that programming language by following its syntax.

The syntax is the set of rules or grammar that governs the formulation of the statements in the language, such as spelling, order of words, punctuation, etc.

Source Code: A program written in a high-level language is called source code.

We need to translate the source code into machine language using a compiler or an interpreter so that it can be understood by the computer.

Decomposition

Decomposition is a process to ‘decompose’ or break down a complex problem into smaller subproblems. It is helpful when we have to solve any big or complex problem.

  • Breaking down a complex problem into sub problems also means that each subproblem can be examined in detail.
  • Each subproblem can be solved independently and by different persons (or teams).
  • Having different teams working on different sub-problems can also be advantageous because specific sub-problems can be assigned to teams who are experts in solving such problems.

Once the individual sub-problems are solved, it is necessary to test them for their correctness and integrate them to get the complete solution.

Read More

Chapter 3 : Emerging Trends | class 11th | revision notes computer science

Emerging Trends – Notes

Emerging Trends

Emerging trends

Emerging trends are the state-of-the-art technologies, which gain popularity and set a new trend among users.

New technologies and initiatives emerge with each passing day. Some of these new technologies prosper and persist over time, gaining attention from users. Emerging trends are the state-of-the-art technologies, which gain popularity and set a new trend among users.


Artificial Intelligence (AI)

Artificial Intelligence endeavours to simulate the natural intelligence of human beings into machines, thus making them behave intelligently.

An intelligent machine is supposed to imitate some of the cognitive functions of humans like learning, decision making and problem solving.

Knowledge Base – A knowledge base is a store of information consisting of facts, assumptions and rules which an AI system can use for decision making.

For example – Google Maps guiding the fastest route on the basis of real data, uploading photo on social sites and your friends come to know, Siri, Google Now, Cortana, Alexa etc.-


Machine Learning

Machine Learning is a subsystem of Artificial Intelligence, wherein computers have the ability to learn from data using statistical techniques, without being explicitly programmed by a human being and make predictions.

Models are the algorithms that used in Machine Learning.

Firstly models are trained and tested using a training data and testing data, respectively. After successive trainings, once these models are able to give results to an acceptable level of accuracy, they are used to make predictions about new and unknown data.


Natural Language Processing (NLP)

Natural Language Processing (NLP) deals with the interaction between human and computers using human spoken languages, such as Hindi, English, etc.

An NLP system can perform text-to-speech and speech-to-text conversion.

Application of NLP :

  • Search the web or operate or control our devices using our voice.
  • Predictive typing feature of search engine or smartphone, which suggesting the next word while typing.
  • Spell checking features.
  • Automated customers service, computer interact with human to solve their queries or complaints.
  • Translate texts from one language to another with fair amount of correctness.

Immersive Experiences

Immersive experiences allow us to visualise, feel and react by stimulating our senses. It enhances our interaction and involvement, making them more realistic and engaging.

Immersive experiences have been used in the field of training, such as driving simulators , flight simulator and so on.

Immersive experience can be achieved by using

  • Virtual Reality (VR) and
  • Augmented Reality (AR)

(A) Virtual Reality

Virtual Reality (VR) is a three-dimensional, computer-generated situation that simulates the real world. The user can interact with and
explore that environment by getting immersed in it while interacting with the objects and other actions of the user.

At present, it is achieved with the help of VR Headsets.

Applications of VR :- Gaming, military training, medical procedures, entertainment, social science and psychology, engineering and
other areas where simulation is needed for a better understanding and learning.

(B) Augmented Reality

The superimposition of computer generated perceptual information over the existing physical surroundings is called as Augmented Reality (AR).

Users can access information about the nearest places with reference to their current location. They can get information about places and choose on the basis of user reviews.

Location-based AR apps are major forms of AR apps, used by travellers to access real-time information of historical places just by pointing their camera view finder to subjects.


Robotics :-

Robotics is an interdisciplinary branch of technology requiring applications of mechanical engineering, electronics, and computer science, among others. Robotics is primarily concerned with the design, fabrication, operation, and application of robots.

Robots :-

A robot is basically a machine capable of carrying out one or more tasks automatically with accuracy and precision.

Unlike other machines, a robot is programmable by a computer, which means it can follow the instructions given through computer programs.

Robots were initially conceptualised for doing repetitive industrial tasks that are boring or stressful for humans or were labour intensive.

Types of Robots:

  • Wheeled robots –

NASA’s Mars Exploration Rover (MER) mission is a robotic space mission to study about the planet Mars

  • Legged robots,
  • Manipulators,
  • Drone –

A drone is an unmanned aircraft which can be remotely controlled or can fly autonomously through software-controlled flight plans in their embedded systems, working in conjunction with onboard sensors and GPS.

Used in journalism, filming and aerial photography, shipping or delivery at short distances, disaster management, search and rescue
operations, healthcare, geographic mapping and structural safety inspections, agriculture, wildlife monitoring or pooching, besides law-enforcement and border patrolling

  • Humanoids – Robots that resemble humans are known as humanoids.
Sophia
Sophia

Sophia is a humanoid that uses artificial intelligence, visual data processing, facial recognition and also imitates human gestures and facial expressions.

Big Data

The generation of data sets of enormous volume and complexity called Big Data.

Big data is generated by a billion Internet users. Around 2.5 quintillion bytes of data are created each day, and the pace is increasing with the continuous evolution of the Internet of Things (IoT).

Processing of Big Data

Big data cannot be processed and analyzed using traditional data processing tools (DBMS) as the data is not only voluminous but also unstructured like our posts, instant messages and chats, photographs that we share through various sites, our tweets, blog articles, news items, opinion polls and their comments, audio/video chats, etc.

Challenges with Big Data

Big Data not only represents voluminous data, it also involves various challenges like integration, storage, analysis, searching, processing, transfer, querying and visualization of such data.

Read More

Chapter 2 : Encoding Schemes and Number System | class 11th | revision notes computer science

Number Systems & Encoding Scheme


Topics are covered in this post :

  • Number system:
    • Binary, Octal, Decimal and Hexadecimal number system
    • Conversion between number systems.
  • Encoding schemes:
    • ASCII, ISCII and UNICODE (UTF8, UTF32)

Number Systems

A number system is a method to represent (write) numbers. Every number system has a set of unique characters or literals. The count of these literals is called the radix or base of the number system.

Number systems are also called positional number system because the value of each symbol, i.e. digit or alphabet, depends upon its position within the number.

Number may also have a fractional part similar to decimal numbers used by us.

The symbol at the right most position in the integer part in a given number has position 0. The value of position (also called position value) in the integer part increases from right to left by 1.

On the other hand, the first symbol in the fraction part of the number has position number –1, which decreases by 1 while reading fraction part from left to right.

For Examples

568.92
210.-1-2
5 x 1026 x 1018 x 100.9 x 10-12 x 10-2

Representation of Number in Decimal Systems

Types of Number Systems

The four different types of number systems are used in computer system. These are –

  1. Decimal Number Systems
  2. Binary Number Systems
  3. Octal Number Systems
  4. Hexadecimal Number Systems

Decimal Number Systems

The decimal number system is the most common number systems. It is known as base-10 Number system. It has 10 digits i.e. unique symbols (0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ).

For Examples : Number 568.92 represented as

568.92
210.-1-2
5 x 1026 x 1018 x 100.9 x 10-12 x 10-2
500608.0.90.02

Decimal Number Systems


Binary Number Systems

A number systems which has only two unique symbols (bi) 0 & 1, with base 2 , is called Binary Number Systems. For example 111001, 10011.111, 111001.1101.

Decimal NumbersBinary Representation (4 – bits)
00000
10001
20010
30011
40100
50101
60110
70111
81000
91001

Binary representation of Decimal Number digits (0 to 9)


Octal Number Systems

Octal number system is called base-8 system as it has total eight digits (0-7), and positional value is expressed in powers
of 8. Three binary digits i.e. 8 = 23 are sufficient to represent any octal number in binary number.

Example : (536)8 , (105)8

Why (943)8 is not a valid octal number?

Ans: In 943, 9 is not a valid octal number digit. Only 0,1,2,3,4,5,6 & 7 are the valid octal digits use to represent any octal number.

Why Octal Number System?

When you represent a large decimal number, binary numbers becomes so large and it is difficult to manage. So that Octal number system was developed. Octal number system is a compact representation of the binary numbers.

Octal DigitBinary Representation (3 – bits)
0000
1001
2010
3011
4100
5101
6110
7111

Binary representation of Octal digits (0 to 7)


Hexadecimal Number Systems

Hexadecimal number systems is consists of 16 unique symbols (0 – 9, A–F), and is called base- 16 system. In Hexadecimal number system Note here that the decimal numbers 10 through 15 are represented by the letters A through F.

Hexadecimal numbers are also used for compact representation of binary numbers.

In hexadecimal system, each alphanumeric digit is represented as a group of 4 binary digits because 4 bits (16 = 24) are sufficient to represent 16 alphanumeric symbols.

Examples of Hexadecimal numbers are (23A.05)16, (1C3)16, (619B.A)16

Representation of Decimal, Hexadecimal, Octal , and Binary

Decimal NumberHexadecimal SymbolOctal RepresentationBinary Representation (4 – bits)
0000000
1110001
2220010
3330011
4440100
5550101
6660110
7770111
88101000
99111001
10A121010
11B131011
12C141100
13D151101
14E161110
15F171111

Decimal -> Hexadecimal -> Octal -> Binary Representation


Conversion between Number Systems

Converting a number from one Base to another
Conversion from decimal number system to Other number system

To convert a decimal number to other number system, repeated division method is used.
Decimal to Binary conversion:
To convert a decimal number to binary number, repeated division method is used.

Repeatedly divide the decimal number with base 2, record all remainders in reverse order.
Example:

Convert (150)10 to Binary Number

BaseNumberRemainder
2371LSB (Least Significant Bit)
2180^
291|
240|
220|
211MSB (Most Significant Bit)
0

(150)10 =(100101)2

Answer : (150)10 =(100101)2

Decimal to Octal conversion:
To convert a decimal number to octal number, repeated division method can be used.

Repeatedly divide the decimal number with base 8, record all remainders in reverse order.
Example:

Convert (150)10 to Octal

BaseNumberRemainder
81506LSB (Least Significant Bit)
8182^
821MSB (Most Significant Bit)
0

(150)10 =(126)8


Answer : (150)10 =(226)8

Decimal to Hexadecimal conversion
To convert a decimal number to Hexadecimal number, we can do repeated division method is used.

Repeatedly divide the decimal number with base 16, record all remainders in reverse order.

Example:

Convert (170)10 to Hexadecimal

BaseNumberRemainder
161655LSB (Least Significant Bit)
161010 -> A^ MSB (Most Significant Bit)
0

(165)10 =(A5)16

Answer : (165)10 =(A5)16

Converting Binary, Octal and Hexadecimal Numbers to Decimal Number


Converting Binary to Decimal number

Start from the rightmost bit. Multiply each bit by its positional value and then take the sum.

Example:-
Convert the Binary number 11011 to its Decimal equivalent.
1 x 24 + 1 x 23 + 0 x 22 + 1 x 21 + 1 * 20
16 + 8 + 0 + 2 + 1 = (27)10

Converting Octal number to Decimal number

Start from the rightmost bit. Multiply each bit by its positional value and then take the sum.
Example

Convert the Octal number 341 to its Decimal equivalent.
= 3 x 82 + 4 x 8+ 1 x 80
= 192 + 32 + 1

= (225)10

Converting Hexadecimal number to Decimal number
Start from the rightmost bit. Multiply each bit by its positional value and then take the sum.

Example

Convert the Hexadecimal number (21A)16 to its Decimal equivalent.

21A

= 2 x 162 + 1 x 161 + A x 160
= 2 x 162 + 1 x 161 + 10 * 160
= 512 + 16 + 10

= (538)10

Arithmetic Operation with Binary Numbers:

Binary Addition
Computers work with binary numbers 0 and 1. They understand only binary numbers.
There are 5 basic cases for binary addition. These are :-

  1. 0+0 = 0
  2. 0+1 = 1
  3. 1+0 = 1
  4. 1+1 = 10

i.e , binary 1+ binary 1 equals 0 with a carry 1

  1. 1+1+1 = 11

i.e, binary 1 + binary 1 equals 1 with a carry 1

Encoding Scheme

Character / String Representation :

A computer can handle numeric and non numeric data like letters, punctuation marks and other special characters. Some predefined codes are used to represent numeric and non numeric characters.

Standards encoding schemes are :-

ASCII
ASCII stands for American Standard Code for Information Interchange. ASCII-7 is a 7-bit code and can represent 128 characters. Out of 7 bits, 3 are zone bits and 4 are numeric bits.

ASCII-8 can represent 256 characters. It is an extended form of ASCII-7.

ISCII: (Indian Standard Code for Information Interchange)

A lot of efforts have done to facilitate the use of Indian languages on computers. In 1991, the Bureau of Indian Standards adopted the ISCII. It is an 8 bit code which allows English and Indian Scripts alphabets to be used simultaneously. Characters coded in ISCII need 8 bits for each character.

Unicode

Unicode is a new universal coding standard adopted by all new platforms. It is promoted by Unicode Consortium which is a non profit organization. Unicode provides a unique number for every character irrespective of the platform, program and the language. It is a character coding system designed to support the worldwide interchange, processing, and display of the written texts of the diverse languages.

Read More

Chapter 1 Computer System | Important Notes Computer System | class 11th revision notes

Chapter 1 Computer System IP 11 | Important Notes Computer System

What is Computer System?

Combination of Software and Hardware together is called Computer System. A computer is a device (hardware) that can perform operations in accordance with a set of instructions called program (software).

Component of Computer System

Since a computer follows Input-Process-Output cycle, thus components of computer are categorized in three parts:

  1. Input Devices
  2. Central Processing Unit
  3. Output Devices

The basic component structure of computer is as shown below:

As shown in diagram various part of computer interact together to make the computer work, you input data to computer by using input devices and the CPU acts upon this data and provide output which is made available to user by using output device.

Input devices

Input device is responsible for taking input from user and provide to computer. Some most commonly used input devices are

  • Keyboard
  • Mouse
  • Microphone
  • Webcam
  • Scanner
  • Bar code reader
  • Light pen
  • Joystick

Output devices

Output device is responsible for providing and displaying output to user. Some most commonly used output devices are:

  • Monitor- LED Monitor, LCD Monitor, CRT Monitor
  • Printer- Impact Printer (Inkjet, Dot-Matrix), Non-Impact Printer (Laser, Inkjet)
  • Plotter
  • Speaker

CPU (Central Processing Unit)

CPU is control center of computer. It understands the instructions and carries out operations on the computer accordingly. It is the brain of computer and controls the activity performed by the computer.

The CPU has three components:

  • ALU (Arithmetic and Logical Unit)
  • MU (Memory Unit)
  • CU (Control Unit)

ALU (Arithmetic and Logical Unit)

ALU is component which is responsible for all the arithmetic or logical operation done on the data. Arithmetic operations are the basic mathematical calculations. Logical operations are basically comparison operation involves comparing data and determine different action to be performed PROCESSOR.

CU (Control Unit)

The control unit is a component which controls the flow of data and operations in a computer. It acts as a manager and instructs and coordinates all the components of CPU to perform their respective task.

MU (Memory Unit)

Memory unit is a component which is responsible for storing all data and information and instructions.

Memory of computer is more like a predefined working space where it temporary keep information and data to facilitate its performance. When the task is performed, it clears it’s memory and memory space is then available for the next task to be performed. This memory is often called main memory. There are two types of memory:

Primary Memory

Primary memory also known as Volatile memory that is temporary as it loses its contents when the computer’s power is turned off. It is internal memory that is accessed directly by the processor. Following are the Primary memory:

RAM: Random Access Memory is the memory that the computer uses for storing the programs and their data while working on them. We can either read data from the RAM or write onto it. Hence it is called read/write memory.

ROM: Read Only Memory is used to store the data about the hardware which does not required frequent updates, for example startup programs that loads Operating System into RAM. ROM is non-volatile memory. We can only read data from the ROM and hence called read only memory.

Cache Memory:  Catch memory is very high speed memory which is placed between processor and RAM to speed up the operations of CPU. Generally it stores the copies of data frequently accessed from RAM.

Secondary Memory

Secondary memory also known as non-volatile memory stores data and instructions permanently for future use. It is slower than primary memory but cannot be accessed by processor directly. Example of Secondary Memory are :

  • Hard Disk
  • CD/DVD
  • USB Flash Drive
  • Memory Card

Memory Unit

‘Byte’ is unit of memory used to measure amount of space consumed by data or instructions in memory.

Memory size conventions

1 Kilobyte = 1024 Bytes

1 Megabyte = 1024 KB

1 Gigabyte = 1024 MB

1 Terabyte = 1024GB

1 Petabyte = 1024TB

1 Exabyte = 1024 PB

Data Capturing

Data capturing refers to process of collecting or inputting data from different sources. To input data different input devices can be used such as keyboard, scanner, camera, bar code reader etc. data capturing might be a complex process due to nonuniformity in data. 

Data Storage

Data storage refers to process of storing captured data for future use. There are many different types of storage device are available which can be used to store data. Now a day due to rise in computers, Internet and Technology large volume of data being produced and hence the storage device should be of large capacity and updated regularly. to store large amount of data, Server can be deployed or Cloud computing can also be used.

Data Retrieval

Data Retrieval refers to accessing or fetching data from storage device as per requirement. Due to large volume of data now a day, system must have good quality and effective programs in order to access data at minimum time.

Data Deletion and Recovery

Deleting data refers to erasing data from storage device. There can be many reasons for deleting data such as system crash, accidental deletion, and illegal deletion by hackers/mischief mongers. When data is deleted from storage media, only the status (address entry) of data is changed and that space is shown empty to user without deleting data actually.

Data recovery is process of accessing deleted, lost or corrupted data from storage device. Deleted data can only be recovered when memory space of deleted data have not been overwritten with new data.

Software

Software is set of programs that instruct hardware to what to and how to do. It makes hardware functional to achieve a common objective. Some example of software is Window10, Macintosh, MySQL, MS Word, Excel, Games etc.

Types of software

There are two types of software:

  • System software
  • Application software

System Software

System software manages computer system. It is software that control and coordinate all internal activities of a computer system.

System software can be categorized as

  • Operating System
  • Utility Software
  • Device Driver

Operating System

Operating System acts as an interface between user and machine. It is set of programs that –

  • Manages hardware resources
  • Manage memory
  • Display result in monitor
  • Control all hardware component attached to computer system
  • Read data through input devices

Examples of Operating System are Window10, Window8, Macintosh, Ubuntu, DOS etc.

Utility software

It is system software that helps you to configure and optimize and maintain a computer. Examples of utility software are- Disk Cleaner, File Backup Utility, Antivirus, Firewall, Disk Defragmenter etc.

Device Driver

Device driver is software which controls a particular type of hardware attached with a computer. It acts as an interpreter between particular hardware and computer system.

Read More