Python Day- 3
(RECAP OF PREVIOUS DAY)
Expressions in Python, Strings: Basics, indexing, slicing, and formatting,
Basic string operations and methods. Short discussion on List, tuple, set and dictionary,
Problems on above concepts.
Expressions in Python
Definition:
An expression is a combination of values, variables, operators, and function calls that the
Python interpreter can evaluate to produce a result.
Types of Expressions:
1. Constant Expressions: Contain only literal values (e.g., 5 + 10).
2. Arithmetic Expressions: Use arithmetic operators to compute numerical values (e.g., a
+ b, x ** y).
3. Logical Expressions: Use logical operators (and, or, not) to evaluate Boolean
conditions.
4. Relational Expressions: Compare values using comparison operators (e.g., a > b).
5. Bitwise Expressions: Perform bitwise operations (e.g., x & y).
6. String Expressions: Combine string literals or variables using operators (e.g., "Hello"
+ " World").
Examples of Expressions:
# Constant Expression
result = 10 + 20
print(result) # Output: 30
# Arithmetic Expression
x = 15
y=5
result = (x + y) * 2
print(result) # Output: 40
# Logical Expression
is_valid = True
is_complete = False
print(is_valid and not is_complete) # Output: True
# Relational Expression
a = 10
b = 20
print(a < b) # Output: True
# Bitwise Expression
x = 5 # Binary: 0101
y = 3 # Binary: 0011
print(x & y) # Output: 1 (Binary: 0001)
# String Expression
greeting = "Hello" + " World"
print(greeting) # Output: Hello World
Strings in Python
● Strings in Python are sequences of characters enclosed in single ('), double ("), or triple
quotes (''' or """).
● Strings are immutable, meaning they cannot be changed after creation.
Examples of Strings:
# Single-quoted string
greeting = 'Hello'
# Double-quoted string
name = "Alice"
# Triple-quoted string (useful for multi-line strings)
multiline_text = '''This is
a multi-line
string.'''
print(greeting) # Output: Hello
print(name) # Output: Alice
print(multiline_text) # Output: This is\na multi-line\nstring.
String Indexing:
● Strings are indexed from 0 to n-1 (forward indexing) and -1 to -n (reverse indexing).
Examples of String Indexing:
text = "Python"
# Forward indexing
print(text[0]) # Output: P (1st character)
print(text[3]) # Output: h (4th character)
# Reverse indexing
print(text[-1]) # Output: n (last character)
print(text[-3]) # Output: t (3rd last character)
String Slicing:
● Extracting a portion of the string using the slicing operator :.
● Syntax: string[start:end:step]
○ start: Starting index (inclusive, default is 0).
○ end: Ending index (exclusive, default is length of string).
○ step: Step size (default is 1).
Examples of String Slicing:
text = "Python Programming"
# Basic slicing
print(text[0:6]) # Output: Python (characters from index 0 to 5)
print(text[:6]) # Output: Python (same as above)
print(text[7:]) # Output: Programming (from index 7 to end)
# Using step
print(text[0 : 12 : 2]) # Output: Pto rg (every 2nd character from index 0 to 11)
# Reverse slicing
print(text[ : : -1]) # Output: gnimmargorP nohtyP (reverses the string)
String Formatting:
● Formatting allows us to insert variables or values into strings dynamically.
Types of String Formatting:
1. Using format() method:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Alice and I am 25 years old.
2. Using f-strings (Python 3.6+):
name = "Bob"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Bob and I am 30 years old.
3. Using % operator (old method):
name = "Eve"
age = 22
print("My name is %s and I am %d years old." % (name, age))
# Output: My name is Eve and I am 22 years old.
3. Basic String Operations and Methods
Basic Operations:
Concatenation: Joining two strings using the + operator.
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Output: Hello World
1. Repetition: Repeating a string using the * operator.
text = "Python "
print(text * 3) # Output: Python Python Python
2. Membership: Checking for substring presence using in and not in.
text = "Python Programming"
print("Python" in text) # Output: True
print("Java" not in text) # Output: True
Common String Methods:
1. lower(): Converts the string to lowercase.
2. upper(): Converts the string to uppercase.
3. strip(): Removes leading and trailing spaces.
4. split(): Splits the string into a list of words.
5. join(): Joins elements of a list into a string.
6. replace(): Replaces a substring with another substring.
7. find(): Finds the first occurrence of a substring.
8. startswith() and endswith(): Check if the string starts or ends with a specific
substring.
Examples:
text = " Hello Python "
print(text.lower()) # Output: " hello python "
print(text.upper()) # Output: " HELLO PYTHON "
print(text.strip()) # Output: "Hello Python"
words = text.split()
print(words) # Output: ['Hello', 'Python']
joined = "-".join(words)
print(joined) # Output: Hello-Python
print(text.replace("Python", "World")) # Output: " Hello World "
print(text.find("Python")) # Output: 8 (starting index of 'Python')
print(text.startswith(" Hello")) # Output: True
print(text.endswith("Python ")) # Output: True
[WE WILL BE DISCUSSING LIST, TUPLE, SET AND DICTIONARY IN
SHORT HERE, DETAIL DISCUSSION ON THESE TOPICS WILL BE
DONE LATER ON DAY 9 AND DAY 10.]
Introduction to List
Definition
● A list is an ordered, mutable (modifiable) collection of elements.
● Lists can contain elements of different data types (integers, strings, floats, other lists,
etc.).
● Lists are defined using square brackets [ ].
Key Properties
● Ordered: The elements have a specific order.
● Mutable: Elements can be added, removed, or modified.
● Allows duplicates: Multiple occurrences of the same value are allowed.
Syntax
# Creating a list
my_list = [1, 2, 3, "hello", 4.5]
Introduction to Tuple
Definition
● A tuple is an ordered, immutable (non-modifiable) collection of elements.
● Tuples can contain elements of different data types.
● Tuples are defined using parentheses ( ).
Key Properties
● Ordered: The elements have a specific order.
● Immutable: Once defined, elements cannot be changed.
● Allows duplicates: Multiple occurrences of the same value are allowed.
# Creating a tuple
my_tuple = (1, 2, 3, "hello", 4.5)
Introduction to Set
Definition
● A set is an unordered, mutable collection of unique elements.
● Sets do not allow duplicate values.
● Sets are defined using curly braces { } or the set() function.
Key Properties
● Unordered: No guaranteed order of elements.
● Mutable: Elements can be added or removed.
● Unique: Duplicate elements are not allowed.
Syntax
# Creating a set
my_set = {1, 2, 3, 4}
Introduction to Dictionary
Definition
● A dictionary is an unordered, mutable collection of key-value pairs.
● Keys are unique, and values can be of any data type.
● Dictionaries are defined using curly braces { } with key-value pairs separated by colons.
Key Properties
● Unordered: No guaranteed order of key-value pairs.
● Mutable: Keys and values can be added, removed, or modified.
● Unique Keys: Keys must be unique, but values can be duplicated.
Syntax
# Creating a dictionary
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
Practice Problems
1. Convert a string to uppercase and lowercase
text = "Python Programming"
print(text.upper()) # Output: PYTHON PROGRAMMING
print(text.lower()) # Output: python programming
2. Find the number of occurrences of a substring
text = "banana"
print(text.count("a")) # Output: 3
3. Check if a string starts and ends with a specific substring
text = "Hello, Python!"
print(text.startswith("Hello")) # Output: True
print(text.endswith("Python!")) # Output: True
4. Extracting initials from a full name.
def get_initials(full_name):
names = full_name.split()
initials = "".join([name[0].upper() for name in names])
return initials
name = "John Doe"
print(get_initials(name)) # Output: JD
5. Count vowels in a string.
def count_vowels(text):
vowels = "aeiouAEIOU"
return sum(1 for char in text if char in vowels)
sentence = "Python is fun"
print(count_vowels(sentence)) # Output: 3
6. Reverse words in a sentence.
def reverse_words(sentence):
words = sentence.split()
reversed_sentence = " ".join(reversed(words))
return reversed_sentence
text = "Python is fun"
print(reverse_words(text)) # Output: "fun is Python"
7. Replace spaces with hyphens in a string.
text = "Python is amazing"
print(text.replace(" ", "-")) # Output: "Python-is-amazing"
8. Check if a string is a palindrome.
def is_palindrome(text):
text = text.replace(" ", "").lower()
return text == text[::-1]
word = "madam"
print(is_palindrome(word)) # Output: True
List of programs to practice (Home work)
9. Write a program to convert the string from upper case to lower case.
10. Write a program to convert the string from lower case to upper case.
11. Write a program to delete the all consonants from given string.
12. Write a program to count the different types of characters in given string.
13. Write a program to count number of words in a multi word string.
14. Write a program to sort the characters of a string.
15. Write a program for concatenation two strings.
16. Write a program to find the length of a string.
17. Write a program to find the length of a string without using string function.
18. Write a program which prints initial of any name (print RAM for RAM KUMAR).
19. Write a program to check whether a string is palindrome or not.
20. Write a program to sort given names in Lexicographical sorting (Dictionary order).