0% found this document useful (0 votes)
129 views36 pages

Practical 02

This document provides an overview of Python programming concepts including strings, lists, control structures, loops, functions, and 2D arrays. It includes examples of basic string methods like upper(), split(), and indexing. It also demonstrates how to define and access list elements, common list methods, if/elif/else conditional statements, while and for loops using range(). Functions are defined with and without parameters and return values. Finally, it shows how to create and access elements of a 2D array in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views36 pages

Practical 02

This document provides an overview of Python programming concepts including strings, lists, control structures, loops, functions, and 2D arrays. It includes examples of basic string methods like upper(), split(), and indexing. It also demonstrates how to define and access list elements, common list methods, if/elif/else conditional statements, while and for loops using range(). Functions are defined with and without parameters and return values. Finally, it shows how to create and access elements of a 2D array in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

IM3690

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

The len() method returns the length of a string:


a = "Hello, World!"
print(len(a))  13

The upper() method returns the string in upper case:


a = "Hello, World!"
print(a.upper())  HELLO, WORLD!
PYTHON STRINGS

The split() method splits the string into substrings if it


finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
COMMAND-LINE STRING INPUT

print("Enter your name:")


x = input()
print("Hello, " + x)

y = input("Enter your name: ")


print("Hello, " + y)
PYTHON OPERATORS

+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
PYTHON LISTS

cars = ["Ford", "Volvo", "BMW"]


PYTHON LISTS
Access the Elements of a list:

Get the value of the first array item:


x = cars[0]

Modify the value of the first array item:


cars[0] = "Toyota"
PYTHON LISTS
List Functions:

append()  Adds an element at the end of the list


cars.append("Benz")

clear()  Removes all the elements from the list


cars.clear()

copy()  Returns a copy of the list


my = cars.copy()
PYTHON LISTS
List Functions:
count()  Returns the number of elements with the specified value
cars = ["Ford", "Volvo", "BMW“, "Volvo"]
cars.count("Volvo")

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)

remove()  Removes the first item with the specified value


cars.remove("Volvo")

reverse()  Reverses the order of the list


cars.reverse()
PYTHON LISTS

List Functions:

sort()  Sorts the list


cars.sort()

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

Python supports the usual logical conditions from mathematics:


• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
PYTHON CONDITIONS
If statement:

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.

Fruits = [‘Apple’, ‘Orange’, ‘Banana’]


a) Calculate the length of the list.

b) Append list1 to above created list.


list1 = [‘aaa’, 35]

c) Insert ‘Grapes’ to index 2.


Exercise 03

Swap the first element and last element of a list.

Fruits = [‘Apple’, ‘Orange’, ‘Banana’]


Exercise 04

a) Write a Python program to check whether a number is Positive or Negative.

b) Accept values of length and breadth of a rectangle from user and check if it is
square or not.

c) Write a program to check if a year is a leap year or not. If a year is divisible by 4


then it is a leap year but if the year is century year like 2000 , 1900, 2100 then it
must be divisible by 400.
Exercise 05

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

Python has two primitive loop commands:


• while loops
• for loops

Python doesn’t have post condition loops.


LOOPS/ REPETITIONS/ ITERATIONS

THE WHILE LOOP

With the while loop we can execute a set of statements as long as the condition is
true.

Print i as long as i is less than 6:


i=1
while i < 6:
print(i)
i += 1
LOOPS/ REPETITIONS/ ITERATIONS

THE WHILE LOOP

Q1. Print 5 stars (*).


Q2. Print even numbers from 1 to 10.
Q3. Develop a calculator to repetitively run four functions as +, -, * and /. You need
to take inputs for numbers and for operators. If the user need to exit from the
calculator, he/she may enter Q.
Q4. Construct the following list and replace all the values by its’ square value.

2 4 3 5 7 6
LOOPS/ REPETITIONS/ ITERATIONS

THE FOR LOOP

Print each fruit in a fruit array:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
LOOPS/ REPETITIONS/ ITERATIONS

THE FOR LOOP

The range() Function

for x in range(6):
print(x)

• Note that range(6) is not the values of 0 to 6, but the values 0 to 5.


LOOPS/ REPETITIONS/ ITERATIONS

THE FOR LOOP

The range() Function

The range() function defaults to 0 as a starting value, however it is possible to specify


the starting value by adding a parameter: range(2, 6), which means values from 2 to
6 (but not including 6):

for x in range(2, 6):


print(x) 2345
LOOPS/ REPETITIONS/ ITERATIONS

THE FOR LOOP

The range() Function

Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)
LOOPS/ REPETITIONS/ ITERATIONS

THE FOR LOOP

Q1. Take 10 integers from keyboard using loop and print their average value on the
screen.

Q2. Write a Python program to find the largest number in a list.

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

INPUT PARAMETERS DEFAULT PARAMETER VALUE


def my_function(country = "Norway"):
def my_function(fname):
print("I am from " + country)
print(fname + " Hello")
my_function("Sweden")
my_function("Emil")
my_function("India")
my_function("Tobias")
my_function()
my_function("Linus")
my_function("Brazil")
FUNCTIONS

RETURN VALUES PYTHON DATETIME


def my_function(x): import datetime
return 5 * x x = datetime.datetime.now()
print(x)
print(my_function(3))
print(my_function(5))
print(my_function(9))
PYTHON 2D ARRAYS

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

You might also like