Professional Documents
Culture Documents
R AND PYTHON
PROGRAMMING
.
Practical 02
Python Basic Syntaxes
Lochana Rajamanthri
PYTHON STRINGS
a = "hello"
print(a[1]) e
b = "world"
print(b[2:5]) rld
PYTHON STRINGS
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
COMMAND-LINE STRING INPUT
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
PYTHON LISTS
index() Returns the index of the first element with the specified
value
cars.index("Volvo")
PYTHON LISTS
List Functions:
pop() Removes the element at the specified position
cars.pop(2)
List Functions:
Length of a list
Return the number of elements in the cars array:
x = len(cars)
PYTHON CONTROL STRUCTURES
Sequence
Selection/ Condition
Repetition/ Iteration/ Loops
PYTHON CONDITIONS
Operators
a = 33
b = 200
if b > a:
print("b is greater than a")
PYTHON CONDITIONS
If – elif statement:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
PYTHON CONDITIONS
If – elif - else statement: e d
Nes t
a = 200 I F?
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Exercise 01
Consider the string (text = "Hello SLIIT“) and write the output of the following.
a) text[:3]
b) text [ : 5]
c) text [ 2 :]
d) text [2 : len(text)]
Exercise 02
Write a Python program to create a list with three elements and perform the
following tasks.
b) Accept values of length and breadth of a rectangle from user and check if it is
square or not.
Write a program to accept a mark from the user and display the grade according to
the following criteria.
Marks Grade
>90 A
>80 and <=90 B
>=60 and <= 80 C
Below 60 D
Exercise 07
Write a program to accept three integers from a user and display the largest number.
LOOPS/ REPETITIONS/ ITERATIONS
Python Loops
With the while loop we can execute a set of statements as long as the condition is
true.
2 4 3 5 7 6
LOOPS/ REPETITIONS/ ITERATIONS
for x in range(6):
print(x)
Q1. Take 10 integers from keyboard using loop and print their average value on the
screen.
Q3. Given a list iterate it and display numbers which are divisible by 5 and if you
find number greater than 150 stop the loop iteration.
List1 = [12, 15, 32, 42, 55, 75, 122, 132, 150, 180, 200]
FUNCTIONS
CREATING A FUNCTION
def my_function():
print("Hello from a function")
CALLING A FUNCTION
my_function()
FUNCTIONS
CREATING 2D ARRAY
List1 = [ [ 0 for i in range (7) ] for j in range (6) ]
List2 = [ [“A”] * 7 ] * 6
ACCESS ELEMENTS
Marks[2][3] = 0
THE END