0% found this document useful (0 votes)
7 views22 pages

Week Three & Four (Ss 1 - Python)

The document covers Python data types, including numeric, text, sequence, mapping, set, boolean, binary, and none types, as well as the concept of casting between these types. It explains implicit and explicit casting with examples, and emphasizes the importance of understanding data types to avoid errors. Additionally, the document introduces Python strings, their manipulation, and methods for string operations such as slicing, concatenation, and formatting.

Uploaded by

semilore
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views22 pages

Week Three & Four (Ss 1 - Python)

The document covers Python data types, including numeric, text, sequence, mapping, set, boolean, binary, and none types, as well as the concept of casting between these types. It explains implicit and explicit casting with examples, and emphasizes the importance of understanding data types to avoid errors. Additionally, the document introduces Python strings, their manipulation, and methods for string operations such as slicing, concatenation, and formatting.

Uploaded by

semilore
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

WEEK THREE

Topic: DATA TYPE

In Python, a data type is a category of data that defines the


type of value a variable can hold and the operations that can
be performed on it. Python has several built-in data types,
including:
1. Numeric Types
 Integers (int): whole numbers, e.g., 1, 2, 3, etc.
 Floating Point Numbers (float): decimal numbers, e.g.,
3.14, -0.5, etc.
 Complex Numbers (complex): numbers with real and
imaginary parts, e.g., 3 + 4j, etc.
2. Text Type
 Strings (str): sequences of characters, e.g., "hello",
'hello', etc. Strings can be enclosed in single quotes or
double quotes.
3. Sequence Types
 Lists (list): ordered collections of items, e.g., [1, 2, 3],
["a", "b", "c"], etc.
 Tuples (tuple): ordered, immutable collections of items,
e.g., (1, 2, 3), ("a", "b", "c"), etc.
4. Mapping Type
 Dictionaries (dict): unordered collections of key-value
pairs, e.g., {"name": "John", "age": 30}, etc.
5. Set Types
 Sets (set): unordered collections of unique items, e.g., {1,
2, 3}, {"a", "b", "c"}, etc.
 Frozensets (frozenset): immutable sets, e.g.,
frozenset({1, 2, 3}), etc.
6. Boolean Type
 Boolean (bool): true or false values, e.g., True, False, etc.
7. Binary Types
 Bytes (bytes): sequences of integers in the range 0 <= x
< 256, e.g., b'hello', etc.
 ByteArray (bytearray): mutable sequences of integers in
the range 0 <= x < 256, e.g., bytearray(b'hello'), etc.
8. None Type
 None (NoneType): a special type with a single value,
None, indicating the absence of a value.
Understanding data types is essential in Python, as it helps
you work with variables, perform operations, and avoid
errors.

CASTING
What is Casting?
Casting is a way to convert a value from one data type to
another. Think of it like changing the clothes of a value to
make it fit into a different category.
Types of Casting in Python
There are two types of casting in Python:
1. Implicit Casting (Automatic)
2. Explicit Casting (Manual)
Implicit Casting (Automatic)
Python automatically converts data types in certain situations.
Example 1:
num = 5 + 3.5
In this example, Python automatically converts the integer 5
to a float, so the result is a float: 8.5
Example 2:
name = "John" + " " + 25
Here, Python automatically converts the integer 25 to a string,
so the result is a string: "John 25"

Explicit Casting (Manual)


We use built-in functions to manually convert data types.
Here is the list of some built-in casting functions in Python:
1. int(): Converts a value to an integer.
2. float(): Converts a value to a floating-point number.
3. str(): Converts a value to a string.
4. bool(): Converts a value to a boolean (True or False).
5. complex(): Converts a value to a complex number.
6. list(): Converts a value to a list.
7. tuple(): Converts a value to a tuple.
8. set(): Converts a value to a set.
9. dict(): Converts a value to a dictionary.
10. bytes(): Converts a value to bytes.
These built-in casting functions help you convert values
between different data types in Python.

Example 1: Converting String to Integer


age = int("25")
Here, we use the int() function to convert the string "25" to an
integer 25
Example 2: Converting Float to Integer
num = int(3.14)
In this example, we use the int() function to convert the float
3.14 to an integer 3
Example 3: Converting Integer to String
name = str(25)
Here, we use the str() function to convert the integer 25 to a
string "25"
Example 4: Converting String to Float
height = float("3.14")
In this example, we use the float() function to convert the
string "3.14" to a float 3.14
Why is Casting Important?
Casting helps prevent errors when working with different data
types. It ensures that our code runs smoothly and produces the
expected results.

ASSESSMENT
Data Types:
1. What is the data type of the value 5? Justify your answer.
2. Write a Python program that takes user input for a
person's name and age, and stores the name as a string
and the age as an integer.
3. Identify the data type errors in the following code: x = 5
+ "hello" and y = True + 3.14. How would you fix them?
4. Research and present on a specific data type (e.g., lists,
dictionaries, sets) and its uses in real-world applications.
Casting:
1. Write Python code to cast the integer 25 to a float. What
is the result?
2. How would you convert the string "hello" to a list of
individual characters? Write Python code to demonstrate
this.
3. Identify the casting error in the following code: x =
int("hello"). How would you fix it?
4. Write a Python program that takes user input as a string
and uses casting to convert it to an integer, then performs
a calculation (e.g., adds 5 to the input).
Combining Data Types and Casting:
1. What would be the result of casting the string "123" to an
integer, then adding 5 to it? Write Python code to
demonstrate this.
2. Write a Python program that takes user input as a string,
converts it to a list of individual characters, then sorts the
list in alphabetical order.
3. Identify and fix the data type and casting errors in the
following code: x = "hello" + 5 and y = int("hello") +
3.14.
4. Design and write a Python program that uses data types
and casting to solve a real-world problem (e.g., building
a simple calculator or game).
WEEK FOUR

TOPIC: Python String

LESSON OBJECTIVES: By the end of the lesson, the


students should be able to:
o define python string
o work with print() function and assigning variable.
o apply slicing and Modification string
o carry out Concatenation and Format on string

ENTRY BEHAVIOUR: The students are familiar with


python datatype and variable which will aid proper
understanding in python string.

What is Python String: In python strings are used for


representing textual data. Though, a string is sequence of
character enclosed in either single quote (“) or double quote
(“”). The python language provides various built-in methods
and functionalities to work with strings efficiently.
Working with print() function and assigning variable .
A. You can display a string literal with the print()
function.

B. Assign String to a Variable.


Assigning a string to a variable is done with the variable name
followed by an equal sign and the string:

C. Multiline Strings.
You can assign a multiline string to a variable by using three
double quotes (""") or three single quotes (''')

OR

D. Strings are Arrays


Like many other popular programming languages, strings in
Python are arrays of bytes representing unicode characters.
However, Python does not have a character data type, a single
character is simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Your result will look like this below.

E. Looping Through a String


Since strings are arrays, we can loop through the characters in
a string, with a for loop.

RESULT BELOW.

F. String Length
To get the length of a string, use the len() function.
RESULT BELOW.

G. Check String.
To check if a certain phrase or character is present in a string,
we can use the keyword in.

RESULT BELOW.

H. Use it in an if statement:
RESULT BELOW.

I. Check if NOT
To check if a certain phrase or character is NOT present in a
string, we can use the keyword not in

RESULT BELOW.

Use it in an if statement:

RESULT BELOW.

2. Python - Slicing Strings


A. You can return a range of characters by using the slice
syntax.
Specify the start index and the end index, separated by a
colon, to return a part of the string.

RESULT BELOW.

Note: The first character has index 0.


B. Slice From the Start
By leaving out the start index, the range will start at the first
character:

RESULT BELOW.

C. Slice To the End


By leaving out the end index, the range will go to the end:
RESULT BELOW.

D. Negative Indexing
Use negative indexes to start the slice from the end of the
string:

RESULT BELOW.

3. Python - Modify Strings


Python has a set of built-in methods that you can use on
strings.
A. Upper Case
RESULT BELOW.

B. Lower Case

C. Remove Whitespace
Whitespace is the space before and/or after the actual text, and
very often you want to remove this space.

RESULT BELOW.

D. Replace String
RESULT BELOW

E. Split String
The split() method returns a list where the text between the
specified separator becomes the list items.

RESULT BELOW.

4. Python - String Concatenation


To concatenate, or combine, two strings you can use the +
operator.
RESULT BELOW.

RESULT BELOW

5. Python - Format - Strings


In Python Variables, we cannot combine strings and numbers
like this:
RESULT SHOWS ERROR IN CODE.

But we can combine strings and numbers by using the


format() method!
The format() method takes the passed arguments, formats
them, and places them in the string where the placeholders {}
are:

RESULT BELOW.

The format() method takes unlimited number of arguments,


and are placed into the respective placeholders:
RESULT BELOW

You can use index numbers {0} to be sure the arguments are
placed in the correct placeholders:

RESULT BELOW.

MULTIPLE CHOICE QUESTION.


1. Which of the following are string methods?
A. split()
B. lower()
C. append()
D. startswith()
E. sort()
2. Which of the following code corresponds to the amount of
characters in the following string variable?
string = "I love coding!"
A. count(string)
B. len(string)
C. int(string)
D. length(string)
3. What does the following code output?
def abbrev(first_name, last_name):
print(first_name[0:1] + ". " + last_name.lower())
abbrev("Joanne", "Weathers")
A. J. Weathers
B. Jo. Weathers
C. oa. Weathers
D. J. weathers
E. j. weathers
4. What does the following Python code snippet do?
string = "Hello, World!"
print([Link]())
a) Prints “Hello, World!” in lowercase
b) Converts “Hello, World!” to uppercase and prints it
c) Reverses the string “Hello, World!”
d) Removes all whitespace characters from the string “Hello,
World!”
Answer: b
Expl
5. How can you concatenate two strings in Python?
a) Using the concat() method
b) Using the join() method
c) Using the & operator
d) Using the + operator
Answer: d
Expla
6. What is the output of the following Python code snippet?
string = "Hello, World!"
print(string[3:7])
a) “Hello”
b) “lo, “
c) “lo, W”
d) “lo, World”
Answer: b
Explanation: Slicing is used to extract a substring from a
string. The indices 3:7 repre
7. Which method is used to split a string into a list of
substrings based on a delimiter in Python?
a) split()
b) substring()
c) separate()
d) divide()
Answer: a
Explanation: The split() method is used to split a string into a
list of substrings based
8. What does the replace() method do in Python string
manipulation?
a) Deletes all occurrences of a substring from the string
b) Replaces the first occurrence of a substring with another
substring
c) Replaces all occurrences of a substring with another
substring
d) Inserts a substring into the string at a specified position
Answer: c
Expl
9. What is the output of the following Python code snippet?
string = "Hello, World!"
print([Link](","))
a) [“Hello”, “World!”]
b) [“Hello,”, “World!”]
c) [“Hello”]
d) [“World!”]
Answer: a
Explanation: The split() method splits the string into a list of
substrings based on the sp
10. Which method is used to convert the first character of a
string to uppercase in Python?
a) upper()
b) capitalize()
c) title()
d) first_upper()
Answer: b
ESSAY
1. Write a Python program to calculate the length of a string.
2. Write a Python program to count the number of characters
(character frequency) in a string.
Sample String : [Link]'
Expected Result : {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}

You might also like