You are on page 1of 27

MN404 Fundamentals of Operating Systems and Programming

Problem Based Learning (PBL) T3 2020

Submission Due: A weekly Report duly signed by the tutor has to be submitted on Moodle
the same day before 11.55 pm.

Total Marks = 5% of total marks for 12 weeks of participation and submission

Note to Students:
Students, on weekly basis, work on the activities as per the activity chart and prepare a
handwritten document each week. The document will be signed by the respective tutor,
scanned and submitted on Moodle before 11.55 pm on the same day.

Marks will be given only to students who attend and participate during 1 hour PBL tutorial
class. Submission on Moodle is mandatory as an evidence of the participation.

Prepared by: Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa Jul;y 2020
MN404 Fundamentals of Operating Systems and Java Programming
Page # of total pages

PBL Activity Chart

Week PBL Topic(s)


1 What makes a Good OS?

2 Unique Features of Different types of OS and their Applications


( Windows, Unix/ Linux, Android, MAC)

3 Basic concepts of Algorithms


4 Software development - Data Types Expressions

5 Case Study: Income Tax Calculator


6 Programming examples reinforcing their learning in their lecture class
7 Programming examples reinforcing their learning in their lecture class
8 Programming examples reinforcing their learning in their lecture class
9 Programming examples reinforcing their learning in their lecture class
10 Programming examples reinforcing their learning in their lecture class
11 Programming examples reinforcing their learning in their lecture class
12 Revision

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 3 of 27

PBL 1:
Introduce the concept of PBL and how are they carried out.
Play the following videos and let them answer the questions below and submit.

https://www.youtube.com/watch?v=WP3uDglbPiI

https://www.youtube.com/watch?v=yhYyMRMwfJc

https://www.youtube.com/watch?v=gxhxcvBuanU

https://www.youtube.com/watch?v=GjNp0bBrjmU

Answer the following:


Brief on evolution of OS
List all the functions of an OS?
What are batch processing systems?
Necessity and Importance of OS

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 4 of 27

PBL 2: Operating Systems Fundamentals


Description of the PBL exercise:
Your tutor will conduct the PBL session as a flipped class. Therefore, you should study the
respective Activity/ business case of the corresponding week before you come to the class.
Students must prepare in advance and participate in the discussion during PBL. Group of 4
students shall be formed and the task will be assigned in the previous week by the tutor.

Each group shall present and discus the activity assigned, for 5-6 min. After all the
presentations are completed, individual student shall document and summarize the activity
and take signature of the tutor to upload it on Moodle.

Each Group shall prepare the salient features of 3 categories of OS assigned in the previous
week. Students have to discuss/ present on the unique features of Different types of OS and
their Applications
1. Hand Programmed machines
2. Serial Processing
3. Batch Processing
4. Multiprogramming
5. Multiprocessor System
6. Time sharing
7. Desktop System
8. Client Server OS
9. Distributed Operating System
10. Clustered System
11. Cloud/ Ubiquitous
12. Realtime Operating System
13. Handheld System
14. Windows
15. Unix/Linux
16. MacOS
17. Android
18. Solaris

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 5 of 27

19. Virtual OS

Homework and Prerequisites for the following PBL:


https://www.youtube.com/watch?v=ZRfkLHQvIws
https://www.youtube.com/watch?v=6hfOvs8pY1k

Groups of 3 -4 students shall be formed and the following week’s activities shall be
distributed.

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 6 of 27

PBL 3: Algorithm
Description of the PBL exercise:
The students shall understand the concept of algorithm and come prepared for the
discussions.
Based on the video links (prerequisites) provided in the previous week, each group shall
develop at least one algorithm from the following list and present/discuss the same.

What’s an Algorithm?

An algorithm is a detailed step-by-step instruction set or formula for solving a problem or


completing a task. In computing, programmers write algorithms that instruct the computer
how to perform a task.

When you think of an algorithm in the most general way (not just in regards to computing),
algorithms are everywhere. A recipe for making food is an algorithm, the method you use to
solve addition or long division problems is an algorithm, and the process of folding a shirt or
a pair of pants is an algorithm. Even your morning routine could be considered an algorithm!

However, “algorithm” is a technical term with a more specific meaning than “recipe”, and
calling something an algorithm means that the following properties are all true:
 An algorithm is an unambiguous description that makes clear what has to be
implemented. In a recipe, a step such as “Bake until done” is ambiguous because it
doesn’t explain what “done” means. A more explicit description such as “Bake until
the cheese begins to bubble” is better. In a programming context “Choose a large
number” is vague: what is large? 1 million, 1 billion, or 100? Does the number have
to be different each time, or can the same number be used on every run?

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 7 of 27

 An algorithm expects a defined set of inputs. For example, it might require two
numbers where both numbers are greater than zero. Or it might require a word, or a
list of zero or more numbers.
 An algorithm produces a defined set of outputs. It might output the larger of the two
numbers, an all-uppercase version of a word, or a sorted version of the list of
numbers.
 An algorithm is guaranteed to terminate and produce a result, always stopping after a
finite time. If an algorithm could potentially run forever, it wouldn’t be very useful
because you might never get an answer.

An Example Algorithm to find sum of the two numbers

Step 1: Start

Step 2: Declare variables num1, num2 and sum.

Step 3: Read values num1 and num2.

Step 4: Add num1 and num2 and assign the result to sum.

sum←num1+num2

Step 5: Display sum

Step 6: Stop

Example algorithm to find the largest among three different numbers entered by user.

Step 1: Start
Step 2: Declare variables a,b and c.
Step 3: Read variables a,b and c.
Step 4: If a>b
If a>c
Display a is the largest number.
Else
Display c is the largest number.
Else
If b>c
Display b is the largest number.
Else
Display c is the greatest number.

Step 5: Stop

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 8 of 27

What output is generated?

In algorithm:
1. Assign sum=0, A=0, B=1, i=1
2. Get the no. of terms up to which u want to generate the Fibonacci no, i.e., n.
3.Add A and B to get the next Fibonacci number {sum = A+B}
4. Assign the value of B to A i.e. A=B
5. Assign the value of sum to B i.e. B=sum
6. Write the value of sum to get next Fibonacci number in the series.
7. increment i with 1 i.e. i=i+1 and repeat step 3,4,5,6 with the last value of i=n(n
is the no. of terms that you want to generate Fibonacci no. series.)
8. Stop

Tasks to be completed:

1. Write an algorithm to identify if a given number is odd or even


2. Write an algorithm to find average of three numbers.
3. Write an algorithm to find cube of a number
4. Write an algorithm to check whether a character is a Vowel or Consonant.

Resources: http://algorithms.openmymind.net/
https://www.tynker.com/blog/articles/ideas-and-tips/how-to-explain-
algorithms-to-kids/

Each group shall summarize the learning and upload the document on Moodle after the
tutor has duly signed with date before 11.55pm the same day.

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 9 of 27

PBL 4: Algorithm
Description of the PBL exercise:
Students shall perform this PBL in group of two formed at the end of previous week’s PBL.
Later part of the PBL they shall discuss the outcome of the learning and write a report of the
same.
Each group shall summarize the learning and upload the document on Moodle after the
tutor has duly signed with date before 11.55pm of the same day.

1. Write an algorithm to swap two numbers


Start
Read a and b
c=a
a=b
b=c
Stop.

Let a = 200, b = 400 and trace the algorithm

2. What output is generated?

Algorithm:

Step 1: Input Low(1), High(10)


Step 2: Count = 1
Step 4: While (Count < = High)
Repeat steps 4 through 6
Step 5: Print Count
Step 6: Count = Count + 1

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 10 of 27

3. Write a script that inputs a line of plaintext and a distance value and outputs an
encrypted text using a Caesar cipher. The script should work for any printable
characters.

Let the students carry out some examples manually.


For example, the word WELCOME becomes YGNEQOG with a distance of 2

Assign values 0, 1 ,2 3…. to a, b, c, … z


Encrypted alphabet value = old alphabet value + distance
Find the new alphabet that is representing the computed encrypted alphabet value.

Reverse the procedure to decrypt.

Think over what happens to alphabets y and z?

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 11 of 27

PBL 5 CASE Study: Income Tax Calculator

Each year, nearly everyone with an income faces the unpleasant task of computing his
or her income tax return. We start with the customer request phase.

Request

The customer requests a program that computes a person’s income tax.

Analysis

Analysis often requires the programmer to learn some things about the problem
domain, in this case, the relevant tax law. For the sake of simplicity, let’s assume the
following tax laws:

 All taxpayers are charged a flat tax rate of 20%.


 All taxpayers are allowed a $10,000 standard deduction.
 For each dependent, a taxpayer is allowed an additional $3,000 deduction.
 Gross income must be entered to the nearest penny.
 The income tax is expressed as a decimal number.

Another part of analysis determines what information the user will have to provide. In
this case, the user inputs are gross income and number of dependents. The program
calculates the income tax based on the inputs and the tax law and then displays the
income tax. Figure 1 shows the proposed terminal-based interface. Characters in italics
indicate user inputs. The program prints the rest. The inclusion of an interface at this
point is a good idea because it allows the customer and the programmer to discuss the
intended program’s behaviour in a context understand- able to both.

Fig. 1: The user interface for the income tax calculator

Design

During analysis, we specify what a program is going to do. In the next phase, design, we
describe how the program is going to do it. This usually involves writing an algorithm. In
fact, algorithms are more often written in a somewhat stylized version of English called
pseudocode. Here is the pseudocode for our income tax program:

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 12 of 27

Input the gross income and number of dependents

Compute the taxable income using the formula

Taxable income = gross income - 10000 - (3000 * number of dependents)

Compute the income tax using the formula

Tax = taxable income * 0.20 Print the tax

Although there are no precise rules governing the syntax of pseudocode, in your
pseudocode you should strive to describe the essential elements of the program in a clear
and concise manner. Note that this pseudocode closely resembles Python code, so the
transition to the coding step should be straightforward.

Implementation:

Given the preceding pseudocode, an experienced programmer would now find it easy to
write the corresponding Python program. For a beginner, on the other hand, writing the
code can be the most difficult part of the process.

Program: taxform.py

Author: Ken Lambert

Compute a person’s income tax.

1. Significant constants
tax rate
standard deduction
deduction per dependent
2. The inputs are
gross income
number of dependents
3. Computations:
taxable income = gross income - the standard deduction - a deduction for each
dependent
income tax = is a fixed percentage of the taxable income
4. The outputs are the income tax
TAX_RATE = 0.20
STANDARD_DEDUCTION = 10000.0
DEPENDENT_DEDUCTION = 3000.0

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 13 of 27

# Request the inputs


grossIncome = float(input("Enter the gross income: ")) numDependents = int(input("Enter
the number of dependents: "))

# Compute the income tax


taxableIncome = grossIncome - STANDARD_DEDUCTION –
DEPENDENT_DEDUCTION * numDependents
incomeTax = taxableIncome * TAX_RATE

# Display the income tax

print("The income tax is $" + str(incomeTax))

Testing
If there are no syntax errors, we will be able to enter a set of inputs and view the results.
However, a single run without syntax errors and with correct outputs provides just a slight
indication of a program’s correctness. Only thorough testing can build confidence that a program
is working correctly. Testing is a deliberate process that requires some planning and discipline
on the programmer’s part. It would be much easier to turn the program in after the first
successful run to meet a deadline or to move on to the next assignment. But your grade, your job,
or people’s lives might be affected by the slipshod testing of software.

Testing can be performed easily from an IDLE window. The programmer just loads the program
repeatedly into the shell and enters different sets of inputs. The real chal- lenge is coming up
with sets of inputs that can reveal an error. An error at this point, also called a logic error or a
design error, is an unexpected output.

A correct program produces the expected output for any legitimate input. The tax calculator’s
analysis does not provide a specification of what inputs are legitimate, but common sense
indicates that they would be numbers greater than or equal to 0. Some of these inputs will
produce outputs that are less than 0, but we will assume for now that these outputs are
expected. Even though the range of the input numbers on a computer is finite, testing all of the
possible combinations of inputs would be impractical. The challenge is to find a smaller set of
inputs, called a test suite, from which we can conclude that the program will likely be correct for
all inputs. In the tax program, we try inputs of 0, 1, and 2 for the number of dependents. If the
program works correctly with these, we can assume that it will work correctly with larger values.
The test inputs for the gross income are a number equal to the standard deduction and a number
twice that amount (10000 and 20000, respectively). These two values will show the cases of a
minimum expected tax (0) and expected taxes that are less than or greater than 0. The program
is run with each possible combination of the two inputs. Table 2-1 shows the possible
combinations of inputs and the expected outputs in the test suite.

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 14 of 27

If there is a logic error in the code, it will almost certainly be caught using these data. Note that
the negative outputs are not considered errors. We will see how to prevent such computations in
the next chapter.

Generally in a project you should write a program that contains an introductory docstring. This
documentation should describe what the program will do (analysis) and how it will do it (design
the program in the form of a pseudocode algorithm). Include suitable prompts for all inputs and
label all outputs appropriately. After you have coded a program, be sure to test it with a
reasonable set of legitimate inputs.

The tax calculator program of the case study outputs a floating-point number that might show
more than two digits of precision. Use the round function to modify the program to display at
most two digits of precision in the output number.

Come up with another similar application and discuss all the phases of the software
development as in the Tax calculation example.

Applications could be something along the line:

1. To compute your salary based on the regular hours and after-hours working time period.

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 15 of 27

PBL 6:

Discuss all the phases of a software development life cycle with regards to the following
applications development.:
To compute your term grade based on the information provided in UD

Inputs: For instance - Sample set 1:


Assessment Type Raw marks Percentage
In Class Test 20/30 10*20/30 = 6.66
Assignment 1 45/60 45*20/60 = 15
Assignment 2 55/80 55*20/80 =13.75
Lab/PBL 9/10 9
Final Exam 35/60 35*40/60 = 23.33
67.74

In summary:
The program must perform the following:
 Read the assessments marks for all five components. Provide a good interface with
appropriate prompts.
 Compute (analyse+ design) the grade based on the policies/strategies mentioned in
UD.
 Generate outputs and also provide decisions for supplementary assessments and
deferred tests.

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 16 of 27

PBL 7

1) A Python program to guess a number between 1 to 9.

Note: User is prompted to enter a guess. If the user guesses wrong then the
prompt appears again until the guess is correct, on successful guess, user will
get a "Well guessed!" message, and the program will exit.

Python Code:
import random

target_num, guess_num = random.randint(1, 10), 0

while target_num != guess_num:

guess_num = int(input('Guess a number between 1 and 10 until you get it


right : '))

print('Well guessed!')

Exercises:

a) Write an algorithm for the code provided.


b) Write down all possible test cases.
c) Change the code to guess a number between 1 to 100

2) Write a Python program to get the Fibonacci series

Note: The Fibonacci Sequence is the series of numbers:


0, 1, 1, 2, 3, 5, 8, 13, 21, ....
Every next number is found by adding up the two numbers before it.
def fib (n):
if( n == 0):
return 0
else:
x=0
y=1
for i in range(1,n):

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 17 of 27

z = (x + y)
x=y
y=z
return y

for i in range(40):
print (fib(i))

Exercises:

d) Write an algorithm for the code provided.


e) Write down all possible test cases.
f) Change the code to print the 100 Fibonacci numbers

3)

Write a Python program to check the validity of a password (input from users).

Validation :

 At least 1 letter between [a-z] and 1 letter between [A-Z].

 At least 1 number between [0-9].

 At least 1 character from [$#@].

 Minimum length 6 characters.

 Maximum length 16 characters.

import re

p= input("Input your password")

x = True

while x:

if (len(p)<6 or len(p)>12):

break

elif not re.search("[a-z]",p):

break

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 18 of 27

elif not re.search("[0-9]",p):

break

elif not re.search("[A-Z]",p):

break

elif not re.search("[$#@]",p):

break

elif re.search("\s",p):

break

else:

print("Valid Password")

x=False

break

if x:

print("Not a Valid Password")

Exercises:

g) Write an algorithm for the code provided.


h) Provide 5 samples of testcases including both valid and invalid ones.

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 19 of 27

PBL 8:
1)

Write a Python program to calculate a dog's age in dog's years.


Note: For the first two years, a dog year is equal to 10.5 human years. After
that, each dog year equals 4 human years.

h_age = int(input("Input a dog's age in human years: "))

if h_age < 0:
print("Age must be positive number.")
exit()

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 20 of 27

elif h_age <= 2:


d_age = h_age * 10.5
else:
d_age = 21 + (h_age - 2)*4

print("The dog's age in dog's years is", d_age)

Exercises:

a) Write an algorithm for the program provided


b) Write all possible test cases

2)

Write a Python program to create the multiplication table (from 1 to 10) of a


number.

n = int(input("Input a number: "))

# use for loop to iterate 10 times


for i in range(1,11):
print(n,'x',i,'=',n*i)

Exercise:

Extend this program to print the multiplication table ( from 1 to 10) of numbers 20, 21, 22,
24, and 25.

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 21 of 27

3)

Write a Python program to construct the following pattern, using a nested loop
number.
Expected Output:
1
22
333
4444
55555
666666
7777777
88888888
999999999

for i in range(10):
print(str(i) * i)

Write down the logic used in detail.

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 22 of 27

PBL 9:

Write an algorithm

 to generate a password with the following rules:


 Length to be greater than 8 characters
 To include MIT as part of the password
 To include at least one number and a special char ( $#@*) as part of
the password
 to encrypt the password before storing it in the database.
 To decrypt the password
 To display the password generated as per the guidelines by the user, its encrypted
version and also its decrypted version.

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 23 of 27

PBL 10
# Strips all whitespace characters from both ends.
<str> = <str>.strip()
# Strips all passed characters from both ends.
<str> = <str>.strip('<chars>')

# Splits on one or more whitespace characters.


<list> = <str>.split()
# Splits on 'sep' str at most 'maxsplit' times.
<list> = <str>.split(sep=None, maxsplit=-1)
# Splits on line breaks. Keeps them if 'keepends'.
<list> = <str>.splitlines(keepends=False)
# Joins elements using string as separator.
<str> = <str>.join(<coll_of_strings>)

# Checks if string contains a substring.


<bool> = <sub_str> in <str>
# Pass tuple of strings for multiple options.
<bool> = <str>.startswith(<sub_str>)
# Pass tuple of strings for multiple options.
<bool> = <str>.endswith(<sub_str>)
# Returns start index of first match or -1.
<int> = <str>.find(<sub_str>)
# Same but raises ValueError if missing.
<int> = <str>.index(<sub_str>)

# Replaces 'old' with 'new' at most 'count' times.


<str> = <str>.replace(old, new [, count])
# True if str contains only numeric characters.
<bool> = <str>.isnumeric()
# Nicely breaks string into lines.
<list> = textwrap.wrap(<str>, width)

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 24 of 27

# Converts int to unicode char.


<str> = chr(<int>)
# Converts unicode char to int.
<int> = ord(<str>

>>> ord('0'), ord('9')


(48, 57)
>>> ord('A'), ord('Z')
(65, 90)
ord('a'), ord('z')
(97, 122

>>> s = "Python string"


>>> print(s)
Python string

>>> #using single quote and double quote


>>> s = "A Poor Woman's Journey."
>>> print(s)
A Poor Woman's Journey.

>>> s = "I read the article, 'A Poor Woman's Journey.'"


>>> print(s)
I read the article, 'A Poor Woman's Journey.'

>>> s = 'dir "c:\&temp\*.sas" /o:n /b > "c:\&temp\abc.txt"'


>>> print(s)
dir "c:\&temp\*.sas" /o:n /b > "c:\&tempbc.txt"

>>> #print multiple lines


>>> s = """jQuery exercises
JavaScript tutorial
Python tutorial and exercises ..."""
>>> print(s)
jQuery exercises
JavaScript tutorial
Python tutorial and exercises ...

>>> s = 'jQuery exercises\n JavaScript tutorial\n Python tutorial


and exercises ...'

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 25 of 27

>>> print(s)
jQuery exercises
JavaScript tutorial
Python tutorial and exercises ...

Access character(s) from a string:

Characters in a string can be accessed using the standard [ ] syntax, and like
Java and C++, Python uses zero-based indexing, so if str is 'hello' str[2] is 'l'. If
the index is out of bounds for the string, Python raises an error.
>>> a = "Python string"

>>> print (a)

Python string

>>> b = a[2]

>>> print(b)

>>> a[0]

'P'

>>>

Copy
Explanation :

 The above statement selects character at position number 2 from a and assigns it to b.

 The expression in brackets is called an index that indicates which character we are
interested.

 The index is an offset from the beginning of the string, and the offset of the first letter is
zero.

We can use any expression, including variables and operators, as an index


>>> a = "Python string"

>>> b = a[4+3]

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 26 of 27

>>> print(b)

>>>

Copy
The value of the index has to be an integer.
>>> a = "Python string"

>>> a[2.3]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: string indices must be integers

>>>

Copy
Negative indices:

Alternatively, we can use negative indices, which count backward from the
end of the

Index -1 gives the last character.


>>> a = "Python string"

>>> a[-2]

'n'

>>> a[-8]

'n'

>>>

Python String concatenation:

The '+' operator is used to concatenate two strings.


>>> a = "Python" + "String"

>>> print(a)

PythonString

>>>

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020
MN404 Fundamentals of OS and Programming Page 27 of 27

Copy
You can also use += to concatenate two strings.
>>> a = "Java"

>>> b = "Script"

>>> a+=b

>>> print(a)

JavaScript

>>>

Copy
Using '*' operator:
>>> a = "Python" + "String"

>>> b = "<" + a*3 + ">"

>>> print(b)

<PythonStringPythonStringPythonString>

>>>

Copy
String length:

len() is a built-in function which returns the number of characters in a string:


>>> a = "Python string"

>>> len(a)

13

>>> a[13]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: string index out of range

>>> a[12]

'g'

>>>

Prepared by: Dr Nandini Sidnal Moderated by: Prof Savitri Bevinakoppa July 2020

You might also like