Chapter 11 : Societal Impact | Class 11th | Computer Science Important Questions

NCERT Book Exercise of Class 11 Computer Science


1. After practicals, Atharv left the computer laboratory but forgot to sign off from his email account. Later, his classmate Revaan started using the same computer. He is now logged in as Atharv. He sends inflammatory email messages to few of his classmates using Atharv’s email account. Revaan’s activity is an example of which of the following cyber crime?
Justify your answer.
a) Hacking
b) Identity theft
c) Cyber bullying
d) Plagiarism


Answer: (b) Identity theft

Identity theft means obtaining someone’s credentials to commit some online fraud.


2. Rishika found a crumpled paper under her desk. She picked it up and opened it. It contained some text which was struck off thrice. But she could still figure out easily that the struck off text was the email ID and password of Garvit, her classmate. What is ethically correct for Rishika to do?
a) Inform Garvit so that he may change his password.
b) Give the password of Garvit’s email ID to all other classmates.
c) Use Garvit’s password to access his account.

Answer: a) Inform Garvit so that he may change his password.


3. Suhana is down with fever. So, she decided not to go to school tomorrow. Next day, in the evening she called up her classmate, Shaurya and enquired about the computer class. She also requested him to explain the concept. Shaurya said, “Mam taught us how to use tuples in python”. Further, he generously said, “Give me some time, I will email you the material
which will help you to understand tuples in python”.

Shaurya quickly downloaded a 2-minute clip from the Internet explaining the concept of tuples in python. Using video editor, he added the text “Prepared by Shaurya” in the downloaded video clip. Then, he emailed the modified video clip to Suhana. This act of Shaurya is an example of —
a) Fair use
b) Hacking
c) Copyright infringement
d) Cyber crime

Answer: c) Copyright infringement


4. After a fight with your friend, you did the following activities. Which of these activities is not an example of cyber bullying?

a) You sent an email to your friend with a message saying that “I am sorry”.
b) You sent a threatening message to your friend saying “Do not try to call or talk to me”.
c) You created an embarrassing picture of your friend and uploaded on your account on a social networking site.


Answer: a) You sent an email to your friend with a message saying that “I am sorry”.


5. Sourabh has to prepare a project on “Digital India Initiatives”. He decides to get information from the Internet. He downloads three web pages (webpage 1, webpage 2, webpage 3) containing information on Digital India Initiatives. Which of the following steps taken by Sourabh is an example of plagiarism or copyright infringement? Give justification in support of your answer.
a) He read a paragraph on “ Digital India Initiatives” from webpage 1 and rephrased it in his own words. He finally pasted the rephrased paragraph in his project.
b) He downloaded three images of “ Digital India Initiatives” from webpage 2. He made a collage for his project using these images.
c) He downloaded “Digital India Initiative” icon from web page 3 and pasted it on the front page of his project report.

Answer: b & c

Plagiarism means using someone else’s work without giving adequate citation for use and presenting as your own work.

Copyright infringement means using copyright-protected material without obtaining copyright holder’s permission or without paying for it, if it is being sold.


6. Match the following:

Column AColumn B
PlagiarismFakers, by offering special rewards or money prize asked for personal information, such as bank account information
HackingCopy and paste information from the Internet into your report and then organise it
Credit card fraudThe trail that is created when a person uses the Internet.
Digital Foot PrintBreaking into computers to read private emails and other files

Answer:

Column AColumn B
PlagiarismCopy and paste information from the Internet into your report and then organise it
HackingBreaking into computers to read private emails and other files
Credit card fraudFakers, by offering special rewards or money prize asked for personal information, such as bank account information
Digital Foot PrintThe trail that is created when a person uses the Internet.

7. You got the below shown SMS from your bank querying a recent transaction. Answer the following —

a) Will you SMS your pin number to the given contact number?

Answer : No, I will not shared PIN to that contact number.

b) Will you call the bank helpline number to recheck the validity of the SMS received?

Answer : Yes. I will call the bank helpline number.


8. Preeti celebrated her birthday with her family. She was excited to share the moments with her friend Himanshu. She uploaded selected images of her birthday party on a social networking site so that Himanshu can see them. After few days, Preeti had a fight with Himanshu. Next morning, she deleted her birthday photographs from that social networking site, so that Himanshu cannot access them. Later in the evening, to her surprise, she saw that one of the images which she had already deleted from the social networking site was available with their common friend Gayatri. She hurriedly enquired Gayatri “Where did you get this picture from?”. Gayatri replied “Himanshu forwarded this image few minutes back”.
Help Preeti to get answers for the following questions.

Give justification for your answers so that Preeti can understand it clearly.

a) How could Himanshu access an image which I had already deleted?

Answer: Images loaded on a social networking site can be saved/downloaded or even screenshots may be taken.

b) Can anybody else also access these deleted images?

Answer: Yes, from the digital footprint, government and other agencies can obtain these legally, if needed.

c) Had these images not been deleted from my digital footprint?

Answer: Images deleted from a social website always remain part of a digital footprint.

Read More

Chapter 10 : Tuples and Dictionaries | Class 11th | Computer Science Important Questions

chapter 10. Tuples and Dictionary


1. Consider the following tuples, tuple1 and tuple2:

tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)

Find the output of the following statements:

i. print(tuple1.index(45))

Answer: 2

ii. print(tuple1.count(45))

Answer: 3

iii. print(tuple1 + tuple2)

Answer: (23, 1, 45, 67, 45, 9, 55, 45, 100, 200)

iv. print(len(tuple2))

Answer: 2

v. print(max(tuple1))

Answer: 67

vi print(min(tuple1))

Answer: 1

vii. print(sum(tuple2))

Answer: 300

viii. print(sorted(tuple1))

print(tuple1)

Answer: [1, 9, 23, 45, 45, 45, 55, 67]

(23, 1, 45, 67, 45, 9, 55, 45)



2. Consider the following dictionary stateCapital:

stateCapital = {“AndhraPradesh”:”Hyderabad”, “Bihar”:”Patna”, “Maharashtra”:”Mumbai”, “Rajasthan”:”Jaipur”}

Find the output of the following statements:

i. print(stateCapital.get(“Bihar”))

Answer: Patna

ii. print(stateCapital.keys())

Answer: dict_keys([‘Assam’, ‘Bihar’, ‘Maharashtra’, ‘Rajasthan’])

iii. print(stateCapital.values())

Answer: dict_values([‘Guwahati’, ‘Patna’, ‘Mumbai’, ‘Jaipur’])

iv. print(stateCapital.items())

Answer: dict_items([(‘Assam’, ‘Guwahati’), (‘Bihar’, ‘Patna’), (‘Maharashtra’, ‘Mumbai’), (‘Rajasthan’, ‘Jaipur’)])

v. print(len(stateCapital))

Answer: 4

vi. print(“Maharashtra” in stateCapital)

Answer: True

vii. print(stateCapital.get(“Assam”))

Answer: Guwahati

viii. del stateCapital[“Rajasthan”]

print(stateCapital)

Answer: {‘Bihar’: ‘Patna’, ‘Maharashtra’: ‘Mumbai’, ‘Rajasthan’: ‘Jaipur’}


3. “Lists and Tuples are ordered”. Explain.

Answer: Lists and Tuples are ordered, it means that both the lists’ and tuples’ elements are ordered, because each element in lists and tuples has a designated index position. The index position (either forward or backward), maintain the order and these elements can also accessed individually with the help of their index position.

For example :

List1 = [10, 3, ‘mycstutorial.in’, False]

Tuple1 = [25, 12, ‘mycstutorial.in’, True]

print(List1[2])

print(Tuple[3])

Output:

myctutorial.in

True



4. With the help of an example show how can you return more than one value from a function.

Answer: A function can return multiple values in the form of tuples.

For example :

#Example - 1
def square(n1, n2, n3):
    sq = n1**2, n2**2, n3**2
    rerurn sq


#Example - 2
def cube(n1, n2, n3):
    return n1**3, n2**3, n3**3
   
#__main__

print("Calling Method Square")
result1 = square(5,10,15)
print(result1)
print(type(result1))


print("Calling Method Cube")
result2 = cube(2,3,4)
print(result2)
print(type(result2))

Output:

Calling Method Square

(25, 100, 225 )

<class ‘tuple’>

Calling Method Cube

(8, 27, 64)

<class ‘tuple’>


5. What advantages do tuples have over lists?

Answer: The advantages of tuples over lists is that tuples ensure that the data stored in tuple will not change.

If you want to store data as a sequence of any type of values and does not want to make any changes accidently, then you can use Tuple instead of List.


6. When to use tuple or dictionary in Python. Give some examples of programming situations mentioning their usefulness.

Answer: Tuples are used to store the data which is not intended to change during the course of execution of the program. For example, if the name of months is needed in a program, then the same can be stored in the tuple as generally, the names will either be repeated for a loop or referenced sometimes during the execution of the program.

Dictionary is used to represent the unordered list of the data. The key and value are separated by colon. Dictionary is used to store associative data like student’s roll no. and the student’s name. Here, the roll no. will act as a key to find the corresponding student’s name. The position of the data doesn’t matter as the data can easily be searched by using the corresponding key.

For example :

#Tuple vs Dictionary

month = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')

stud = {1: ('Amrit', 'IV','DPS Mgarh'), 2: ('Tanmay', 'III', 'DPS Mgarh')}

print("Name of month 6th : ", month[5])

print("Details of Roll Number 1: ")
print(stud[1])

Output:

Name of month 6th : Jun

Details of Roll Number 1:

(‘Amrit’, ‘IV’, ‘DPS Mgarh’)


7. Prove with the help of an example that the variable is rebuilt in case of immutable data types.

Answer: A tuple once created cannot be changed Even if you try to make changes in the tuple and give it the same name, Python Internally will create a new tuple and store it at a different memory location. For example

>>> tup1 = (1,2,'mycstutorial.in')
>>> id(tup1)
61944840
>>> print(tup1)
(1, 2, 'mycstutorial.in')

>>> tup1 = tup1 + ('ncert solution','xi','computer','science')
>>> tup1
(1, 2, 'mycstutorial.in', 'ncert solution', 'xi', 'computer', 'science')
>>> id(tup1)
59301336
>>> print(tup1)
(1, 2, 'mycstutorial.in', 'ncert solution', 'xi', 'computer', 'science')
>>> 

Check the id printed in two different statement. As you can observe in both cases variable name is the same but it is printed different id’s, It means that tuple is immutable data type, and if you try to change it, it will not make the change in-place, it create a new variable.


8. TypeError occurs while statement 2 is running. Give reason. How can it be corrected?

tuple1 = (5) #statement 1
len(tuple1) #statement 2

Answer: tuple1 = (5) statement does not create a tuple type variable, it creates integer type variable. len() function works with collection/sequence type variable such tuple, list, dictionary, string.

len() function need sequence value or variable as argument. That’s why len(tuple1) generate an error TypeError.

Corrected Way :

tuple1 = (5,) #statement 1
len(tuple1) #statement 2

Output:

1

Read More

Chapter 9 : Lists | Class 11th | Computer Science Important Questions

Class 11 Computer Science – NCERT Book question answers

Chapter 9. Lists


1. What will be the output of the following statements?

i. Find the output

list1 = [12,32,65,26,80,10]
list1.sort()
print(list1)

Answer: [10, 12, 26, 32, 65, 80]

ii. Find the output

list1 = [12,32,65,26,80,10]
sorted(list1)
print(list1)

Answer: [10, 12, 26, 32, 65, 80]

[12, 32, 65, 26, 80, 10]

iii. Find the output

list1 = [1,2,3,4,5,6,7,8,9,10]
list1[::-2]
list1[:3] + list1[3:]

Answer: [10, 8, 6, 4, 2]

[1,2,3,4,5,6,7,8,9,10]

iv. Find the output

list1 = [1,2,3,4,5]
list1[len(list1)-1]

Answer: 5


2. Consider the following list myList. What will be the elements of myList after the following two operations:

myList = [10,20,30,40]
i. myList.append([50,60])
ii. myList.extend([80,90])

Answer: Elements of myList after given operations are (i) [10,20,30,40,[50,60]]

(ii) [10,20,30,40,[50,60], 80,90]


3. What will be the output of the following code segment:

myList = [1,2,3,4,5,6,7,8,9,10]
for i in range(0,len(myList)):
        if i%2 == 0:
             print(myList[i])

Answer: Above code print even positioned element of myList.

1

3

5

7

9


4. What will be the output of the following code segment:

a. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[3:]
print(myList)

Answer: [1, 2, 3]

b. myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
del myList[:5]
print(myList)

Answer: [6, 7, 8, 9, 10]

c. myList = [1,2,3,4,5,6,7,8,9,10]
del myList[ : : 2]
print(myList)

Answer: [2, 4, 6, 8, 10]


5. Differentiate between append() and extend() functions of list.

Answer: append() vs extend()

1. append() method of list is use to add element at the end of the list.

extend() method of list is use to add a list at the end of another list.

2. append() method increase the size of list by 1 while extend() method increase the size of list by len(list2).

myList = [10,20,30,40]

myList.append([50,60])
print(myList)
myList.extend([80,90])

print(myList)


6. Consider a list:

list1 = [6, 7, 8, 9]

What is the difference between the following operations on list1:

a. list1 * 2
b. list1 *= 2
c. list1 = list1 * 2

Answer: (a) In list1 * 2, * operator work as replication operator. Which replicate the list1 two times. list1 * 2 will generate a list [6, 7, 8, 9, 6, 7, 8, 9]. But list1 is not changed.

(b) list1 *= 2, in this *= is a replication and assignment operator. It means it replicate the list1 two times and update list1. New list1 is [6, 7, 8, 9, 6, 7, 8, 9]

(c) list1 = list1 * 2, this statement will create a new list1 containing the two times replicated value of list1.

Lets understand this with an example.

>>> list1 = [6, 7, 8, 9]
>>> id(list1)
33379432

>>> list1 * 2
[6, 7, 8, 9, 6, 7, 8, 9]
>>> list1
[6, 7, 8, 9]
>>> id(list1)
33379432

>>> list1 *= 2
>>> list1
[6, 7, 8, 9, 6, 7, 8, 9]

>>> id(list1)
33379432

>>> list1 = list1 * 2
>>> list1
[6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9]

>>> id(list1)
64129512
>>> 

7. The record of a student (Name, Roll No., Marks in five subjects and percentage of marks) is stored in the following list:
stRecord = [‘Raman’,’A-36′,[56,98,99,72,69], 78.8]
Write Python statements to retrieve the following information from the list stRecord.
a) Percentage of the student
b) Marks in the fifth subject
c) Maximum marks of the student
d) Roll no. of the student
e) Change the name of the student from ‘Raman’ to ‘Raghav’

Answer: Statements are –

(a) print(” Percentage of the student : “, stRecord[3])

b) print(“Marks in the fifth subject : “, stRecord[2][4])

c) print(“Maximum marks of the student :”, max(stRecord[2]))

d) print(“Roll no. of the student :”, stRecord[1])

e) stRecord[0] = ‘Raghav

Read More

Chapter 8 : Strings | Class 11th | Computer Science Important Questions

Very Short Answer type Questions [1 mark each]

Question 1:
Explain capitalize( ) method in Python.
Answer:
The method capitalize( ) returns a copy of the string with only its first character capitalized.

Question 2:
Write the syntax for capitalize( ) method.
Answer:
Following is the syntax for capitalize( ) method : str.capitalize( )

Question 3:
What value will be returned by center (width, fillchar) method in Python.
Answer:
The method center( ) returns centered in a string of length width. Padding is done using the specified fillchar.

Question 4:
What are the two parameters of center( ) method.
Answer:
width — This is the total width of the string,
fillchar — This is the filler character

Question 5:
Describe the count(str, beg=0,end= len(string))
Answer:
The method count( ) returns the number of occurrences of substring sub in the range [start, end].

Question 6:
Describe the decode (encoding=’UTF8′, errors=’ strict’ )
Answer:
The method decode( ) decodes the string using the codec registered for encoding.

Question 7:
What do you n .an by encode(encoding= ‘UTF- 8,errors=’strict’)
Answer:
The method encode( ) returns an encoded version of the string. Default encoding is the current default string encoding.

Question 8:
What do you mean by endswith(suffix, beg=0, end=len(string))
Answer:
The method endswith( ) returns True if the string ends with the specified suffix, otherwise return False

Question 9:
Write the the syntax for find( ) method
Answer:
Following is the syntax for find( ) method :
str.find(str, beg=0 end=len(string))

Question 10:
Write the output of the following code.
# !/usr/bin/py thon
str1 = “this is string example… ,wow!!!”;\
str2 = “exam”;
print strl.find(str2);
print strl.find(str2,10);
print strl.find(str2, 40);
Answer:
15 15 -1

Question 11:
Write the syntax for isalnum( ) method.
Answer:
Following is the syntax for isalnum( )
method :
str.isalnum( )

Question 12:
Write the output of the following code.
# !/usr/bin/python
str = “this2009”; # No space in this string print str.isalnum( );
str = “this is string example….wow!!!”;
print str.isalnum( );
Answer:
True False

https://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-7398766921532682&output=html&h=280&adk=2523109437&adf=568131091&pi=t.aa~a.1381849204~i.27~rp.4&w=750&fwrn=4&fwrnh=100&lmt=1668321352&num_ads=1&rafmt=1&armr=3&sem=mc&pwprc=6908628465&ad_type=text_image&format=750×280&url=https%3A%2F%2Fwww.cbsetuts.com%2Fncert-solutions-class-11-computer-science-python-strings%2F&fwr=0&pra=3&rh=188&rw=750&rpe=1&resp_fmts=3&wgl=1&fa=27&adsid=ChEIgM3knQYQi7aKz6raxcqeARI5AN8-ETKxdRu8noyUBdpNiYwq4zsCT9SLEqnLKpy-Sb83QRIUgTK7wcEpDrRhseGcc1X8ya7_gan4&uach=WyJXaW5kb3dzIiwiNi4wLjAiLCJ4ODYiLCIiLCIxMDguMC41MzU5LjEyNSIsW10sZmFsc2UsbnVsbCwiNjQiLFtbIk5vdD9BX0JyYW5kIiwiOC4wLjAuMCJdLFsiQ2hyb21pdW0iLCIxMDguMC41MzU5LjEyNSJdLFsiR29vZ2xlIENocm9tZSIsIjEwOC4wLjUzNTkuMTI1Il1dLGZhbHNlXQ..&dt=1673106819685&bpp=3&bdt=3746&idt=3&shv=r20230104&mjsv=m202301040101&ptt=9&saldr=aa&abxe=1&cookie=ID%3Dabbbd049660c1ef5-2201b28402d90024%3AT%3D1671719836%3ART%3D1671719836%3AS%3DALNI_MazhTIzYkzGHXl260j5g4NFTSeuqQ&gpic=UID%3D00000b960889abfa%3AT%3D1671719836%3ART%3D1673106818%3AS%3DALNI_MZitKfGKipH7BopsZPzcTHmvXnt4Q&prev_fmts=0x0%2C750x280%2C300x600%2C750x280%2C750x280%2C750x280%2C1519x754%2C728x90&nras=7&correlator=4356224157036&frm=20&pv=1&ga_vid=1762681568.1671719837&ga_sid=1673106819&ga_hid=1465708488&ga_fc=1&u_tz=330&u_his=16&u_h=864&u_w=1536&u_ah=824&u_aw=1536&u_cd=24&u_sd=1.25&dmc=4&adx=190&ady=2736&biw=1519&bih=754&scr_x=0&scr_y=0&eid=44759875%2C44759926%2C44759842%2C31071413%2C44779794&oid=2&pvsid=145708464233543&tmod=169065013&uas=0&nvt=1&ref=https%3A%2F%2Fwww.google.com%2F&eae=0&fc=1408&brdim=0%2C0%2C0%2C0%2C1536%2C0%2C1536%2C824%2C1536%2C754&vis=1&rsz=%7C%7Cs%7C&abl=NS&fu=128&bc=31&ifi=8&uci=a!8&btvi=6&fsb=1&xpc=Bz7YHvBUg5&p=https%3A//www.cbsetuts.com&dtd=729

Question 13:
Write the syntax for isalpha( ) method.
Answer:
Following is the syntax for isalpha( ) method :
str.isalpha( )

Question 14:
Write the output of the following code.
# !/usr/bin/python
str = “this”; # No space & digit in this string print str.isalpha( );
str = “this is string example….wow!!!”; print str.isalpha( );
Answer:
True False

Question 15:
Describe the isdigit( ) method
Answer:
The method isdigit( ) checks whether the string consists of digits only

Question 16:
Why we use islower( ) method in python?
Answer:
The method islower( ) checks whether all the case-based characters (letters) of the string are lowercase

Question 17:
Describe the isspace( ) method
Answer:
The method isspace( ) checks whether the string consists of whitespace.

Question 18:
Write the output of the following code.
#!/usr/bin/python
str = ” “;
print str.isspace( );
str = “This is string example….wow!!!”;
print str.isspace( );
Answer:
True
False

Question 19:
Write the output of the following code.
#!/usr/bin/python
str = “this is string example….wow!!!”;
print str.ljust(50, ‘0’);
Answer:
This is string example
…wow!!!000000000000000000

Question 20:
Write the output of the following code.
# !/usr/bin/python
str = “Waltons Technology….wow!!!”;
print “str.upper() : “str.upper()
Answer:
str.upper() : Waltons Technology ….WOW!!!

Question 21:
Rectify the error (if any) in the given statements.
>>>str = “Hello World”
>>>str[5] = ‘p’
Answer:
Strings are immutable. So convert to 2.
list > > >s = list (str)’p’)
>>s [5]=’p’

Question 22:
Give the output of the following state-ments :
>>>str = ‘Honesty is the best policy”
>>>str.replace (‘o’.’*’)
Answer:
H*nesty is the best p*licy.

Short Answer type Questions  [2 mark each]

Question 1:
What do you mean by string in Python ?
Answer:
Strings are amongst the most popular types in Python. We can create them simply by characters in quotes. Python treats single quotes the same as double quotes.
Creating strings is as simple as assigning a value to a variable. For example :
var1 = ‘Waltons Technology!’
var2 = “Python Programming”

Question 2:
What is indexing in context to Python strings ? J Why is it also called two-way indexing ?
Answer:
In Python strings, each individual character is ! given a location number, called “index” and this process is called “indexing”. Python allocates indices in two directions :

  1. in forward direction, the indexes are numbered as 0,1, 2,    length-1.
  2. in backward direction, the indexes are numbered as -1, -2, -3,…. length.
    This is known as “two-way indexing”.

Question 3:
What is a string slice ? How is it useful ?
Answer:
A sub-part or a slice of a string, say s, can be obtained using s[n : m] where n and m are integers. Python returns all the characters at indices n, n+1, n+2,…. m-1.
For example,
‘Oswaal Books’ [1 : 4] will give ‘swa’

Question 4:
How you can “update” an existing string ?
Answer:
You can “update” an existing string by (re) assigning a variable to another string.
The new value can be related to its previous value or to a completely different string altogether.
Following is a simple example :
# !/usr/bin/python
var1 = ‘Hello World!’
print”Updated String:-“,var i[:6] + ‘Python’

Question 5:
Describe Triple Quotes in Python.
Answer:
Python’s triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters. The syntax for triple quotes consists of three consecutive single or double quotes.
# !/usr/bin/py thon
para str = “””this is a long string that is made up of several lines and non-printable characters such as
TAB ( \t ) and they will show up that way when displayed.
NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable assignment will also show up.
” ” ”
print para_str;

Question 6:
Define raw string with example.
Answer:
Raw strings don’t treat the backslash as a special character at all. Every character you put into a raw string stays in the way you wrote it :
# !/usr/bin/python
print ‘C:\\nowhere’
When the above code is executed, it produces the following result :
C:\nowhere
Now let’s make use of raw string. We would put expression in r’expression’ as follows :
# !/usr/bin/python
print r’C:\\nowhere’
When the above code is executed, it produces the following result :
C:\\nowhere

Question 7:
Explain Unicode String with example.
Answer:
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16- bit Unicode. This allows for a more varied set of characters, including special characters from most languages in the world.
Example…….
#!/usr/bin/python
print u’Hello, world!’

Question 8:
Describe isdecimal( ) with example.
Answer:
The method isdecimal( ) checks whether the string consists of only decimal characters. This method is present only on Unicode objects.
Note : To define a string as Unicode, one simply prefixes a ‘u’ to the opening quotation mark of the assignment.
Below is the example.
Syntax :
Following is the syntax for isdecimal( ) method :
str.isdecimal( )

Question 9:
Explain zfill (width) with Syntax and Return Value
Answer:
The method zfill( ) pads string on the left with zeros to fill width.
Syntax : str.zfill(width)
Parameters: This is final width of the string. This is the width which we would get after filling zeros. Return Value: This method returns padded string

Question 10:
Write the output of the following code
# !/usr/bin/python
str = “this is string example….wow!!!”;
print str.zfill(40);
print str.zfill(50);
Answer:
On compiling and running the above program, this will produce the following result :
OOOOOOOOthis is string example….wow!!! 000000000000000000this is string example…. wow!!!

Question 11:
Write the output of the following code
# !/usr/bin/python
from string import maketrAns. # Required to call maketrAns. function.
intab = “aeiou” outtab = “12345”
trantab = maketrAns.(intab, outtab) str = “this is string example….wow!!!”; print str.trAns.late(trantab, ‘xm’);
Answer:
The given code will produce following result :
th3s 3s str3ng 21pl2….w4w!M

Question 12:
Describe the following method trans.late(table, deletechars=””)
Answer:
The method translate( ) returns a copy of the string in which all characters have been translated using table (constructed with the maketrans( ) function in the string module), optionally deleting all characters found in the string deletechars.

Question 13:
Give an example of title( ) in Python
Answer:
The following example shows the usage of title( ) method
# !/usr/bin/python
str = “this is string example….wow!!!”;
print str.title( );
On compile and run the above program, this will produce the following result :
This Is String Example….Wow!!!

Question 14:
Give an example of swapcase( ) in Python
Answer:
The following example shows the usage of swapcase( ) method.
# !/usr/bin/py thon
str = “this is string example….wow!!!”;
print str.swapcase( );
str = “THIS IS STRING EXAMPLE….WOW!!!”;
print str.swapcase( );
This will produce the following result :
THIS IS STRING EXAMPLE….WOW!!!
this is string example….wow!!!

Question 15:
Define strip ([chars]) with its syntax
Answer:
The method strip( ) returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (default whitespace characters).
Syntax: str.strip([chars]);

Question 16:
Explain Parameters of str.startswith(str, beg=0,end=len( string) );
Answer:
str — This is the string to be checked.
beg — This is the optional parameter to set start index of the matching boundary.
end — This is the optional parameter to set end index of the matching boundary.

Question 17:
Explain Parameters of str.rjust(width[, fillchar])
Answer:
width — This is the string length in total after padding.
fillchar — This is the filler character, default is a space.

Question 18:
Write the output of the given Python code # !/usr/bin/python
str = “this is really a string example…. wow!!!”;
str = “is”;
print str.rfind(str);
print str.rfind(str, 0,10);
print str.rfind(str, 10, 0);
print str.find(str);
print str.find(str, 0,10);
print str.find(str, 10, 0);
Answer:
Above code will produce the following result :
5
5
-1
2
2
-1

Question 19:
Write the output of the given code #!/usr/bin/python
str = “this-is-real-string-example….wow!!!”;
print “Min character: ” + min(str);
str = “this-is-a-string-example….wow!!!”;
print “Min character: ” + min(str);
Answer:
Min character: !
Min character: !

Question 20:
Write the output of the given code #!/usr/bin/python
str = “this is really a string example….wow!!!”;
print “Max character: ” + max(str);
str = “this is a string example….wow!!!”;
print “Max character: ” + max(str);
Answer:
Output
Max character: y
Max character: x

Question 21:
Describe the function maketrans( )
Answer:
The method maketrans( ) returns a translation table that maps each character in the intab string into the character at the same position in the outtab string. Then this table is passed to the translate( ) function.
Syntax : str.maketrans(intab, outtab]);

Question 22:
Write the output of the following code
#!/usr/bin/py thon
str = ” this is string example….wow!!! “; print str.lstrip( );
str = “88888888this is string example….wow!!!8888888”;
print str.lstrip(‘8’);
Answer:
Output
this is string example….wow!!!
this is string example..,.wow!!!8888888

Question 23:
Study the given script
defmetasearch( ):
import re
p=re.compile(‘sing+’)
searchl=re.search(p,’ Some singers sing well’)
if searchl:
match=searchl.group( )
index=searchl.start( )
lindex=search 1 ,end( )
print “matched”, match, “at index”, index ,”ending at”, lindex
else:
print “No match found”
metasearch( )
What will be the output of the above script if search( ) from the re module is replaced by match ( ) of the re module. Justify your answer
Answer:
The output would be “N match found”
Justification : re.search( ) rill attempt the pattern throughout the string, i ntil it finds a match. re.match( ) on the other hand, only attempts the pattern at the very start of the string.
Example :
>>>re.match(“d”, “abcdef’) # No match
>>>re.search(“d”, “abcdef’) # Match

Question 24:
What will be the output of the script mentioned below? Justify your answer, def find) ):
import re
p=re.compile(‘ sing+’)
searchl=p.findall(‘Some singer sing well’)
print searchl
Answer:
Output : [‘sing’, ‘sing’]
Justification : fmdall( ) finds all occurences of the given substring with metacharacter.

Long Answer type Questions [4 mark each]

Question 1:
What is the concept of immutable strings ?
Answer:
Strings are immutable means that the contents of string cannot be chrnged after it is created.
For example :
>>> str = ‘Meney’
>>> str [3] = ‘h’
Type Error : ‘str’ object not support item assignment Python does not allow to change a character in a string. So an attempt to replace ‘e’ in the string by ‘h’ displays a Type Error.

Question 2:
What do you understand by traversing a string ? Ans. Traversing a string means accessing all the elements of the string one after the other by using the subscript. A string can be traversed using for loop or while loop.
For example :
A = ‘Python’
i = 0
while i < lenn (A) :
print A[i]
i = i + 1
Output :
P
y
t
h
o
n

Question 3:
Write a program to check whether the string is a palindrome or not.
Answer:
def palindrom ( ) :
str = input (“Enter the string”)
l = len (str)
P = l – 1
inex = 0
while (index < p) :
if (str[index] = = str [p]):
index = index + 1
p = p-1
else :
print “String is not a palindrom” break
else :
print “String is a palindrom”

Question 4:
Write a program to count number of ‘s’ in the string ‘successor’.
Answer:
def letcount ( ) :
word = ‘successor’
count = 0
for letter in word :
if letter = = ‘s’ :
count = count + 1
print (count)

Question 5:
Write a program to determine if the given word is present in the string.
Answer:
def wsearch ( ) :
imprt re
word = ‘good’
search1 = re.search (word, ‘I am a good person’)
if search1 :
position = search1.start ( )
print “matched”, word, “at position”, position
else :
print “No match found”

Question 6:
Input a string “Green Revolution”. Write a script to print the string in reverse.
Answer:
def reverseorder(list 1) :
relist = [ ]
i = len (list 1) -1
while i > = 0 :
relist.append (list [i])
i = 1 -1
return relist

Question 7:
Write a program to print the pyramid ?
Answer:
num = eval (raw_input (“Enter an integer from 1 to 5:”))
if num < 6 :
for i in range (1, num + 1):
for j in range (num-i, 0,-1):
print (” “)
for j in range (i, 0, -1):
print (j)
for j in range (2, i+1):
print (j)
print (” “)
else :
print (“The number entered is greater than 5”)
Output :
ncert-solutions-for-class-11-computer-science-python-strings-(107-1)

Question 8:
Write the syntax of isdecimal( ) and give suitable example
Answer:
The method isdecimal( ) checks whether the string consists of only decimal characters.
This method are present only on Unicode objects. Below is the example.
Syntax
str.isdecimal( )
Example
# !/usr/bin/python
str = u”this2009″;
print str.isdecimal( );
str = u”23443434″;
print str.isdecimal( );
This will produce the following result :
False
True

Question 9:
Write the output of the following python code #!/usr/bin/python
str = “Line1-a b c d e f\nLine2- a b
c\n\nLine4- a b c d”;
print str.splitlines( );
print str.splitlines(O);
print str.splitlines(3);
print str.splitlines(4);
print str.splitlines(5);
Answer:
Output
[‘Linel-a b c d e f’, ‘Line2- a b c’, “, ‘Line4- abed’]
[‘Linel-a b c d e f’, ‘Line2- a b c’, “, ‘Line4- abed’]
[‘Linel-a b c d e f\ri, ‘Line2- a b c\ri, ‘\n’, ‘Line4- a b c d’]
[‘Linel-a b c d e f\n’, ‘Line2- a b c\ri, ‘\ri, ‘Line4- a b c d’]
[‘Linel-a b c d e f\ri, ‘Line2- a b c\ri, ‘\n’, ‘Line4- a bed’]

Question 10:
Define split( ) with suitable example.
Answer:
The method split( ) returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.
Syntax
str.split(str=””, num=string.count(str)).
Parameters
str — This is any delimeter, by default it is space.
num — This is number of lines to be made.
Example
# !/usr/bin/python
str = “Linel-abcdef \nLine2-abc \nLine4-abcd”;
print str.split( ); print str.split(‘ 1 );
OUTPUT
[‘Linel-abcdef’, ‘Line2-abc’, ‘Line4-abcd’]
[‘Linel-abcdef’, ‘\nLine2-abc \nLine4-abcd’]

Question 11:
Explain replace(old, new [, max])
Answer:
The method replace( ) returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max.
Syntax
str.replace(old, new[, max])
Parameters –
old — This is old substring to be replaced.
new — This is new substring, which would replace old substring.
max — If this optional argument max is given, only the first count occurrences are
replaced.
Example
# !/usr/bin/python
str = “this is string example….wow!!! this is really string”;
print str.replace(“is”, “was”); print str.replace(“is”, “was”, 3);
OUTPUT
thwas was string example….wow!!! thwas was really string
thwas was string example….wow!!! thwas is really string

Question 12:
Describe index(str, beg=0, end=len(string)) with example
Answer:
The method index( ) determines if string str occurs in string or in a substring of string if starting indexbeg and ending index end are given. This method is same as find( ), but raises an exception if
sub is not found.
Syntax
str.index(str, beg=0 end=len(string))
Example
# !/usr/bin/python
str = “this is string example….wow!!!”;
str = “exam”;
print str.index(str);
print str.index(str, 10);
print str.index(str, 40);
OUTPUT
15
15
Traceback (most recent call last):
File “test.py”, line 8, in
print str.index(str, 40);
ValueError: substring not found
shell returned 1

Read More

Chapter 7 : Functions | Class 11th | Computer Science Important Questions

Question 1:

Observe the following programs carefully, and identify the error:

a) def create (text, freq):

        for i in range (1, freq):

            print text

    create(5) #function call

b) from math import sqrt,ceil
    def calc():
        print cos(0)
    calc()  #function call

c) mynum = 9

    def add9():  

        mynum = mynum + 9

        print mynum

    add9()

d) def findValue(vall = 1.0, val2, val3):
        final = (val2 + val3)/ vall
        print(final)
    findvalue()  #function call

e) def greet():

          return(“Good morning”)

    greet() = message #function call

ANSWER:

a) There are two errors in the given program.

  1. The function “create” is defined using two arguments, ‘text’ and ‘freq’, but when the function is called in line number 4, only one argument is passed as a parameter. It should be written ‘create(5, 4)’ i.e with two parameters.
  2. The syntax of ‘print’ function is incorrect. The correct syntax will be ‘print(text)’

b)  There are two errors in the given program.

  1. Only square root (sqrt) and ceiling (ceil) functions have been imported from the Math module, but here cosine function (cos) is used. ‘from math import cos’ should be written in the first line for the ‘cos’ function to work properly.
  2. The syntax of ‘print’ function is incorrect. The correct syntax will be ‘print(cos(0))’. 

c) There are two errors in the given program.

  1. In line 1, ‘mynum’ variable is defined which is a global variable. However, in line 3, a variable with the same name is defined again. Therefore, ‘mynum’ is treated as a new local variable. As no value has been assigned to it before the operation, hence, it will give an error. The local variable can either be changed to a different name or a value should be assigned to the local ‘mynum’ variable before line 3.
  2. The syntax of ‘print’ function is incorrect. The correct syntax will be ‘print(mynum)’.

d) There are three errors in the given program:

  1. The ‘function call’ in line 4 is calling an invalid function. ‘findValue()’ is different from ‘findvalue()’ as Python is case sensitive.
  2. ‘findValue()’ function needs the value of at least 2 arguments val2 and val3 to work, which is not provided in the function call.
  3. As ‘vall’ is already initialized as ‘vall = 1.0’, it is called ‘Default parameter’ and it should be always after the mandatory parameters in the function definition. i.e. def findValue(val2, val3, vall = 1.0) is the correct statement.
  4. The function ‘greet()’ returns value “Good Morning” and this value is assigned to the variable “message”. Therefore, it should follow the rule of assignment where the value to be assigned should be on RHS and the variable ‘message’ should be on LHS. The correct statement in line 3 will be ‘message = greet()’.

e) There is one error in the given program.

Page No 170:

Question 2:

How is math.ceil(89.7) different from math.floor(89.7)?

ANSWER:

Floor: The function ‘floor(x)’ in Python returns the largest integer not greater than x. i.e. the integer part from the variable.  
Ceil: The function ‘ceil(x)’ in Python returns the smallest integer not less than x i.e., the next integer on the RHS of the number line.

Hence, ‘math.ceil(89.7)’ will return 90 whereas ‘math.floor(89.7)’ will return 89.

Page No 170:

Question 3:

Out of random() and randint(), which function should we use to generate random numbers between 1 and 5. Justify.

ANSWER:

‘randint(a,b)’ function will return a random integer within the given range as parameters.
‘random()’ function generates a random floating-point value in the range (0,1)
Therefore, to generate a random number between 1 and 5 we have to use the randint(1,5) function.

Note: ‘randint()’ is a part of  ‘random’ module so, before using the same in the program, it has to be imported using the statement ‘from random import randint’

Page No 170:

Question 4:

How is built-in function pow() function different from function math.pow()? Explain with an example.

ANSWER:

There are two main differences between built-in pow() function and math.pow() functions.

  • The built-in pow(x,y [,z]) function has an optional third parameter as modulo to compute x raised to the power of y and optionally do a modulo (% z) on the result. It is same as the mathematical operation: (x ^ y) % z. Whereas, math.pow() function does not have modulo functionality.
  • In math.pow(x,y) both ‘x’ and ‘y’ are first converted into ‘float’ data type and then the power is calculated. Therefore, it always returns a value of  ‘float’ data type. This does not happen in the case of built-in pow function, however, if the result is a float data type, the output will be float else it will return integer data type.

Example: 
import math
print()
#it will return 25.0 i.e float
print(math.pow(5,2))
print()
#it will return 25 i.e int
print(pow(5,2))

Page No 170:

Question 5:

Using an example, show how a function in Python can return multiple values.  

ANSWER:

Program:
def myfun():
    return 1, 2, 3
a, b, c = myfun()
print(a)
print(b)
print(c)


OUTPUT:
1
2
3


NOTE: Although it looks like ‘myfun()‘ returns multiple values, but actually a tuple is being created here. It is the comma that forms a tuple, not the parentheses, unless it is absolutely required there, such as in the case of a blank tuple.
 

Page No 170:

Question 6:

Differentiate between the following with the help of an example:

a) Argument and Parameter
b) Global and Local variable

ANSWER:

a) Argument and Parameter:

The parameter is variable in the declaration of a function. The argument is the actual value of this variable that gets passed to function when the function is called. 
Program:

def create (text, freq):

  for i in range (1, freq):

    print text

 create(5, 4)   #function call

Here, in line 1, ‘text’ and ‘freq’ are the parameters whereas, in line 4 the values 5and4 are the arguments.

b) Global and Local variable:
In Python, a variable that is defined outside any function or any block is known as a global variable. It can be accessed in any function defined in the program. Any change made to the global variable will impact all the functions in the program where that variable is being accessed.

A variable that is defined inside any function or a block is known as a local variable. It can be accessed only in the function or a block where it is defined. It exists only till the function executes. 

Program:
# Global Variable
a = “Hi Everyone!!”
def func():
    # Local variable
    b = “Welcome”
    # Global variable accessed
    print(a)        
    # Local variable accessed
    print(b)        
func()
# Global variable accessed, return Hi! Everyone
print(a)
# Local variable accessed, will give error: b is not defined
print(b)        

Page No 170:

Question 7:

Does a function always return a value? Explain with an example.

ANSWER:

A function does not always return a value. In a user-defined function, a return statement is used to return a value.
Example:

Program:
# This function will not return any value
def func1():
    a = 5
    b = 6

# This function will return the value of ‘a’ i.e. 5
def func2():
    a = 5
    return a

# The return type of the functions are stored in the variables
message1 = func1()
message2 = func2()

print(“Return from function 1–>”, message1)
print(“Return from function 2–>”, message2)



​​OUTPUT:
Return from function 1–> None
Return from function 2–> 5



 

Page No 171:

Question 1:

 To secure your account, whether it be an email, online bank account or any other account, it is important that we use authentication. Use your programming expertise to create a program using user defined function named login that accepts userid and password as parameters (login(uid,pwd)) that displays a message “account blocked” in case of three wrong attempts. The login is successful if the user enters user ID as “ADMIN” and password as “St0rE@1”. On successful login, display a message “login successful”.

ANSWER:

Points to consider:

i) As per the question, user-defined function login(uid,pwd)needs to be created which should display either “Login Successful” or “Account Blocked” after 3 wrong attempts. Therefore, a global variable should be used and its value should increase by 1 after every unsuccessful attempt. 
ii) If the username and password are correct, the program should display “Login Successful” and terminate.
iii) Once the check for the username/password is complete and if the credentials are incorrect, the program should check for the counter value, and if ‘counter’ is more than 2, the program should display “Account Blocked” and exit, otherwise it should give the option to enter the username and password again.

The flow chart for the program can be drawn as follows:




Program:counter = 0
def logintry():

    ##This function will ask for username and password from the user and then pass the entered value to the login function
    username = input(“Enter username: “)
    password = input(“Enter password: “)
    login(username, password);
def login(uid,pwd):
    global counter
    if(uid==”ADMIN” and pwd ==”St0rE@1″):
        print(“Login Successful”)
        return

    #If username and password is correct the program will exit
    else:
        counter += 1
        print(“The username or password is incorrect”)
    if(counter>2):

        # check counter value to see
        # the no.of incorrect attempts
        print(“Account blocked”)
        return
    else:

        # Calling logintry() function to # start the process again
        print(“Try again”)
        logintry()

# Start the program by calling the function
logintry()

OUTPUT:

When Incorrect values are entered:

Enter username:  user
Enter password: pwd
The username or password is incorrect
Try again

Enter username: uname
Enter password: password
The username or password is incorrect
Try again

Enter username: user
Enter password: password
The username or password is incorrect
Account blocked

When the correct values are entered:

Enter username: ADMIN
Enter password: St0rE@1
Login Successful

Page No 171:

Question 2:

 XYZ store plans to give a festival discount to its customers. The store management has decided to give discount on the following criteria: 
 

Shopping AmountDiscount Offered
>=500 and <1000 5%
>=1000 and <2000 8%
>=2000 10%

An additional discount of 5% is given to customers who are the members of the store. Create a program using user defined function that accepts the shopping amount as a parameter and calculates discount and net amount payable on the basis of the following conditions:
Net Payable Amount = Total Shopping Amount – Discount.

ANSWER:

In this program, the shopping amount needs to be compared multiple times, hence ‘elif’ function will be used after first ‘if’.
If the comparison is started from the highest amount, each subsequent comparison will eliminate the need to compare maximum value.

Program:
# function definition,
def discount(amount, member):
    disc = 0
    if amount >= 2000:
        disc = round((10 + member) * amount/100, 2)
    elif amount>= 1000:
        disc = round((8 + member) * amount/100, 2)
    elif amount >= 500:
        disc = round((5 + member) * amount/100, 2)
    payable = amount – disc
    print(“Discount Amount: “,disc)
    print(“Net Payable Amount: “, payable)

amount = float(input(“Enter the shopping amount: “))
member = input(“Is the Customer a member?(Y/N) “)
if(member == “y” or member == “Y”):
    #Calling the function with member value 5
    discount(amount,5)
else:

    #if customer is not a member, the value of member is passed as 0  
    discount(amount, 0)

OUTPUT:
Enter the shopping amount: 2500
Is the Customer a member?(Y/N) Y
Discount Amount:  375.0
Net Payable Amount:  2125.0

​​​Enter the shopping amount: 2500
Is the Customer a member?(Y/N) N
Discount Amount:  250.0
Net Payable Amount:  2250.0

Page No 171:

Question 3:

‘Play and learn’ strategy helps toddlers understand concepts in a fun way. Being a senior student you have taken responsibility to develop a program using user defined functions to help children master two and three-letter words using English alphabets and addition of single digit numbers. Make sure that you perform a careful analysis of the type of questions that can be included as per the age and curriculum.

ANSWER:

This program can be implemented in many ways. The structure will depend on the type of questions and options provided. A basic structure to start the program is given below. It can be built into a more complex program as per the options and type of questions to be included.

Program:
import random

#defining options to take input from the user
def options():
    print(“\n\nWhat would you like to practice today?”)
    print(“1. Addition”)
    print(“2. Two(2) letters words”)
    print(“3. Three(3) letter words”)
    print(“4. Word Substitution”)
    print(“5. Exit”)
    inp=int(input(“Enter your choice(1-5)”))
    
    #calling the functions as per the input
    if inp == 1:
        sumOfDigit()
    elif inp == 2:
        twoLetterWords()
    elif inp == 3:
        threeLetterWords()
    elif inp == 4:
        wordSubstitution()
    elif inp == 5:
        return
    else:
        print(“Invalid Input. Please try again\n”)
        options()

#Defining a function to provide single digit addition with random numbers
def sumOfDigit():
    x = random.randint(1,9)
    y = random.randint(1,9)
    print(“What will be the sum of”,x,”and”,y,”? “)
    z = int(input())
    if(z == (x+y)):
        print(“Congratulation…Correct Answer…\n”)
        a = input(“Do you want to try again(Y/N)? “)
        if a == “n” or a == “N”:
            options()
        else:
            sumOfDigit()
    else:
        print(“Oops!!! Wrong Answer…\n”)
        a = input(“Do you want to try again(Y/N)? “)
        if a == “n” or a == “N”:
            options()
        else:
            sumOfDigit()        

#This function will display the two letter words
def twoLetterWords():
    words = [“up”,”if”,”is”,”my”,”no”]
    i = 0
    while i < len(words):
        print(“\n\nNew Word: “,words[i])
        i += 1
        inp = input(“\n\nContinue(Y/N):”)
        if(inp == “n” or inp == “N”):
            break;
    options()

#This function will display the three letter words
def threeLetterWords():
    words = [“bad”,”cup”,”hat”,”cub”,”rat”]
    i = 0
    while i < len(words):
        print(“\n\nNew Word: “,words[i])
        i += 1
        inp = input(“Continue(Y/N):”)
        if(inp == “n” or inp == “N”):
            break;
    options()

#This function will display the word with missing character
def wordSubstitution():
    words = [“b_d”,”c_p”,”_at”,”c_b”,”_at”]
    ans = [“a”,”u”,”h”,”u”,”r”]
    i = 0
    while i < len(words):
        print(“\n\nWhat is the missing letter: “,words[i])
        x = input()
        if(x == ans[i]):
            print(“Congratulation…Correct Answer…\n”)
        else:
            print(“Oops!!!Wrong Answer…\n”)
        i += 1
        inp = input(“Continue(Y/N):”)
        if(inp == “n” or inp == “N”):
            break;
    options()

#This function call will print the options and start the program
options()

 

Page No 172:

Question 4:

Take a look at the series below:
1, 1, 2, 3, 5, 8, 13, 21, 34, 55…
To form the pattern, start by writing 1 and 1. Add them together to get 2. Add the last two numbers: 1 + 2 = 3. Continue adding the previous two numbers to find the next number in the series. These numbers make up the famed Fibonacci sequence: previous two numbers are added to get the immediate new number. 

ANSWER:

The number of terms of the Fibonacci series can be returned using the program by getting the input from the user about the number of terms to be displayed.
The first two terms will be printed as 1 and 1 and then using ‘for’ loop (n – 2) times, the rest of the values will be printed.
Here, ‘fib’ is the user-defined function which will print the next term by adding the two terms passed to it and then it will return the current term and previous term. The return values are assigned to the variables such that the next two values are now the input terms.

Program:
def fib(x, y):
    z = x + y
    print(z, end=”,”)
    return y, z

n = int(input(“How many numbers in the Fibonacci series do you want to display? “))

x = 1
y = 1

if(n <= 0):
    print(“Please enter positive numbers only”)
elif (n == 1):
    print(“Fibonacci series up to”,n,”terms:”)
    print(x)
else:
    print(“Fibonacci series up to”,n,”terms:”)
    print(x, end =”,”)
    print(y, end =”,”)
    for a in range(0, n – 2):
        x,y = fib(x, y)

    print()

​OUTPUT:
How many numbers in the Fibonacci series do you want to display? 5
Fibonacci series up to 5 terms:
1,1,2,3,5,

Page No 172:

Question 5:

Create a menu driven program using user defined functions to implement a calculator that performs the following:

a) Basic arithmetic operations(+,-,*,/)

b) log10(x), sin(x), cos(x)

ANSWER:

a) Basic arithmetic operations

Program:
#Asking for the user input
x = int(input(“Enter the first number: “))
y = int(input(“Enter the second number: “))

#printing the Menu
print(“What would you like to do?”)
print(“1. Addition”)
print(“2. Subtraction”)
print(“3. Multiplication”)
print(“4. Division”)

#Asking user about the arithmetic operation choice
n = int(input(“Enter your choice:(1-4) “))

#Calculation as per input from the user
if n == 1:
    print(“The result of addition:”,(x + y))
elif n == 2:
    print(“The result of subtraction:”,(x – y))
elif n == 3:
    print(“The result of multiplication:”,(x * y))
elif n == 4:
    print(“The result of division:”,(x / y))
else:
    print(“Invalid Choice”)


b) log10(x), sin(x), cos(x)

Program:
import math

#Providing the Menu to Choose
print(“What would you like to do?”)
print(“1. Log10(x)”)
print(“2. Sin(x)”)
print(“3. Cos(x)”)

#Asking user about the choice
n = int(input(“Enter your choice(1-3): “))

#Asking the number on which the operation should be performed
x = int(input(“Enter value of x : “))
​#Calculation as per input from the user
if n == 1:
    print(“Log of”,(x),”with base 10 is”,math.log10(x))
elif n == 2:
    print(“Sin(x) is “,math.sin(math.radians(x)))
elif n == 3:
    print(“Cos(x) is “,math.cos(math.radians(x)))
else:
    print(“Invalid Choice”)


​​

Read More

Chapter 6 : Flow of Control | Class 11th | Computer Science Important Questions

1. What is the difference between else and elif construct of if statement?

Answer: – else statement does not allow to check the condition, while elif allow to check the condition. elif is use to handle the multiple situations.


2. What is the purpose of range() function? Give one example.

Answer: – The purpose of range() function is to generate a sequence (list) of numbers, started from start and ended at end-1, with the gap of step. i.e. to generate a list.

It becomes useful when we want to execute loop n-times, generate a list of integers.

Syntax :

(a) range(end),

(b) range(start, end),

(c) start(start, end, step)

For example:

>>> range(5) # generate a list like [0,1,2,3,4]

>>> range(2, 6) # generate a list like [ 2, 3, 4, 5]

>>> range(1, 10, 3) #generate a list like [1,4,7]


3. Differentiate between break and continue statements using examples.

Answer: – break and continue both comes under the category of jump statement. In Python, it is used inside the loop statement.

break:

break jumps the control outside the loop. It is use to terminate the execution of loop on the basis of certain condition. You can also use the break without condition (not preferred).

The break statement immediately exits a loop, skipping the rest of the loop’s body. Execution continues with the statement immediately following the body of the loop.

Syntax: break

Example :

for n in range(1, 20): 
    if n == 5: 
       break 
    print(n, end = ' - ')

Output: 1 – 2 – 3 – 4 –

continue:

continue jumps the control to the beginning of the loop for the next iteration. It is use to skip the some parts of body of loop and start the next iteration of loop on the basis of certain condition. You can also use the continue without condition (not preferred).

When a continue statement is encountered, the control jumps to the beginning of the loop for the next iteration.

Syntax: continue

Example :

for n in range(1, 10): 
    if n % 2 == 1: 
       continue 
    print(n, end = ' ')

Output: 2 4 6 8


4. What is an infinite loop? Give one example.

Answer: – A loop, which never terminates called infinite loop. For Example:

# Example 1:

n = 1
while True: 
    print(n, end = ' ')


# Example 2:

n = 1
while n <= 10: 
    print(n, end = ' ')
  

5. Find the output of the following program segments:

(i) 

a = 110
while a > 100:
    print(a)
    a -= 2

Answer: – Output:

110

108

106

104

102


(ii) 

for i in range(20,30,2):
    print(i)

Answer: – Output:

20

22

24

26

28


(iii)

country = 'INDIA'
for i in country:
    print (i)

Answer: – Output:

I

N

D

I

A


(iv) 

i = 0; sum = 0
while i < 9: 
     if i % 4 == 0: 
         sum = sum + i 
     i = i + 2 
print (sum) 

Answer: – Output: 12


(v) 

for x in range(1,4): 
    for y in range(2,5): 
        if x * y > 10:
               break
        print (x * y)

Answer: – Output:

2

3

4

4

6

8

6

9


(vi) 

var = 7
while var > 0:
   print ('Current variable value: ', var)
   var = var - 1
   if var == 3:
       break
   else:
       if var == 6:
          var = var - 1
          continue
   print ("Good bye!")

Answer: – Output:

Current variable value : 7

Current variable value : 5

Good bye!

Current variable value : 4


Programming Exercises

1. Write a program that takes the name and age of the user as input and displays a message whether the user is eligible to apply for a driving license or not. (the eligible age is 18 years).

Answer: – Eligible for a Driving License or not.

name = input("Enter your name : ")
age = int(input("Enter your age : "))
if age >= 18:
   print(name, "You are eligible for driving license")
else:
   print(name, "You are not eligible for driving license")

2. Write a function to print the table of a given number. The number has to be entered by the user.

Answer: – Function to print Table of given number:

def printtable(num):
    for n in range(num, num*10+1, num):
         print(n, end = ' ')
         print()

#main block

Number = int(input("Enter a number :"))
print("Table of", Number)
printtable(Number)

3. Write a program that prints minimum and maximum of five numbers entered by the user.

Answer: – Minimum and Maximum of five numbers

min = 0
max = 0
for count in range(5):
    n = int(print("Enter Number ",count+1))
    if n < min: 
        min = n
    if n > max:
        max = n
print("Maximum : ",max)

print("Minimum : ",min)

4. Write a program to check if the year entered by the user is a leap year or not.

Answer: – Python program to check leap year or not a leap year.

Method – 1

year = int(input("Enter a year :"))
if year % 4 == 0:
   print(year, "is a leap year")
else:
   print(year, "is not a leap year")

Method – 2

year = int(input("Enter a year :"))

if year % 4 == 0 and year % 100 != 0:

   print(year, "is a leap year")

elif year % 100 == 0 and year % 400 == 0):

   print(year, "is a leap year")

else:

   print(year, "is not a leap year")

5. Write a program to generate the sequence: –5, 10, –15, 20, –25….. upto n, where n is an integer input by the user.

Answer: – Program to generate Sequence in Python

# Generate a Sequence in Python

n = int(input("Enter a Number : "))
flag = 1
for t in range(5, n+1,5):
    print(t * flag, end=' ')
    flag = flag * - 1

Output:


6. Write a program to find the sum of 1+ 1/8 + 1/27……1/n3, where n is the number input by the user.

Answer: – Python program to find sum of given sequence:

# Find the sum of 1 + 1/8 + 1/27……1/n^3

n = int(input("Enter a Number : "))
sum = 0
for t in range(1, n+1):
    sum = sum + 1/t**3
    
print("Sum : ", sum)

Output:


7. Write a program to find the sum of digits of an integer number, input by the user.

Answer: – Find the sum of digits of an integer number, input by the user.

Method – I ( Pythonist Way )

# Method - I (Pythonist way)

number = input("Enter a Number : ")
sum = 0
for digit in number:
    sum = sum + int(digit)
print("Sum of Digits of", number, "is", sum)

Method – II (General Way)

# Method - II(General way)

number = int(input("Enter a Number : "))

sum = 0
rem = 0
temp = number

while number > 0:
    rem = number % 10
    sum = sum + rem
    number = number // 10

print("Sum of Digits of", temp, "is", sum)

Output:


8. Write a function that checks whether an input number is a palindrome or not.

[Note: A number or a string is called palindrome if it appears same when written in reverse order also. For example, 12321 is a palindrome while 123421 is not a palindrome]

Answer: – Checks whether an input number is palindrome or not.

#Method - 1 (General)

number = int(input("Enter a Number : "))

rev = 0
rem = 0
temp = number

while number > 0:
    rem = number % 10
    rev = rev * 10 + rem
    number = number // 10
if temp == rev:
    print(temp, "is a palindrome")
else:
    print(temp, "is not a palindrome")
#Method - II ( Its Python Way)

number = input("Enter a Number : ")

reverse = number[::-1]

if number == reverse:
    print(number, "is a palindrome")
else:
    print(number, "is not a palindrome")

Output:


9. Write a program to print the following patterns:

Answer: –


10. Write a program to find the grade of a student when grades are allocated as given in the table below.

Percentage of MarksGrade
Above 90%A
80% to 90%B
70% to 80%C
60% to 70%D
Below 60%E

Percentage of the marks obtained by the student is input to the program.

Answer: – A python program to find grade of students

per = float(input("Enter Percentage Marks : "))

if per > 90 :
    Grade = 'A'
elif per > 80 and per <= 90:
    Grade = 'B'
elif per > 70 and per <= 80:
    Grade = 'C'
elif per >= 60 and per <= 70:
    Grade = 'D'
elif per < 60 :
    Grade = 'E'

print("Your Grade is ", Grade)

Output:


Case Study-based Questions

Let us add more functionality to our SMIS developed in Chapter 5.

6.1 Write a menu driven program that has options to

• accept the marks of the student in five major subjects in Class X and display the same.

• calculate the sum of the marks of all subjects. Divide the total marks by number of subjects (i.e. 5), calculate percentage = total marks/5 and display the percentage.

• Find the grade of the student as per the following criteria:

CriteriaGrade
percentage > 85A
percentage < 85 && percentage >= 75B
percentage < 75 && percentage >= 50C
percentage > 30 && percentage <= 50D
percentage <30Reappear

Let’s peer review the case studies of others based on the parameters given under “DOCUMENTATION TIPS” at the end of Chapter 5 and provide a feedback to them.

Answer: – Marks and Result Calculator

Read More

Chapter 5 : Getting Started with Python | Class 11th | Computer Science Important Questions

1. Which of the following identifier names are invalid and why?

(i) Serial_no. (ii) 1st_Room (iii) Hundred$ (iv) Total Marks (v) Total_Marks (vi) total-Marks (vii) _Percentage (viii) True

Answer: – Valid Identifiers are :

(v) Total_Marks and (vii) _Percentage

Invalids Identifiers are :

(i) Serial_no. : Special Symbol . (dot) is not allowed in identifier name

(ii) 1st_Room : Identifier name can not start with digit.

(iii) Hundred$ : Special Symbol $ is not allowed in identifier name

(iv) Total Marks : Space is not allowed in identifier name

(vi) total-Marks : Special Symbol – (hyphen) is not allowed in identifier name

(viii) True : True is a keyword, and Keyword is not allowed in identifier name

2. Write the corresponding Python assignment statements:

a) Assign 10 to variable length and 20 to variable breadth.

Answer: – length = 10

breadth = 10

b) Assign the average of values of variables length and breadth to a variable sum.

Answer: – sum = (length + breadth) / 2

c) Assign a list containing strings ‘Paper’, ‘Gel Pen’, and ‘Eraser’ to a variable stationery.

Answer: – stationery = [‘Paper’, ‘Gel Pen’, ‘Eraser’]

d) Assign the strings ‘Mohandas’, ‘Karamchand’, and ‘Gandhi’ to variables first, middle and last.

Answer: – first , middle, last = ‘Mohandas’, ‘Karamchand’, ‘Gandhi’

e) Assign the concatenated value of string variables first, middle and last to variable fullname. Make sure to incorporate blank spaces appropriately between different parts of names.

Answer: – fullname = first + ‘ ‘ + middle + ‘ ‘ + last

3. Write logical expressions corresponding to the following statements in Python and evaluate the expressions (assuming variables num1, num2, num3, first, middle, last are already having meaningful values):

a) The sum of 20 and –10 is less than 12.

Answer:- 20 + -10 < 12

b) num3 is not more than 24.
Answer:- num3 < 24

c) 6.75 is between the values of integers num1 and num2.

Answer:- (i) num1 < 6.75 < num2

(ii) num1 < 6.75 and 6.75 < num2

d) The string ‘middle’ is larger than the string ‘first’ and smaller than the string ‘last’.

Answer:- middle > first and middle < last

e) List Stationery is empty.

Answer:- Stationery == []

4. Add a pair of parentheses to each expression so that it evaluates to True.

a) 0 == 1 == 2

Answer: – 0 == ( 1 == 2)
Reason:
0 == (1 == 2) => 0 == False => 0 == 0 => True
b) 2 + 3 == 4 + 5 == 7

Answer: (2 + (3 == 4)) + 5 == 7

Reason:
( 2 + (3 == 4) ) + 5 == 7
==> ( 2 + 0) + 5 == 7
==> 7 == 7 ==> True

c) 1 < -1 == 3 > 4

Answer: (1 < -1) == (3 > 4)

Reason :

(1 < – 1) == (3 > 4) ==> False == False ==> True

5. Write the output of the following:

a) num1 = 4
   num2 = num1 + 1
   num1 = 2
   print (num1, num2)

Answer:- 2 5

b) num1, num2 = 2, 6
   num1, num2 = num2, num1 + 2
   print (num1, num2)

Answer:- 6 4

c) num1, num2 = 2, 3
   num3, num2 = num1, num3 + 1   
   print (num1, num2, num3)

Answer:- [Assume num1, num3 = 2, 3]

Output: 2 4 2

Note: NameError : undefined symbol num3 in line number 2

6. Which data type will be used to represent the following data values and why?

a) Number of months in a year , b) Resident of Delhi or not, c) Mobile number, d) Pocket money, e) Volume of a sphere , f) Perimeter of a square, g) Name of the student, h) Address of the student

Answer: –

a) Number of months in a year: integer, number of month is a positive numeric value.


b) Resident of Delhi or not : Boolean, Resident of Delhi or not can be store as True or False

You can store it as String also, if you want to store value as “Yes” or “No”


c) Mobile number: String, because a mobile number not only contains number, it contain symbols like +, – and space also.

d) Pocket money: float, money can be stored as decimal number.

e) Volume of a sphere : float or integer, it is a numeric value. float is most appropriate.

f) Perimeter of a square: float, it is a numeric value.

g) Name of the student: String, Name can contain alphabet and space.


h) Address of the student: String, Address can contain alphanumeric value

7. Give the output of the following when num1 = 4, num2 = 3, num3 = 2

a) num1 += num2 + num3

print (num1)

Answer: – 9

[ Value of num1 = 4 + (3 + 2) = 9 ]

b) num1 = num1 ** (num2 + num3)

print (num1)

Answer: – 1024

Note : [ num1 = 4 ** (3+2) = 4 ** 5 = 1024 ]

c) num1 *= num2 + c
Answer: – NameError : Undefined symbol ‘c’

d) num1 = ‘5’ + ‘5’
print(num1)
Answer: – 55

Note : num1 = ’55’

e) print(4.00/(2.0+2.0))
Answer: – 1.0

f) num1 = 2 + 9 * (( 3 * 12) – 8)/10

print(num1)

Answer: – 27.2
Note : 2 + 9 * (36 – 8) / 10 = 2 + 9 * 28 / 10 = 2 + 25.2 = 27.2

g) num1 = 24 // 4 // 2

print(num1)

Answer: – 3

Note: num1 = 24 // 4 // 2 => (24//4)//2 => 6 // 2 => 3
h) num1 = float(10)

print (num1)

Answer: – 10.0
i) num1 = int(‘3.14’)

ValueError: invalid literal for int() with base 10: ‘3.14’ . It should be like num1 = int(float(‘3.14’))

print (num1)

Answer: – 3.14 , if statement given in (m) is correct and executed properly.


k) print(10 != 9 and 20 >= 20)

Answer:- True

l) print(10 + 6 * 2 ** 2 != 9//4 -3 and 29 >= 29/9)

Answer:- True

m) print(5 % 10 + 10 < 50 and 29 <= 29)

Answer: – True


n) print((0 < 6) or (not(10 == 6) and (10<0)))

Answer:- True

Read More

Chapter 4 : Introduction to Problem Solving | Class 11th | Computer Science Important Questions

Introduction to Problem Solving Class 11 Questions and Answers

1. Write pseudocode that reads two numbers and divide one by another and display the quotient.
Answer –
Input num1
Input num2
Calculate div = num1 / num2
Print div

2. Two friends decide who gets the last slice of a cake by flipping a coin five times. The first person to win three flips wins the cake. An input of 1 means player 1 wins a flip, and a 2 means player 2 wins a flip. Design an algorithm to determine who takes the cake?
Answer –
Set p1 = 0
Set p2 = 0
For i in range (5):
Input coin
If coin = 1 then
P1 += 1
Elif coin = then
P2 += 1
If p1 > 2 then
P1 wins
Elif p2 > 2 then
P2 wins

3. Write the pseudocode to print all multiples of 5 between 10 and 25 (including both 10 and 25).
Answer –
FOR num := 10 to 25 DO
IF num % 5 = 0 THEN
PRINT num
END IF
END LOOP

4. Give an example of a loop that is to be executed a certain number of times.
Answer –
SET i: = 1
FOR i: = 1 to 10 do
PRINT i
END LOOP

5. Suppose you are collecting money for something. You need ` 200 in all. You ask your parents, uncles and aunts as well as grandparents. Different people may give either ` 10, ` 20 or even ` 50. You will collect till the total becomes 200. Write the algorithm.
Answer –
Step 1 : Start
Step 2 : Set money := 0
Step 3 : While Loop (money <200)
Input money
Step 4 : money = money + money
Step 5 : End Loop
Step 6 : Stop

6. Write the pseudocode to print the bill depending upon the price and quantity of an item. Also print Bill GST, which is the bill after adding 5% of tax in the total bill.
Answer –
INPUT Item
INPUT price
CALCULATE bill := Item * price
PRINT bill
CALCULATE tax := bill * (5 / 100)
CALCULATE GST_Bill := bill + tax
PRINT GST_Bill

7. Write pseudocode that will perform the following:
a) Read the marks of three subjects: Computer Science, Mathematics and Physics, out of 100
b) Calculate the aggregate marks
c) Calculate the percentage of marks
Answer –
INPUT computer, maths, phy
COMPUTE average := (computer + maths + phy) / 3
COMPUTE percentage := (average / 300) * 100
PRINT average
PRINT percentage

8. Write an algorithm to find the greatest among two different numbers entered by the user.
Answer –
INPUT num1, num2
IF num1 > num2 THEN
PRINT num1
ELSE IF num2 > num1 THEN
PRINT num2
END IF

9. Write an algorithm that performs the following: Ask a user to enter a number. If the number is between 5 and 15, write the word GREEN. If the number is between 15 and 25, write the word BLUE. if the number is between 25 and 35, write the word ORANGE. If it is any other number, write that ALL COLOURS ARE BEAUTIFUL.
Answer –
INPUT num
IF num >=5 AND num < 15 THEN
PRINT ‘GREEN’
ELSE IF num >= 15 AND num < 25 THEN
PRINT ‘BLUE’
ELSE IF num >= 25 AND num < 35 THEN
PRINT ‘ORANGE’
ELSE
PRINT ‘ALL COLOURS ARE BEAUTIFUL’
END IF

10. Write an algorithm that accepts four numbers as input and find the largest and smallest of them.
Answer –
INPUT max
SET min := max
FOR i: = 1 to 3 do
INPUT num
IF num<max THEN
SET max :=num
ELSE
SET min := num
END LOOP
PRINT max
PINT min

11. Write an algorithm to display the total water bill charges of the month depending upon the number of units consumed by the customer as per the following criteria:
• for the first 100 units @ 5 per unit
• for next 150 units @ 10 per unit
• more than 250 units @ 20 per unit
Also add meter charges of 75 per month to calculate the total water bill .
Answer –
INPUT units
SET bill := 0
IF units > 250 THEN
CALCULATE bill := units * 20
ELIF units <= 100 THEN
CALCULATE bill := units * 5
ELSE
CALCULATE bill := 100 * 5 + (units – 100) * 10
END IF
END IF
CALCULATE totalBill := bill + 75
PRINT totalBill

12. What are conditionals? When they are required in a program?
Answer – Conditionals are programming language elements used in computer science that execute various computations or actions based on whether a boolean condition supplied by the programmer evaluates to true or false.

When a software needs to calculate a result based on a given circumstance, they are necessary (s).

14. Following is an algorithm for going to school or college. Can you suggest improvements in this to include other options?
Reach_School_Algorithm
a) Wake up
b) Get ready
c) Take lunch box
d) Take bus
e) Get off the bus
f) Reach school or college
Answer –
a) Wake up
b) Brush your teeth
c) Take bath
d) Dress up
e) Eat breakfast
f) Take lunch box
g) Take Bus
h) Get off the bus
i) Reach school or college

15. Write a pseudocode to calculate the factorial of a number (Hint: Factorial of 5, written as 5!=5 4 3 21 ×××× ).
Answer –
INPUT num
SET fact := 1, i := 1
WHILE i <= num DO
CALCULATE fact := fact * i
INCREASE i by 1
END LOOP
PRINT fact

16. Draw a flowchart to check whether a given number is an Armstrong number. An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.
Answer –

flow chart of Armstrong number

17. Following is an algorithm to classify numbers as “Single Digit”, “Double Digit” or “Big”.
Classify_Numbers_Algo
INPUT Number
IF Number < 9
“Single Digit”
Else If Number < 99
“Double Digit”
Else
“Big”
Verify for (5, 9, 47, 99, 100 200) and correct the algorithm if required
Answer –
INPUT Number
IF Number <= 9
“Single Digit”
Else If Number <= 99
“Double Digit”
Else
“Big”

18. For some calculations, we want an algorithm that accepts only positive integers upto 100.

Accept_1to100_Algo
INPUT Number
IF (0<= Number) AND (Number <= 100)
ACCEPT
Else
REJECT
a) On what values will this algorithm fail?
b) Can you improve the algorithm?


Answer –
INPUT number
IF (number>0) AND (number <=100)
ACCEPT
Else
REJECT

Read More

Chapter 3 : Emerging Trends | Class 11th | Computer Science Important Questions

Emerging Trends Class 11 Questions and Answers

1. List some of the cloud-based services that you are using at present.
Answer – Some of the cloud based services are
a. Infrastructure as a Service (IaaS) – The IaaS providers can offer different kinds of computing infrastructure because of its speed of deployment, example Amazon Web Services, Google Compute Engine and Microsoft Azure.

b. Platform as a Service (PaaS) – The facility provided by the cloud, where a user can install and execute an application without worrying about the underlying infrastructure and their setup. example, Database Server, Web Server, Programming language execution environment.

c. Software as a Service (SaaS) – SaaS provides on-demand access to application software, usually requiring a licensing or subscription by the user. example, Google Doc, Microsoft Office 365, Drop Box etc.

Emerging Trends Class 11 Questions and Answers

2. What do you understand by the Internet of Things? List some of its potential applications.
Answer – The ‘Internet of Things’ is a network of devices that have an embedded hardware and software to communicate (connect and exchange data) with other devices on the same network.
Some of the potential applications of IoT are –
a. Smart Door Locks
b. Medical Sensors
c. Smart Mobiles
d. Smart Refrigerators
e. Smartwatches
f. Smart Fire alarms

3. Write short notes on the following:
a) Cloud Computing
b) Big data and its Characteristics
Answer –
a) Cloud Computing – In the field of information technology, cloud computing is a new trend where computer-based services are supplied via the Internet or the cloud and are accessible to the user from any location using any device. The services include hardware (servers), databases, storage, and software.

b) Big data and its Characteristics – Big data is a collection of information from numerous sources, and it is frequently defined by five factors: volume, value, diversity, velocity, and veracity.

Emerging Trends Class 11 Questions and Answers

4. Explain the following along with their applications.
a) Artificial Intelligence
b) Machine Learning
Answer –
a) Artificial Intelligence – Artificial intelligence (AI) is the simulation of human intelligence in devices that have been designed to behave and think like humans. The statement can also be used to refer to any computer that demonstrates characteristics of the human intellect, like learning and problem-solving.

b) Machine Learning – Machine Learning is a subfield of Artificial Intelligence to mimic intelligent human behaviour. Similar to how people approach problem-solving, artificial intelligence systems are employed to carry out complex jobs.

Emerging Trends Class 11 Questions and Answers

5. Differentiate between cloud computing and grid computing with suitable examples.
Answer – Because of cloud computing, the system is always accessible. In order to provide a setting where several computers can work together to complete a task as needed, grid computing refers to a network of the same or various types of computers. Also capable of working alone is each computer.

Example of Cloud computing – Gmail, Dropbox, Facebook, Amazon Web Services etc.
Example of Grid Computing – Online Games, Entertainment Industry, Database, WebLogic Application Servers etc.

6. Justify the following statement:
“Storage of data is cost-effective and time saving in cloud computing.”
Answer – Because the cloud vendor manages everything, using cloud storage is both time and money efficient. We don’t need to spend money on hardware resources, power, or support to manage and store data.

7. What is on-demand service? How it is provided in cloud computing?
Answer – On-demand self-service, customers can purchase, customize, and install apps via cloud service catalogues without the help of a skilled professional. The resources could be kept up by the user’s company or supplied by a cloud service provider.

Emerging Trends Class 11 Questions and Answers

8. Write examples of the following:
a) Government provided cloud computing platform
b) Large scale private cloud service providers and the services they provide
Answer –
a) Government provided cloud computing platform – The Government of India’s cloud computing project seeks to maximize government ICT spending while accelerating the delivery of e-services across the nation. Example, AWS and IBM.

b) Large scale private cloud service providers and the services they provide – An industry leader, Amazon Web Services (AWS) enables businesses all over the world to fully or partially create their digital infrastructure using the cloud.

Emerging Trends Class 11 Questions and Answers

9. A company interested in cloud computing is looking for a provider who offers a set of basic services, such as virtual server provisioning and on demand storage that can be combined into a platform for deploying and running customized applications.
What type of cloud computing model fits these requirements?
a) Platform as a Service
b) Software as a Service
c) Application as a Service
d) Infrastructure as a Service
Answer –
d) Infrastructure as a Service

10. If the government plans to make a smart school by applying IoT concepts, how can each of the following be implemented in order to transform a school into IoT-enabled smart school?
a) e-textbooks
b) Smart boards
c) Online Tests
d) Wifi sensors on classrooms doors
e) Sensors in buses to monitor their location
f) Wearables (watches or smart belts) for attendance monitoring.

Answer –
a) e-textbooks – E-textbooks are available through online libraries or other web services.
b) Smart boards – In the class smart boards can helps to diliver the content to the students and helps to improve teaching learning process
c) Online Tests – IoT should be used to centralize the test and track student progress.
d) WIFI sensors on classrooms doors – Wi-Fi sensors may be used to keep an eye on the kids. These sensors can also record the students’ attendance.
e) Sensors in buses to monitor their location –The school and parents can obtain visibility, control, and safety into the GPS location of the school buses as well as arrival and departure times at each stop along the route.

f) Wearables (watches or smart belts) for attendance monitoring – Utilizing a wearable gadget to take attendance will make it easier to track students’ attendance.

Emerging Trends Class 11 Questions and Answers

11. Five friends plan to try a startup. However, they have a limited budget and limited computer infrastructure. How can they avail the benefits of cloud services to launch their startup?
Answer – They require servers, a huge amount of storage, and sophisticated infrastructure to deploy a number of applications in order to establish their firm. These are accessible through cloud computing infrastructure as a service (IaaS) providers like Amazon Web Services (AWS), Microsoft Azure, and others.

12. Governments provide various scholarships to students of different classes. Prepare a report on how blockchain technology can be used to promote accountability, transparency and efficiency in distribution of scholarships?
Answer – The blockchain technology is based on the idea of shared, decentralized databases that are replicated across all computers. Therefore, if the government makes this technology available, all scholarship applicants will have access to read the applications of other applicants.

Emerging Trends Class 11 Questions and Answers

13. How are IoT and WoT related?
Answer – Both IoT and WoT can be used to connect to a network and communicate with several devices. They can act as a bridge between other devices, allowing communication through an app, a web service, or any other network-capable device.

14. Match the columns:
You got a reminder to take medication – Smart Health
You got an SMS alert that you forgot to lock the door – Home Automation
You got an SMS alert that parking space is available near your block – Smart Parking
You turned off your LED TV from your wrist watch – Smart Wearable

Read More

Chapter 2 : Encoding Schemes and Number System | Class 11th | Computer Science Important Questions

Encoding Schemes and Number System Class 11 important Terms

Encoding Schemes

A computer can only understand binary (0s and 1s) numbers. As a result, whenever a key is touched on a keyboard, is internally translated into a special code known as unique code and then converted to binary. for example, Pressing the key “A” causes is internally mapped to the value 65 (the code value), which is then translated to its corresponding binary value for the computer to comprehend. encoding helps the system to give unique number to the characters, symbols or numbers. 

What is encoding?

Encoding is the process of transforming data into an encryption process that is equivalent using a particular code. Some of the well-known encoding schemes are described in the following sections. There are three most popular encoding in computer system.
a. American Standard Code for Information Interchange (ASCII)
b. Indian Script Code for Information Interchange (ISCII)
c. Unicode ( Most popular coding method)

American Standard Code for Information Interchange (ASCII)

For the purpose of standardizing character representation, ASCII was created. The most widely used coding technique is still ASCII. ASCII represented characters using 7 bits. There are just 2 binary digits 0 and 1. Consequently, the total amount of distinct characters on the 27 = 128 on an English keyboard can be represented by a 7-bit ASCII code.

CharacterDecimal ValueCharacterDecimal ValueCharacterDecimal Value
Space32@64`96
!33A65a97
34B66b98
#35C67c99
$36D68d100
%37E69e101
&38F70f102
39G71g103
(40H72h104
)41I73i105

Encoding Schemes and Number System Class 11 Notes

Indian Script Code for Information Interchange (ISCII)

A standard for coding Indian scripts it is develop in the middle of the 1980s, India developed a system of characters known as ISCII. It is an 8-bit representation of Indian languages. which means it can represent 28=256 characters.

Unicode

Every character in the Unicode Standard has a specific number, independent of the platform, gadget, programme, or language. As a result of its wider adoption by modern software vendors, data may now be sent without corruption across a wide range of platforms, gadgets, and programmes.

The most popular method for identifying characters in text in almost any language is now Unicode. Unicode uses three different encoding formats: 8-bit, 16-bit, and 32-bit.

09050906090709080909090A090B090C

Encoding Schemes and Number System Class 11 Notes

Number System

What is Number System?

A way to represent (write) numbers is called a number system. There are a specific set of characters or literals for each number system. It is the mathematical notation for consistently employing digits or other symbols to represent the numbers in a particular set.
There are four different types of number system
a. Decimal Number System
b. Binary Number
c. Hexadecimal Number
d. Octal Number

I

Encoding Schemes and Number System Class 11 Notes

Decimal Number System

Decimal is single digit number system in computer. The decimal number system consists of ten single-digit numbers 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. This number system is also known as based-10 number.

Image by NCERT via cbseacademic.com
Binary Number System

Binary Number is used in computer system because computer only understands the language of the two digits 0 and 1 (low/high). Binary number is also known as the base-2 system. Examples of binary numbers include 111111.01, 1011101, and 1001011.

DecimalBinary
00
11
210
311
4100
5101
6110
7111
81000
91001

Binary value for (0–9) digits of decimal number system

Encoding Schemes and Number System Class 11 Notes

Octal Number System

Sometimes, a binary number is so large that it becomes difficult to manage. Octal number system was devised for compact representation of the binary numbers. Octal number system is called base-8 system.

Octal DigitDecimal Value3 -bit Binary Number
00000
11001
22010
33011
44100
55101
66110
77111

Decimal and binary equivalent of octal numbers 0–7

Hexadecimal Number System

Hexadecimal numbers are also used for compact representation of binary numbers. It consists of 16 unique symbols (0–9, A–F), and is called base16 system. In hexadecimal system, each alphanumeric digit is represented as a group of 4 binary digits because 4 bits (24=16) are sufficient to represent 16 alphanumeric symbols.

Hexadecimal SymbolDecimal Value4-bit Binary Number
000000
110001
220010
330011
440100
550101
660110
770111
881000
991001
A101010
B111011
C121100
D131101
E141110
F151111

Decimal and binary equivalent of hexadecimal numbers 0–9, A–F

Encoding Schemes and Number System Class 11 Notes

Applications of Hexadecimal Number System

Every byte’s memory location is described using the hexadecimal number system. For computer professionals, these hexadecimal numbers are also simpler to read and write than binary or decimal numbers.

Memory Address example using hexadecimal Number System

Decimal NumberBinary NumberHexadecimal Number
760100110037FD00
380010011037FD02

Color code example using hexadecimal Number System

Colour NameDecimalBinaryHexadecimal
Black(0,0,0)(00000000,00000000,00000000)(00,00,00)
Yellow(255,255,0)(11111111,11111111,00000000)(FF,FF,00)

Conversion between Number Systems

Although digital computers understand binary numbers, humans most often utilise the decimal number system. Octal and hexadecimal number systems are used to make the binary representation easier for us to understand. Lets see some of the number conversion system –

Conversion from Decimal to other Number Systems

To convert a decimal number to any other number system (binary, octal or hexadecimal), use the steps
given below.
Step 1: Divide the given number by the base value (b) of the number system in which it is to be converted
Step 2: Note the remainder
Step 3: Keep on dividing the quotient by the base value and note the remainder till the quotient is zero
Step 4: Write the noted remainders in the reverse order (from bottom to top)

Encoding Schemes and Number System Class 11 Notes

Decimal to Binary Conversion

Binary equivalent of 65 is (1000001)2. Let us now convert a decimal value to its binary representation and verify that the binary equivalent of (65)10 is (1000001)2.

decimal to binary
Decimal to Octal Conversion

Since the base value of octal is 8, the decimal number is repeatedly divided by 8 to obtain its equivalent octal number. The octal equivalent of letter “A” by using its ASCII code value (65)10 is calculated in below figure –

decimal to octal
Decimal to Hexadecimal Conversion

Since the base value of hexadecimal is 16, the decimal number is repeatedly divided by 16 to obtain its equivalent hexadecimal number. The hexadecimal equivalent of letter ‘A’ using its ASCII code (65)10 is calculated as shown below –

decimal to hexadecimal

Conversion from other Number Systems to Decimal Number System

We can use the following steps to convert the given number with base value b to its decimal equivalent, where base value b can be 2, 8 and 16 for binary, octal and hexadecimal number system, respectively.

Step 1: Write the position number for each alphanumeric symbol in the given number
Step 2: Get positional value for each symbol by raising its position number to the base value b symbol in the given number
Step 3: Multiply each digit with the respective positional value to get a decimal value
Step 4: Add all these decimal values to get the equivalent decimal number

Encoding Schemes and Number System Class 11 Notes

Binary Number to Decimal Number

Binary number system has base 2, the positional values are computed in terms of powers of 2. Using the above mentioned steps we can convert a binary number to its equivalent decimal value as shown below –

binary to decimal
Binary to Decimal
Octal Number to Decimal Number

The following example shows how to compute the decimal equivalent of an octal number using base value 8.

octal to decimal
Octal to Decimal
Hexadecimal Number to Decimal Number

For converting a hexadecimal number into decimal number, use steps given in this section with base value 16 of hexadecimal number system. Use decimal value equivalent to alphabet symbol of hexadecimal number in the calculation, as shown below –

hexadecimal to decimal
Read More