0% found this document useful (0 votes)
32 views12 pages

Lab Task # 3 Introduction To Programming With Python

The document provides an introduction to various Python concepts like strings, lists, arrays, functions, classes/objects and conditions (if/else statements). It includes examples of creating and manipulating strings, lists, arrays. Examples of defining and calling functions with/without parameters and return values are also given. Creating classes and objects in Python is also briefly explained. Students will learn to create strings and lists, use if/else conditions, create and call functions, work with arrays, and create classes and objects in Python.

Uploaded by

Maryam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
32 views12 pages

Lab Task # 3 Introduction To Programming With Python

The document provides an introduction to various Python concepts like strings, lists, arrays, functions, classes/objects and conditions (if/else statements). It includes examples of creating and manipulating strings, lists, arrays. Examples of defining and calling functions with/without parameters and return values are also given. Creating classes and objects in Python is also briefly explained. Students will learn to create strings and lists, use if/else conditions, create and call functions, work with arrays, and create classes and objects in Python.

Uploaded by

Maryam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 12

ISRA UNIVERSITY

Department of Computer Science

(CSAI-412) Artificial Intelligence


Lab Task # 03
Fall 2023
Instructor: Areeba Naeem
Date: 17-JAN-2023
WEEK # 3

Introduction to Basics of Python Continued….


After completing this lab students will be able to
 Create Strings and use its built-in function in Python
 Access Python program in Command line.
 Create Lists and use its built-in functions
 If Else conditions with AND, OR operators
 Create and Call Functions in Python
 Create Array and use its built-in function
 Create Classes and Objects

Python Strings

String literals in python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".

Example 1.

Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"

print(a[1])

Example 2.

Substring. Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"

print(b[2:5])
Example 3.

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "

print(a.strip()) # returns "Hello, World!"

Example 4.

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

a = "Hello, World!"

print(len(a))

Example 5.

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

a = "Hello, World!"

print(a.lower())

Example 6.

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

a = "Hello, World!"

print(a.upper())

Example 7.

The replace() method replaces a string with another string:

a = "Hello, World!"

print(a.replace("H", "J"))

Example 8.

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

Python allows for command line input.

That means we are able to ask the user for input.

The following example asks for the user's name, then, by using the input () method, the program
prints the name to the screen:

Example 1.

print("Enter your name:")

x = input()

print("Hello, " + x)

Typecasting

Int( )

Float( )

Str( )
Access Items

You access the list items by referring to the index number:

Example 1.

Print the second item of the list:

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

print(thislist[1]).

Task # 1: Create a List of ten string elements using Python and print them on screen.

Change Item Value

To change the value of a specific item, refer to the index number:

Example 1.

Change the second item:

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

thislist[1] = "blackcurrant"

print(thislist)

Loop Through a List

You can loop through the list items by using a for loop:

Example 1.

Print all items in the list, one by one:

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

for x in thislist:

print(x)

Task # 2: Create a list of 10 string elements and print them using for loop.
Check if Item Exists

To determine if a specified item is present in a list use the in keyword:

Example 1.

Check if "apple" is present in the list:

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

if "apple" in thislist:

print("Yes, 'apple' is in the fruits list")

List Length

To determine how many items a list has, use the len() method:

Example 1.

Print the number of items in the list:

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

print(len(thislist))

Add Items

To add an item to the end of the list, use the append() method:

Example 1.

Using the append() method to append an item:

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

thislist.append("orange")

print(thislist)
To add an item at the specified index, use the insert() method:

Example 1.

Insert an item as the second position:

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

thislist.insert(1, "orange")

print(thislist)

Remove Item

There are several methods to remove items from a list:

Example 1.

The remove() method removes the specified item:

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

thislist.remove("banana")

print(thislist)

The del keyword can also delete the list completely:

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

del thislist

print(thislist) #this will cause an error because "thislist" no longer exists.

The clear() method empties the list:

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

thislist.clear()

print(thislist)

The list() Constructor

It is also possible to use the list() constructor to make a list.

Example

Using the list() constructor to make a List:


thislist = list(("apple", "banana", "cherry")) # note the double round-brackets

print(thislist)

List Methods
Python has a set of built-in methods that you can use on lists.

Method Description

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

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the
current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Python If ... Else

Python Conditions and If statements

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

An "if statement" is written by using the if keyword.


Example 1.

If statement:

a = 33

b = 200

if b > a:

print("b is greater than a")

Indentation

Python relies on indentation, using whitespace, to define scope in the code. Other programming
languages often use curly-brackets for this purpose.

Example 1.

If statement, without indentation (will raise an error):

a = 33

b = 200

if b > a:

print("b is greater than a") # you will get an error

Elif

The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".

a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

Else

The else keyword catches anything which isn't caught by the preceding condition

Example

a = 200
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")

Task # 03: Create a program of taking three inputs from user and compare them and print
which one is greater.

Task # 04: Create a program of taking five subjects marks using for loop and print
Percentage and Grade of Students.

Short Hand If

If you have only one statement to execute, you can put it on the same line as the if statement.

Example

One line if statement:

if a > b: print("a is greater than b")

Short Hand If ... Else

If you have only one statement to execute, one for if, and one for else, you can put it all on the same
line:

Example
print("A") if a > b else print("B")

You can also have multiple else statements on the same line:

Example with 03 conditions


print("A") if a > b else print("=") if a == b else print("B")
And

The and keyword is a logical operator, and is used to combine conditional statements:

Example
Test if a is greater than b, AND if c is greater than a:
if a > b and c > a:
print("Both conditions are True")
Or

Test if a is greater than b, OR if a is greater than c:


if a > b or a > c:
print("At least one of the conditions is True")

Python Functions

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a Function

In Python a function is defined using the def keyword:

def my_function():
print("Hello from a function")
Calling a Function

To call a function, use the function name followed by parenthesis:

def my_function():
print("Hello from a function")
my_function()
Parameters
Example 1
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Default Parameter Value


Example 2.
def my_function(country = "Norway"):
print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

Return Values
To let a function return a value, use the return statement

def my_function(x):
return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Task # 5: Create 4 different function for basic arithmetic operations.

Arrays

Arrays are used to store multiple values in one single variable:

Example 1:

Create an array containing car names:

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

Access the Elements of an Array

You refer to an array element by referring to the index number.

Example

Get the value of the first array item:

x = cars[0]

Modify the value of the first array item:

cars[0] = "Toyota"

Use the len() method to return the length of an array (the number of elements in an array).

Example

return the number of elements in the cars array:

x = len(cars)

Looping Array Elements

You can use the for in loop to loop through all the elements of an array.

Example
Print each item in the cars array:

for x in cars:
print(x)
Adding Array Elements

You can use the append() method to add an element to an array.

Add one more elements to the cars array:


cars.append("Honda")

Task # 06: Create a program which takes 10 values and store them in to an array A and 10
values in array B and store their addition in array C and print on screen.

Python Classes/Objects

Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class:

Create a class named MyClass, with a property named x:

class MyClass:
x=5
Create Object

Now we can use the class named myClass to create objects:

Example

Create an object named p1, and print the value of x:

p1 = MyClass()
print(p1.x)

Task # 7: Create a program of classes and objects of your own choice.

You might also like