Assignment on Methods and Built-in functions
1. Return the second-to-last word in a string. ("Welcome to the Python world")
2. Extract the protocol (http, https, ftp) from a given URL.
("[Link]
3. Swap the first and last words of a string. ("From all of us at OpenAI")
4. Capitalize the first letter of a string, and make sure the rest is in lowercase.
("pYTHON")
5. Extract the domain extension (like "com", "org") from a website URL.
("[Link]
6. Given the string "hello_world_python", split it at underscores and then join it using
hyphens (-).
7. Check if the given string "apple123" starts with a non-digit character.
8. Replace every "is" in the string with "was", but only for the first two occurrences.
("This is a story. This is not a drill.")
9. Find out if a string is entirely made up of digits. ("12345a")
10. Convert the first character of each word in a string to uppercase and the rest to
lowercase. ("ThIS iS a MIXed CaSE STring.")
1. Tricky Exponents:
Given the expression 3 ** 2 ** 2, without computing, can you guess what the result is?
Now, code it and check!
2. Mysterious Parentheses:
If a = 5, b = 6, and c = 2, predict the result of (a + b * c) ** c. After predicting, write
the code and see if you were correct.
3. Order of Operations:
Evaluate the following expressions and explain the step-by-step process of how Python
arrives at each result:
● 3+4∗6/2−(9+2)
● 3∗3//2∗4+2
● 7
4. String Operators Quest:
Can you figure out the output of the following expressions without executing them?
● "Python" * 3
● "Python" + "Rocks" * 2
● "Python"[1:3] * 2
5. Complex Operations Challenge:
If x = 4, y = 3, and z = 2, then find the value of the following expression and explain the
steps:
6. String Membership:
Given the string "ProgrammingInPythonIsFun", determine whether the substring "Python"
is a member. Also, check if "Java" is not a member.
7. Combined Operator Mystery:
If a = 2, b = 3, and c = 1, what is the output of:
● a + b * c == a + (b * c)
● a ** b ** c
● a + b * c / a
8. The Big Challenge:
Create an expression using at least five different operators (like +, -, *, /, **, %, //, and, or,
not) that results in the number 100.
Built-in Functions
● Just like magic spells in a spellbook, Python has pre-made tools or "built-in
functions" ready for us to use anytime.
● You don't need to do anything special to use them. They're always there!
● Examples:
● print(): Displays the argument value on the console.
● len(): Returns the length of an object.
● type(): Returns the type of an object.
● int(), float(), str(): Type conversion functions.
● input(): Reads input from the console.
● list(), dict(): Creates a list or dictionary.
● min(), max(): Returns the smallest or largest item.
● sum(): Returns the sum of a collection.
● Here's a treasure map ([Link] ) to
see all of these magic spells and what they do
Keywords
● Python has special words, like magic words, that mean specific things.
● We should not use these words for naming our own things, like pets or treasure
chests (or in coding terms, variables or functions).
● How many are there? 35!
● Want to see them? Type help('keywords') in Python and it'll show you the list!
Underscores in Numbers
● Long numbers can look confusing. So, just like we use commas to group
numbers, in Python, we use underscores.
● Example: count = 10_000_000_000 is the same as 10,000,000,000.
● And guess what? It works for decimals too! count = 10_000_0.00_000.
Python Booleans
● Sometimes we need to check if something is true or false.
● The bool() magic spell can tell us! Like a truth-telling crystal ball.
● print(bool("Hello")) tells us True, because "Hello" is something.
● print(bool("")) tells us False, because it's empty, like an empty
treasure chest.
● Almost any value is evaluated to True if it has some sort of content.
● Any string is True, except empty strings.
● Any number is True, except 0.
● Any list, tuple, set, and dictionary are True, except empty ones.
● There are not many values that evaluate to False, except empty values, such as (), [],
{}, "", the number 0, and the value None(None means nothing, nil).
● Value False evaluates to False.
Built-in Functions vs. String Methods
● Built-in Functions: Like general magic spells. Examples: len(), print().
● How to use? Just say the spell's name! Like: len("Hello") → 5.
● String Methods: Special spells just for text (strings). Examples: .lower(),
.upper().
● How to use? Attach them to the text! Like: "Hello".lower() → "hello".
Python Strings and Their Magic!
● Escape Sequences: Special codes to make text do fun things!
● print('This is a new\nLine!') → This breaks the text into two lines!
● print('This is a\tTab!') → This adds a big space in the text.
● print('Look, a backslash: \\') → This shows a backslash in the text.
String Methods
1. .capitalize()
● Description: Capitalizes the first letter of a string.
2. .islower()
● Description: Checks if all characters in the string are lowercase.
3. .isupper()
● Description: Checks if all characters in the string are uppercase
4. .upper()
● Description: Converts all characters in the string to uppercase.
5. .lower()
● Description: Converts all characters in the string to lowercase.
6. .title()
● Description: Capitalizes the first letter of each word in a string.
7. .count(substring, start, end)
● Description: Returns occurrences of a substring in the string between the start
and end positions.
8. .startswith(substring)
● Description: Checks if a string starts with the specified substring.
9. .endswith(substring)
● Description: Checks if a string ends with the specified substring.
10. .swapcase()
● Description: Switches the case for all characters in the string.
11. .replace(old, new, count)
● Description: Replaces all (or up to count) occurrences of a substring.
12. .split(separator, maxsplit)
● Description: Splits a string into a list of substrings based on a separator.
13. .isidentifier()
● Description: Checks if a string is a valid identifier (e.g., for variable names).
14. .isdecimal()
● Description: Checks if all characters in the string are decimals (0-9).
15. .isalpha()
● Description: Checks if all characters are alphabets (A-Z, a-z).
16. .isalnum()
● Description: Checks if the string consists of alphanumeric characters.
17. .find(substring)
● Description: Returns the index of the first occurrence of a substring or -1 if not
found.
18. .rfind(substring)
● Description: Returns the index of the last occurrence of a substring or -1 if not
found.
19. .join(iterable)
● Description: Joins an iterable (e.g., list) of strings using the specified delimiter.
Chapter: Variables
The Tale of Variables
In our previous quest, we learned about Numbers and Strings. Now, it's time to discover
🎁
the secret language of Variables and Data Types. In Python, variables are like magic
boxes .
They can hold strings, numbers, or even a spell (or what we humans call "functions")!
Imagine you have a treasure chest, and instead of gold, it is filled with phrases or
numbers you need to use over and over again. Instead of carrying this bulky chest
around, you could just use a magical word that could summon whatever is inside it.
That's precisely what variables do!
Creating a Variable: A set of rules
1. When naming your variable, it must start with a letter or an underscore, but never
with a number.
2. Variable names can only contain alpha-numeric characters and underscores (A-z,
0-9, and _). Beware of special characters; they will anger the Python gods!
3. Variable names are case-sensitive, just like passwords. (Remember, "password",
"Password", and "PASSWORD" are different!)
4. Choose names that are easy to remember and clearly describe the treasure they
hold. It's like naming a pet; you want it to be fun, unique, and meaningful.
Valid Variable Names:
firstname,
age,
num1,
first_name,
last_name,
year2021,
year_2021,
num2
Invalid Variables Names:
first-name,
first@name,
first$name,
num-1,
1num,
#sum,
*first
Python variable naming style
1. Python developers use snake case(snake_case) variable naming convention.
2. We use underscore character after each word for a variable containing more than
one word (eg. first_name, last_name).
Declaring a Variable: The Magic Spell ✨
In Python, you cast a spell on a variable by assigning a value to it. You can think of the
equal sign (=) as a magic wand that puts whatever value you want into the variable. The
"spell" to store "Anand" into a variable named "first_name" would look like this:
first_name = "Anand"
Now, every time you call upon first_name, Python will replace it with "Anand". So, the
next time you want to print your first name, you can just say:
print(first_name)
1. When we assign a certain data to a variable, it is called variable declaration. For
instance in the example above, my first name is assigned to a variable
first_name.
2. The equal sign is an assignment operator. Assigning means storing data in the
variable.
3. The equal sign in Python is not equality as in Mathematics.
4. Python variables can be a single character, a word or multiple words.
Remember, the kind of value you put in a variable determines its type. So, if you put a
string value into a variable, it becomes a string variable. If you put a number value into a
variable, it becomes a number variable. Pretty neat, right?
Examples: fruit = "apple", age = 12
Here, fruit is a string variable and age is a number variable.
The Power of Multiple Declarations:
You can also put different treasures into multiple boxes at the same time!
first_name, last_name, country, age, is_married = 'Siddhar', 'Sinha',
'India',39,True
Now print these variables and check values they have stored.
print(first_name)
print(age)
print('First name:', first_name)
print('Age: ', age)
print('Married: ', is_married)
#Note!! Use False not FALSE. Same with True, Don't use TRUE. We will learn about these data
types later.
Getting user input using the input() spell
You can even ask a fellow wizard (or user) for a value to put in your variable!
Using input() functions, we get an input from the user and store it in a variable.
first_name = input('What is your name, great wizard?: ')
age = input('How many seasons have you seen?: ')
Variable Operations:
Just like numbers, variables can also be added, subtracted, multiplied... But beware! You
can only do with variables what you can do with their values. If a variable holds a string,
you cannot subtract it. If a variable holds a number, you cannot multiply it by a word.
Only the operators corresponding to a variable's type are allowed for that variable.A
string variable only allows using the + and * operators, while a number variable can
use +, -, *, / etc.
Incorrect Operation:
fruit = "apple" print(fruit-1) #This will lead to an error!
Correct Operation:
age = 25
age = age + 5
print(age) #This will print 30.
Beware of the Unassigned Variable!
Never use a variable before you have assigned a value to it. That would be like trying to
open an empty treasure chest!
Below code will fail because the variable called "name" is not defined yet. So Python
does not know what value to put in for the variable called name.
print(“Hellp” + name) #This will lead to an error.
Borrowing Values:
Sometimes, a variable might want to borrow the value of another variable.
name = "Anand"
greeting = "Hello, " + name
print(greeting)
# This will print "Hello, Anand"
Assignment
Homework:
1. Practice the art of declaring multiple variables in 1 line.
2. Declare a year variable and assign a value to it.
3. Declare an age variable and assign a value to it.
4. Declare a is_married variable and assign a value to it.
5. Swap the values of 2 variables, like a magic trick!
6. Classroom Seats: A classroom has 5 rows of seats. Each row can seat 8
students. Write a program that asks the user how many students are in the class,
then calculates and prints the number of empty seats.
7. Temperature Conversion: Write a program that asks the user to input a
temperature in Fahrenheit and convert it to Celsius. The formula to convert
Fahrenheit to Celsius is (Fahrenheit - 32) * 5/9
8. Favorite Color: Ask the user to input their favorite color. Then print a sentence
saying "Your favorite color is _____." Replace the blank with the color the user
inputted.
9. Declare 5 as num_one and 4 as num_two. Perform these spells:
● Add num_one and num_two and assign the value to a variable total.
● Subtract num_two from num_one and assign the value to a variable diff.
● Multiply num_two and num_one and assign the value to a variable product.
● Divide num_one by num_two and assign the value to a variable division.
● Use modulus division to find num_two divided by num_one and assign the value to
a variable remainder.
Some Multiple choice questions:
1. What symbol is used for variable assignment in Python?
a) -
b) *
c) =
d) +
2. Which of the following is an invalid Python variable name?
a) first_name
b) _last_name
c) 1st_name
d) Lastname
3. Which of the following commands will print the variable name that contains the
string "John"?
a) print(name("John"))
b) [Link]
c) print("name")
d) print(name)
4. Is myVar the same as myvar in Python?
a) Yes
b) No
5. What is the output of the following code: x = 5; x = x + 5; print(x)
a) 10
b) 5
c) 25
d) Error
6. How can we assign the value 10 to a variable x in Python?
a) x == 10
b) 10 -> x
c) x <- 10
d) x = 10
7. What will be the output of print(num) after executing the following lines of code:
num = 10
num = 'ten'
a) 10
b) 'ten'
c) Error
d) None of the above
8. What is the output of the following code: a, b, c = 1, 2, 3; print(b)
a) 1
b) 2
c) 3
d) Error
9. Which function is used to get the user's input in Python?
a) user_input()
b) get_input()
c) input()
d) read_input()
10. Can we assign the value of a variable using the value of another variable in
Python?
a) Yes
b) No
11. Consider the following Python code:
var1 = 2
var2 = var1
var1 = 4
print(var2)
What will be printed?
a) 2
b) 4
c) var1
d) var2
Data Types
What Are Data Types?
Imagine you have different containers in your room. Some are for toys, some for clothes, some
for books, and so on.
In Python, data types are like those containers. They tell Python what kind of stuff (data) you
want to store and how to handle it.
Data types define the type of value a variable can hold.
Let's look at some of these "containers" (Data types)!
1. Numbers:
In the Number container (Number data type), we store numbers like your age, the number of
pets you have, or how many candies are left in the jar.
● Integers (Whole Numbers): Like 5, 10, or -3. They have no decimal points!
● Floats (Decimal Numbers): Like 3.14, 2.5, or 0.99. They have decimal points!
age = 12
temperature = -5
print(age, temperature) # Output: 12 -5
2. Strings
In the string container (String data type), we store strings like your name, your favorite color, or
a whole story can be a string.
● "I love Python!"
● 'Alice'
● "Blue"
greeting = 'Hello, World!'
print(greeting) # Output: Hello, World!
3. Booleans
Imagine you have a remote-controlled toy car, and you want to set up a system to control when
it can move. You might have a rule that says, "If the car's battery is full, then it can move." So,
you would need a way to check if the battery is full or not. That's where the Boolean container
comes in!
The Boolean container (Data type) can hold one of two values: True (like the battery is full) or
False (like the battery is empty). By checking this value, your program can decide what to do
next, like whether the toy car should move or not.
is_battery_full = True
has_umbrella = False
print(is_battery_full, has_umbrella) # Output: True False
4. Lists
Imagine you have a backpack, and you want to put various things inside: pencils, notebooks, an
apple for lunch, etc. Now, instead of holding each item separately, you can put them all in the
backpack. That way, you can carry them all together and find them easily when you need them.
A List in Python is like this backpack. You can put different kinds of things (numbers, words,
other lists) inside it, and then you can use them all at once. It makes it easier to keep track of a
bunch of things in your program without having to remember them all separately.
Technical Explanation:
Lists are ordered collections of items. They can contain mixed types of data
Storing Multiple Values: A List can hold many values together in one variable. This can
simplify your code, as you don't have to create a separate variable for each value. For example:
Numbers = [1, 2, 3] #A list of numbers.
Pets = ['Cat', 'Dog', 'Fish']: #A list of strings
Ordered Collection: Lists keep the order of the items, so you can always find things in the
same place where you put them. This helps when the order of elements matters in your
program.
Flexibility: Lists can hold different types of data together, like numbers, strings, or even other
lists. For example:
Combine = ['Cat', 'Dog', 1, -32]: #A list combined of strings and numbers
Easy to Modify: You can add, remove, or change items in a List easily.
* To create a list of a few items, just put the items inside square brackets and separate them
with commas.
5. Tuples
Imagine you have a photo album with some special pictures that you don't want to change, like
your birthday or a family vacation. You want to keep those pictures in the same order, and you
don't want anyone to add or remove any pictures.
A tuple in Python is like this special photo album. Once you put things inside it, you can't change
them. They'll stay in the same order, and no one can add or remove anything. This can be
useful when you want to make sure things stay exactly the way you put them.
* Tuple is like a list, but you can’t change the order or remove any element. To create a tuple
just put the items inside square brackets and separate them with commas.
Fruits =('Apple', 'Banana', 'Cherry')
6. Sets
Imagine you have a big bucket of marbles, and you want to make sure that there's only one
marble of each color. If you find another marble of the same color, you don't put it in the bucket.
You also don't care about the order of the marbles in the bucket; you just want one of each
color.
A set in Python is like this bucket of marbles. It holds different things, like numbers or words, but
it only keeps one of each. It doesn't care about the order, just that everything inside is unique.
● {2, 3, 4, 5}: If you try to add another 3, it will still be {2, 3, 4, 5}.
You can create a set by putting values inside curly braces {} and separating them with commas:
set_A = {2, 3, 4, 5}
set_B = {‘a’, ‘c’, ‘d’, ‘e’}
7. Dictionaries
Imagine you have a big drawer with many compartments. In each compartment, you want to
store a specific thing, like your favorite toys, school supplies, or stickers. To find them quickly,
you put a label on each compartment, like "Toys," "Pencils," or "Stickers."
A dictionary in Python is like this labeled drawer. It lets you store things (values) in
compartments (keys) with labels, so you can find them quickly. You just need to look at the label
(key), and you can get the thing (value) you stored there.
# Defining a dictionary
my_dictionary = {
'name': 'Alice',
'age': 12,
'city': 'Wonderland',
'Subjects': [‘Maths’, ‘English’, ‘Science’]}
Assignments:
1) What is the data type of the value 5 in Python?
A) Float
B) String
C) Integer
D) List
2) Which data type would you use to store the name of your pet?
A) Integer
B) List
C) Float
D) String
3) If you want to store multiple values in a specific order and change them later, what should
you use?
A) Tuple
B) Set
C) String
D) List
4) What is a unique feature of a set in Python?
A) It can have duplicate values.
B) It keeps the values in order.
C) It only allows numbers.
D) It cannot have duplicate values.
5) What will the following code create?
my_data = (1, 2, 3)
A) A set with three numbers
B) A list with three numbers
C) A dictionary with three numbers
D) A tuple with three numbers
6) Which data type is immutable, meaning it cannot be changed after it's created?
A) List
B) Set
C) Dictionary
D) Tuple
7) What will the following code create?
my_fruits = ['apple', 'banana', 'cherry']
A) A string with three words
B) A dictionary with three keys
C) A list with three strings
D) A tuple with three strings
8) What is the data type of the value 3.14 in Python?
A) Integer
B) String
C) Float
D) Tuple
9) Which of the following can be used to store multiple unique values without caring about their
order?
A) List
B) String
C) Tuple
D) Set
10) If you want to pair names with ages, what data type would be best?
A) List
B) Set
C) Dictionary
D) Float
11) What will the following code create? name = "Alice"
A) An integer
B) A tuple
C) A string
D) A set
12) Which of the following is mutable, meaning you can change its content after creation?
A) String
B) Tuple
C) Float
D) List
13) What will the following code create?
numbers = {1, 2, 2, 3}
A) A list with four numbers
B) A tuple with four numbers
C) A set with three numbers
D) A dictionary with four keys
14) Which of the following code snippets will create a dictionary?
A) data = [1, 2, 3]
B) data = {1, 2, 3}
C) data = (1, 2, 3)
D) data = {'a': 1, 'b': 2, 'c': 3}
15) Which data type would you use to store the coordinates of a point ‘example: (x,y)’?
A) String
B) Dictionary
C) Tuple
D) Integer
16) Create a list named foods which stores three of your favorite foods, then print the entire list.
17) Create a tuple named superheroes which stores three of your favorite super heroes, then
print the entire tuple.
Day 2: Journey into the Land of Python Strings
Today we're embarking on a fantastic journey to discover the magic of 'Strings' in Python.
What's a string you ask? Well, a string is like a chain of characters held together. Imagine a pearl
necklace, where each pearl represents a character, and the whole necklace is our string.
You can enclose your string of characters with either single ('), double ("), or even triple (''')
quotes. Like wrapping a gift in different types of wrappers. So you can define a string as follows:
print("Hello there!")
print('Hello again!')
print('''And hello some more!''')
Sometimes, we want to express ourselves in more than just one line. And for that, we have
multiline strings. These are created by using either triple single (''') or triple double quotes ("""):
epic_intro = '''A long time ago in a galaxy far, far away...
It is a period of civil war.
Rebel spaceships have won their first victory against the evil Galactic Empire.'''
print(epic_intro)
● For multiline string use only either triple single quote or triple double quote
If using single triple quote or double triple quote without storing in variable it will be
treated as multiline comment
In the world of strings, you have endless possibilities. Your string can be just one character, one
word, one sentence , a number, a mathematical expression , or an entire book!
# Single character
secret_code = "Z"
print(secret_code)
# A word
magic_word = "Abracadabra"
print(magic_word)
# A sentence
excitement = "Woo-hoo! I just coded my first string."
print(excitement)
# An entire story!
fairytale = "Once upon a time, in a faraway land, there was a brave knight and a
beautiful princess."
print(fairytale)
# A paragraph in multiple lines!
fairytale = "Once upon a time,\nin a faraway land, \nthere was a brave knight and
a beautiful princess."
print(fairytale)
# Mathematical expression
Num = "123456+12"
print(Num)
But wait! There's a rule here. You cannot mix single and double quotes within the same string.
So print("Hey, How are you') is a no-go.
But what if we want to use both in a string? Worry not, Python got us covered. Just use double
quotes around the string if you want to use a single quote within it:
print("Hello, what's up?")
Now, let's look at some magic spells, umm... I mean string operators:
String Concatenation: Like adding Lego blocks together. We either use the plus (+)
operator or the comma (,).
print("Hello " + "world") # This will print: Hello world
print("Learning", "Python", "is", "fun!") # This will print: Learning Python is
fun!
String Repetition: Imagine if you had a magic wand that could replicate your favorite
candy. In Python, we do it with the asterisk (*) operator.
print("Python " * 3) # This will print: Python Python Python
Finding Length of String: Want to know how many characters are in your string? The
len() function is here to help!
print(len("Python")) # This will print: 6
Here len is a function to check the number of characters in the string, similar to length there are
many other string functions. Which we will discuss later.
Indexing in Python
Strings in Python also come with secret maps and hidden treasures. By using indexing and
slicing, we can access any part of the string we want:
Imagine you're going on a treasure hunt and your map has different steps marked as 0, 1, 2, and
so on. Each step brings you closer to the treasure. That's what indexing is in Python! It helps you
find the treasure in your list of values or a string of characters.
Think of a string as a chain of treasure boxes, each having a unique number (the index), and a
treasure inside (the character). This is what Python does when you create a string.
Let's dive into our indexing adventure with Python!
1. Understanding Indexing
Let's take a word like "PYTHON". Each letter in this word is like a treasure box, and it has an
index, starting from 0. Yes, Python starts counting from zero, not one!
word = "PYTHON"
# P is at index 0
print(word[0]) # Output: P
# Y is at index 1
print(word[1]) # Output: Y
# T is at index 2
print(word[2]) # Output: T
Now, what if you want to start from the end? Python has a cool trick for this too. It uses
negative indexing!
# N is at index -1
print(word[-1]) # Output: N
# O is at index -2
print(word[-2]) # Output: O
# H is at index -3
print(word[-3]) # Output: H
# and so on...
# String indexing
magic_phrase = "I love coding"
print(magic_phrase[0]) # This will print: I
2. Indexing Out of Range
What if you try to look for a treasure box that doesn't exist? Like, if you try to find the
treasure at index 10 in "PYTHON"?
print(word[10])
Python will say, "IndexError: string index out of range". So always remember, the index
has to be within the range of the length of your string!
String Slicing in Python
After the thrill of the treasure hunt with indexing, we're heading on a new journey to the
fascinating "Slice Island".
You've seen how we can pick up individual treasure boxes (characters) using their map
numbers (indexes). Now, imagine you can pick up a whole range of treasure boxes at
once. That's what string slicing in Python allows you to do!
Understanding Slicing
Let's say you have a string "PYTHONER". The string slicing format is like this:
string[start:stop]. Python will start at the start index, and go up to but not include
the stop index.
Here's how we can slice to get the word "PYTH":
word = "PYTHONER"
# Take the slice from index 0 up to but not including index 4
print(word[0:4]) # Output: PYTH
We will learn more about slicing in details in the next class
Now, I believe you're ready to take on some challenges. So, here are some tasks for you to
tackle:
Task 1: Craft a string that displays your name, your country, your grade, and your favorite
subject.
Task 2: Write your full name using string concatenation operator (+).
Task 3: Weave the strings 'I', 'love', 'Python', 'Programming' into a single string 'I love
Python Programming' using the comma (,).
Task 4: Use the magic len() function to find out the length of your full name.
Task 5: What is the character hiding at index 2 in the string "Coding For Kids"?
Task 6: Discover the last index of the string "Coding For Kids".
Task 7: Use your new slicing skills to cut out the first word of "Coding For Kids".
Task 8: Can you extract a substring from "Coding For Kids" using index 4 and 7?
Task 9: Challenge time! Cut out all the characters from the string "Coding is Fun" starting
from index 4.
Task 10: Now, try to cut out all the characters from the string "Coding is Fun", but this
time, stop at index 5.
That's it for today's journey. Grab your keyboard and start coding away!
The universe of Python strings awaits you. Happy coding!