Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Python Lesson 5 Basic Strings, Conditions Loops and Functions

Python Lesson

Uploaded by

Xuan Zheng Lim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python Lesson 5 Basic Strings, Conditions Loops and Functions

Python Lesson

Uploaded by

Xuan Zheng Lim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Basic Strings, Conditions

Loops and Functions


Dr. Saima Nisar
PhD (IT), MS (IT), BBA (Hons.)
saima.nisar@xmu.edu.my
A2-448
Learning Objectives

• In this chapter, you will learn:


o Understand and apply basic string operations in Python,
including indexing, slicing, and character counting.
o Utilize conditional statements and comparison operators to
implement logic in Python programs.
o Implement loops (for and while) to efficiently iterate over data
structures.
o Define, call, and return values from functions to promote code
reusability and organization.
Strings
• Sequences of characters used to represent text in Python. Strings can be
created by enclosing characters in either single quotes (‘ ’) or double
quotes (“ “). If the string itself contains single quotes, using double quotes
to enclose the string will prevent syntax errors. For example, to assign the
string It’s a sunny day, the correct code is:

my_string = “It’s a sunny day”

my_string = ‘It’s a sunny day’ # this will cause a syntax error


String Operations
• Strings can be printed directly using the print() function. For instance, to
display the string, the code would be:

print(my_string) # Outputs: It's a sunny day

• To determine the number of characters in a string, including spaces, the


len() function is used:

print(len(my_string)) # Outputs: 16

• This function helps in understanding the total number of characters in the


string
Accessing Characters by Index
• String in Python are indexed, allowing access to individual characters using
their positions, starting from 0. For example, to access the first character:

print(my_string[0]) # Outputs: I

• The output will be I not 1, because my_string[0] referes to the first


character of the string my_string, and if my_string = “we are learning
Python”, the first character is the letter w.
• In Python, string indexing starts from 0, so my_string[0] accesses the first
character of the string.
Counting Occurrences of a Characters in a
String
• The count() method is available to find how many times a specific character
appears in a string:

print(my_string.count(‘s’)) # Outputs: 2

• This illustrates the frequency of the letter s in the string.


Slicing a Strings
• Slicing allows for extracting a portion of a string by specifying start and stop
indices. To obtain the substring:

print(my_string[7:12]) # Outputs: sunny

I T ‘ S A S U N N Y D A Y
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

• The slice will include the characters from the start index up to, but not
including, the end index.
Omitting Indexes in Slicing
• The slicing syntax [:6] includes all characters from index 0 up to (but not
including) index 6. This means it will take characters from index 0 to index
5.
print(my_string[:6]) # Outputs: “It’s a“

• When you reverse the slicing syntax and use [6:], it means it start from the
index 6 and go to the end of the string.

print(my_string[6:]) # Outputs: “ sunny day”

• The substring will include everything starting from index 6, which is a


space(‘ ’), and it will continue to the end of the string.
Negative Indexing
• Negative indexes count from the end of the string.

print(my_string[-10:]) # Outputs: sunny day

• The substring “ sunny day” includes the space from the negative index -10
and everything after it.
Reversing Strings
• Strings can be reversed easily by using slicing with a step of -1:

print(my_string[::-1]) # Outputs: yad ynnus t'sI


Conditions in Python
• Conditions enable performing different actions based on specific scenarios.
Boolean logic is the foundation, where expressions evaluate to either True
or False.
Comparison Operators:

• Comparison Operators:

== Equal > Greater than


!= Not equal <= Less than or equal to
< Less than >= Greater than or equal to

x=5
print(x == 5) # Outputs: True
Boolean Operators:

• Conditions can be combined using and, or and not. For instance, to check
if x is greater than 2 and less than 10:

X=5 X=5
If x > 2 and x < 10: If x > 2 or x < 10:
print(“x is between 2 and 10”) print(“x is between 2 and 10”)
# Outputs: x is between 2 and 10 # Outputs: x is between 2 and 10

X=15
If not x < 10:
print(“x is not less than 10”)
# Outputs: x is not less than 10
Using in Operator:

• To verify if a value exists in a collection, such as a list, the in operator can


be applied:

colors = [‘blue’, ‘red’, ‘green’, ‘pink’]

if ‘green’ in colors:
print(‘Green is one of the color‘)
else:
print(‘Green is not one of the color’)

# Outputs: Green is one of the color


Loops in Python:

• There are two types of loops in Python, for and while. Loops facilitate
executing a block of code repeatedly based on specific conditions.
• The for Loop
• For loops iterate over a given sequence. numbers = [2,3,5,7]
• In this example: for num in numbers:
• numbers is the list value [2, 3, 5, 7] print(num)
• num is the variable name used in the
# Outputs: 2
for loop to represent each value in the list 3
during iteration 5
7
Loops in Python:
• A while loop continues executing as long as a specified condition remains
True.
• In this example:
count = 0
• The variable count is initialized to 0 While count <5:
• The while loop runs as long as count is less print(count)
than 5. count += 1

# Outputs: 0
Inside the loop, print(count) output the current
1
value of count 2
The count+=1 statement increments count by1 3
after each iteration. 4
Loops in Python:
• A break statement used to exit a for loop or a while loop, whereas continue
is used to skip the current block, and return to the "for" or "while"
statement.
for number in range(10):
for number in range(10): if number % 2 == 0:
if number == 5: continue # Skip even
break # Exit the loop numbers
when number equals 5 print(number)
print(number) # Outputs: 1, 3, 5, 7, 9

• Break will print numbers 0 through 4. In contrast, using continue would skip
the current iteration. In short, even numbers are skipped.
Functions in Python:
• Functions are a convenient way to divide your code into useful blocks,
allowing us to order our code, make it more readable, reuse it and save
some time. Also functions are a key way to define interfaces so
programmers can share their code.
Note: Function is a piece of code that a program uses many times.
• A block is an area of code of written in the format of:

block_head:
1st block line
2nd block line
...
Defining Function:
• A function is defined by specifying its name and any parameters it may
take.
• To define a function, use the def keyword.

def greet():
print(“Hello, Welcome!”)
Calling Function:
• When calling a function in Python, you simply write the function's name
followed by parentheses (). If the function requires any arguments, you
place them within the parentheses.

def greet():
print(“Hello, Welcome!”)
greet()
Explanation:

• Function Name: greet is the name of the function


• Calling the Function: You call it by writing greet() this executes
the code inside the function
Returning Values:
• Functions can return values using the return keyword. For instance

def greet():
return "Hello, Welcome!" # Return the greeting instead of printing it

# Calling the function and storing the result in a variable


greeting_message = greet()

# Now print the returned value


print(greeting_message) # Outputs: Hello, Welcome!
Thank you

You might also like