0% found this document useful (0 votes)
32 views

3) LogicalOperator-algo

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

3) LogicalOperator-algo

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

CS114 - Fundamental of Programming

Week 03:

Dr. Nazia Perwaiz


[email protected]

vision.seecs.edu.pk
Recap – week 02

• Variables (integers, float, string, Boolean, lists***, dictionaries***)


• Getting user input (default input variable type is ???)
• Typecasting of variables
• Comments (single-line comments, multi-line comments)
• Operators
• arithmetic (+, -, *, /, %, //, **)
• assignment/ augmented assignment (=, +=, -=, *=, /=, %=, //=, **=)
• comparison (==, !=, >, <, >=, <=)
• logical (and, or, not)***
• Strings

*** Topics are to be covered in detail yet


Recap – Strings

• A string is a series of characters


• Use single quotes or double quotes to create strings
• For multi-line string use triple single quotes
• Use the backslash character \ to escape quotes in strings
• str = “This is Ahmad\’s book. “
• Use \n for newline.
• str = “This is Ahmad\’s book.\n He likes English Literture. “
• Use + sign for string concatenation
• Use * sign for string replication
• Use len() function to check length of string
• Use the str[n] to access the character at the position n of the string str
• Use slicing to extract a substring from a string
• sub_string = str[start:end] // substring includes the character at the start and excludes the string at
the end
Contents

• String Slicing …. (continued)


• Strings are immutable

• Logical Operators

• Algorithm
• Pseudocode
• Flowchart
String Slicing
• String starting index [0]
• String end index [len(str)-1] // string length minus 1

• String slicing [start:end] //start inclusive, end


exclusive
[start:] //slice from
start index to the end
[end:] //slice from
beginning to index end-1

str = "Python String"

print(str[4]) # output: ?
print(str[0]) # output: ?
print(str[2:5]) # output: ?
5 print(str[5:]) # output: ?
String Slicing
• String starting index [0]
• String end index [len(str)-1] // string length minus 1

• String slicing [start:end] //start inclusive, end


exclusive
[start:] //slice from
start index to the end
[end:] //slice from
beginning to index end-1

str = "Python String"

print(str[4]) # output: o
print(str[0]) # output: P
print(str[2:5]) # output: tho
6 print(str[5:]) # output: n String
String Slicing
• For a negative index, Python returns the character starting from the end of the string.

str = "Python String"

print(str[-1]) # output: g
print(str[-6:-1]) # output: Strin
print(str[-6:]) # output: String
print(str[:-6]) # output: Python

print(str[:]) # output: ?
print(str[ ]) # output: ?
print(str[-13:-1]) # output: ?
print(str[-13:]) # output: ?
7
Strings are Immutable
• Python strings are immutable. It means that you cannot change the string.
• You’ll get an error if you update one or more characters in a string

str = "Python String"


str[0] = 'J' # TypeError: 'str' object does not support item
assignment

• In order to modify a string, you need to create a new string from the existing string
• For Example:
str = "Python String"
new_str = 'J' + str[1:]
print(new_str) # Output?
Comparison Operators - review
• When you compare two variable, Python returns the result as a Boolean value
• For Example: a=20, b=10
x=a>b
print(x) # output: True
______________________________
print(a >= b) # output: True
print(a < b) # output: False
print(a <= b) # output: False .
print(a == b) # output: False
print(a != b) # output: True
print('a' < ‘b’) # output: True
print('a' > 'b‘) # output: False
Boolean Function: bool()
• Use the bool() function to test if a value is True or False.
• For Example:
x = 100
bool(x) # returns True for any non-zero number (all negatives and positives)
______________________________
x=0
bool(x) # returns False for zero number
______________________________
x=''
bool(x) # returns False for empty string
______________________________
x = 'hello'
bool(x) # returns True for non-empty string
______________________________
Logical Operators
• Output of comparison operators or bool() function: ???

• It is used to combine conditional statements (if a given condition is true)


• Example: if (a>b)
• Logical operators perform Logical AND, Logical OR, and Logical NOT operations.
Logical Operators
• Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to
combine conditional statements
• For Example:
a = True
b = False

print(a and b) # Print a and b is False

print(a or b) # Print a or b is True

print(not a) # Print not a is False


Algorithm
• An algorithm refers to a set of rules/instructions that step-by-step define how a work is to be
executed in order to get the expected results.

How to make tea?

1. Take water into kettle


2. Heat the water
3. Check if the water is boiled
4. After boiling of water, make tea
Pseudocode
• A pseudocode is a method of writing an algorithm using high-level description
• Pseudocode is an informal way of writing a program
• Represents the algorithm of the program in natural language and mathematical notations.

FUNCTION make_tea():
How to make tea?
SET water into kettle
FOR water heating, check:
1. Take water into kettle IF water is boiled THEN
2. Heat the water
3. Check if the water is boiled make tea
4. After boiling of water, make tea ELSE
continue boiling
END IF
END FOR
END FUNCTION

Algorithm
Pseudocode
• Pseudocode constructs/ keywords are used to describe the control flow of the algorithm.
• SEQUENCE represents linear tasks sequentially performed one after the other.
• WHILE a loop with a condition at its beginning.
• REPEAT-UNTIL a loop with a condition at the bottom.
• FOR another way of looping.
• IF-THEN-ELSE a conditional statement changing the flow of the algorithm.
• CASE the generalization form of IF-THEN-ELSE.
FUNCTION make_tea():
Pseudocode
SET water into kettle
Rules to write Pseudocode: FOR water heating, check:
IF water is boiled THEN

• Always capitalize the keywords/ constructs. make tea


ELSE
continue boiling
• Make only one statement per line. END IF
END FOR
• Indent to show hierarchy, improve readability, and show END FUNCTION
nested constructs.
• Always end multi-line sections using any of the END keywords
(ENDIF, ENDWHILE, etc.).
• Keep your statements programming language independent.
• Keep it simple, concise and readable.
Flowchart
• Flowcharts have some standard symbols that allow them to be read and understood

17
Algorithm vs Pseudocode vs Flowchart
• How to make tea?

FUNCTION make_tea():

SET water into kettle


1. Take water into kettle FOR heat water, check:
2. Heat the water IF water is boiled THEN
3. Check if the water is boiled
4. After boiling of water, make make tea
tea ELSE
keep boiling
END IF
END FOR
END FUNCTION
Algorithm vs Pseudocode vs Flowchart
• Find the sum of numbers from 1 to N:
1. Take the input N for the total numbers
2. Set the values of index i = 1, and the sum = 0
3. Start a loop from 1 to N
4. Every loop, add the value of i into SUM, and increment i
5. Print the value of sum

FUNCTION SUM():

GET the value of N


SET the value of index i=1, and SUM=0
FOR index FROM 1 to N:
IF index i <= N THEN
ADD SUM and i
INCREMENT i
END IF
END FOR

END FUNCTION
Algorithm vs Pseudocode
• Find if a character is Vowel:

1. Declare a variable ch of character datatype.


2. Read one character from the user and store it in a
variable "ch"
3. Compare "ch" with the vowels in both upper and lower
case. If it matches print "vowel”, otherwise end the
program.

Start
SET character type variable ch
Read ch from User
IF (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E'
|| ch == 'i' || ch == 'I' || ch == 'o' ||
ch == 'O' || ch == 'u' || ch == 'U' ) THEN
RETURN "Vowel“
END IF
END
Algorithm vs Pseudocode
• Find if a character is Vowel or Consonant:

1. Declare a variable ch of character datatype.


2. Read one character from the user and store it in a
variable "ch"
3. Compare "ch" with the vowels in both upper and lower
case. If it matches print "vowel" else we print
"Consonant".

1. Start
2. SET character type variable ch
3. Read ch from User
4. IF (ch == 'a' || ch == 'A' || ch == 'e' || ch ==
'E' || ch == 'i' || ch == 'I' || ch == 'o' ||
ch == 'O' || ch == 'u' || ch == 'U' ) THEN
5. RETURN "Vowel"
6. ELSE
7. Print "Consonant"
8. END IF
9. END
Algorithm vs Pseudocode
• Find if a character exists in a string:

1. Start from the leftmost chracter of str[] and one by


one compare x with each element of str[].
2. If x matches with a character, return the index.
3. If x doesn’t match with any of character, return -1.

FUNCTION linearSearch(str, searchTerm):

FOR index FROM 0 -> length(str):


IF str[index] == searchTerm THEN
RETURN index
ELSE
RETURN -1
END IF
END FOR
END FUNCTION

You might also like