0% found this document useful (0 votes)
9 views16 pages

String Concepts in Python: Indexing

The document provides an overview of string concepts in Python, including string creation, indexing, slicing, and common string methods. It also covers conditional statements such as if, else, and elif, with practice programs for each concept. The document serves as a guide for beginners to understand and implement string manipulation and conditional logic in Python.

Uploaded by

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

String Concepts in Python: Indexing

The document provides an overview of string concepts in Python, including string creation, indexing, slicing, and common string methods. It also covers conditional statements such as if, else, and elif, with practice programs for each concept. The document serves as a guide for beginners to understand and implement string manipulation and conditional logic in Python.

Uploaded by

misbahjfr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

STRING CONCEPTS IN PYTHON

→ String is a data type in Python.


→ String is a sequence of characters enclosed in quotes.
→ We can primarily write strings in the following ways

1. Single quote string → a = ‘Saheer’

2. Double quote → b = “Saheer”

3. Triple quote → c = ‘’’ Saheer ‘’’

Indexing
Indexing in Python allows you to access individual elements of a sequence (like
strings, lists, or tuples) using their position or "index." Each item in a sequence
has an index, starting with 0 for the first element, 1 for the second, and so on.
Negative indexing is also allowed, where -1 refers to the last element, -2 to the
second last, and so on.
Example of Indexing with a String:

name = "Python"
# Positive Indexing
print(name[0]) # Output: 'P'
print(name[3]) # Output: 'h'

# Negative Indexing
print(name[-1]) # Output: 'n' (last character)
print(name[-3]) # Output: 't'

In this example:

name[0] gives us the first character, "P" .

name[3] gives the fourth character, "h" .

name[-1] fetches the last character, "n" .

name[-3] fetches "t" , the third character from the end.

Untitled 1
Indexing is a powerful way to access and work with specific parts of
sequences in Python.

1. Creating Strings
Single-line String:

greeting = "Hello, World!"

Multi-line String:

paragraph = """This is a paragraph.


It spans multiple lines."""

2. Accessing Characters in a String (Indexing)


Each character in a string has an index. Python uses 0-based indexing, so the
first character is at index 0 .

Example:

text = "Python"
print(text[0]) # Output: P
print(text[2]) # Output: t

Negative Indexing: You can also use negative indices to access characters
from the end of the string.

print(text[-1]) # Output: n
print(text[-3]) # Output: h

Untitled 2
3. Slicing Strings
Slicing allows you to get a specific part (substring) of the string.

Syntax: string[start:end]

Example:

word = "Python"
print(word[0:3]) # Output: Pyt
print(word[2:]) # Output: thon
print(word[:4]) # Output: Pyth
print(word[-3:]) # Output: hon

4. Modifying Strings
Strings are immutable in Python, meaning they cannot be changed after
creation. However, you can create a new string based on modifications.

Example:

text = "Hello"
new_text = text + " World" # Concatenation
print(new_text) # Output: Hello World

5. Common String Methods


Python has several built-in methods to work with strings:

.lower() : Converts all characters to lowercase.

print("HELLO".lower()) # Output: hello

.upper() : Converts all characters to uppercase.

Untitled 3
print("hello".upper()) # Output: HELLO

.strip() : Removes whitespace from the beginning and end of the string.

print(" hello ".strip()) # Output: hello

.replace(old, new) : Replaces a substring with another substring.

print("hello world".replace("world", "Python")) # Output: hello Python

.find(substring) : Finds the index of the first occurrence of a substring, or


returns 1 if not found.

print("hello world".find("world")) # Output: 6

6. Escape Characters
Escape characters allow you to include special characters in strings, like quotes
or newlines.

Examples:

print("He said, \"Hello!\"") # Output: He said, "Hello!"


print("Hello\nWorld") # Output:
# Hello
# World

7. Checking String Contents

Untitled 4
You can check for specific characters or substrings within a string using in and
not in keywords.

Example:

sentence = "The quick brown fox"


print("fox" in sentence) # Output: True
print("cat" not in sentence) # Output: True

Practice Programs:
1. Write a program that takes a user’s full name as input and prints it in
uppercase.

# Program to print full name in uppercase


full_name = input("Enter your full name: ")
print("Your name in uppercase is:", full_name.upper())

2. Create a program that asks for a sentence and prints the number of times
the word "Python" appears in it.

# Program to count occurrences of "Python" in a sentence


sentence = input("Enter a sentence: ")
count = sentence.count("Python")
print("The word 'Python' appears", count, "times in the sentence.")

3. Write a program to slice a string to extract the last 3 characters of a user-


input string.

# Program to extract the last 3 characters of a string


user_string = input("Enter a string: ")

Untitled 5
last_three_chars = user_string[-3:]
print("The last three characters are:", last_three_chars)

Conditional Statements: if, else, elif


→ Sometimes we want to play games on our phone if the day is Sunday.

→ Sometimes we order ice cream online if the day is sunny.

→ sometimes we go hiking if our parents allow it.

All these are decisions that depend on the condition.

In Python programming too we must be able to execute instructions on a


condition. This what conditional statement.

if statement:

if 5 > 3:
print("Five is greater than three")

else statement: Runs if the if condition is False.

if 3 > 5:
print("Three is greater")
else:
print("Five is greater")

elif (else if): Adds more conditions.

age = 18
if age < 18:
print("You are a minor")
elif age == 18:

Untitled 6
print("You just turned 18!")
else:
print("You are an adult")

Practice Programs
1. Using if Statements

1. Write a program that asks the user for their age. If the user is 18 years or
older, print "You are an adult." Otherwise, do nothing.

age = int(input("Enter your age: "))


if age >= 18:
print("You are an adult.")

2. Create a program that asks the user for a number. If the number is positive,
print "The number is positive."

number = float(input("Enter a number: "))


if number > 0:
print("The number is positive.")

3. Write a program that checks if a given number is even or odd using an if

statement. If the number is even, print "Even number".

num = int(input("Enter a number: "))


if num % 2 == 0:
print("Even number")

2. Using if-else Statements

Untitled 7
1. Write a Python program that checks whether a number entered by the user
is positive or negative. If the number is positive, print "Positive"; vv!, print
"Negative".

number = float(input("Enter a number: "))


if number >= 0:
print("Positive number")
else:
print("Negative number")

2. Create a program to check if a user is eligible to drive based on their age. If


the user is 18 years or older, print "You can drive"; otherwise, print "You
cannot drive."

age = int(input("Enter your age: "))


if age >= 18:
print("You can drive")
else:
print("You cannot drive")

3. Write a program that asks the user to enter a number and checks if the
number is divisible by 5. If it is divisible, print "Divisible by 5"; otherwise,
print "Not divisible by 5."

number = int(input("Enter a number: "))


if number % 5 == 0:
print("Divisible by 5")
else:
print("Not divisible by 5")

3. Using if-elif-else Statements

Untitled 8
1. Create a program that asks the user for their marks and prints the grade
according to the following conditions:

Marks >= 90: Print "A"

Marks >= 80: Print "B"

Marks >= 60: Print "D"

Marks >= 70: Print "C"

Marks < 60: Print "F"

marks = int(input("Enter your marks: "))


if marks >= 90:
print("Grade A")
elif marks >= 80:
print("Grade B")
elif marks >= 70:
print("Grade C")
elif marks >= 60:
print("Grade D")
else:
print("Grade F")

2. Write a program that asks the user for the day of the week (as a number
from 1 to 7) and prints the name of the day (e.g., 1 for "Monday", 2 for
"Tuesday", etc.).

day = int(input("Enter day number (1-7): "))


if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
elif day == 4:
print("Thursday")

Untitled 9
elif day == 5:
print("Friday")
elif day == 6:
print("Saturday")
elif day == 7:
print("Sunday")
else:
print("Invalid day number")

3. Create a Python program that asks the user to enter a number between 1
and 100. If the number is greater than 90, print "High"; if it's between 50
and 90, print "Medium"; and if it's less than 50, print "Low."

number = int(input("Enter a number between 1 and 100: "))


if number > 90:
print("High")
elif number >= 50:
print("Medium")
else:
print("Low")

Practice Questions
For if Statements
1. Write a program that asks the user to input their favorite color. If the color is
"blue", print "That's a cool color!".

2. Write a program that checks if a number entered by the user is greater than
100.

3. Write a program that asks the user for their score in a game. If the score is
above 50, print "You passed the level!".

4. Create a program that asks the user for the temperature in Celsius. If the
temperature is above 30, print "It's hot outside".

Untitled 10
5. Write a program to check if a given year is a leap year using the following
rule: a year is a leap year if it is divisible by 4 but not by 100, or it is divisible
by 400.

For if-else Statements


1. Write a program that asks for the user’s temperature. If it’s 37°C or higher,
print "You have a fever"; otherwise, print "You don’t have a fever."

2. Write a program that checks if a number entered by the user is a multiple of


10. If yes, print "Multiple of 10"; otherwise, print "Not a multiple of 10."

3. Write a program to determine if a person’s age is even or odd.

4. Create a program that asks the user for their score and checks if they
passed or failed (passing mark is 40).

5. Write a program that checks if a given number is zero or non-zero.

For if-elif-else Statements


1. Write a program that takes the price of a product as input and assigns a
discount based on the price:

Price > 1000: Discount 10%

Price between 500 and 1000: Discount 5%

Price < 500: No discount.

2. Create a program that checks if a person’s weight falls into one of the
following categories:

Below 50 kg: Underweight

50-70 kg: Normal weight

Above 70 kg: Overweight

3. Write a program to input the amount of rainfall (in mm) and print:

More than 50mm: "Heavy Rain"

20-50mm: "Moderate Rain"

Less than 20mm: "Light Rain"

4. Write a program that checks whether a student has passed or failed an


exam using the following rule:

Untitled 11
Marks >= 50: Passed

Marks >= 40 and <50: Retake

Marks < 40: Failed.

5. Write a program that takes a temperature in Fahrenheit and classifies it into:

Above 85°F: "Hot"

60°F to 85°F: "Warm"

Below 60°F: "Cold"

For if Statements
1. Write a program that asks the user to input their favorite color. If the color
is "blue", print "That's a cool color!".

color = input("Enter your favorite color: ")


if color.lower() == "blue":
print("That's a cool color!")

2. Write a program that checks if a number entered by the user is greater


than 100.

number = int(input("Enter a number: "))


if number > 100:
print("The number is greater than 100.")

3. Write a program that asks the user for their score in a game. If the score is
above 50, print "You passed the level!".

score = int(input("Enter your game score: "))


if score > 50:

Untitled 12
print("You passed the level!")

4. Create a program that asks the user for the temperature in Celsius. If the
temperature is above 30, print "It's hot outside".

temperature = float(input("Enter the temperature in Celsius: "))


if temperature > 30:
print("It's hot outside")

5. Write a program to check if a given year is a leap year.

year = int(input("Enter a year: "))


if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("It's a leap year.")

For if-else Statements


1. Write a program that asks for the user’s temperature. If it’s 37°C or higher,
print "You have a fever"; otherwise, print "You don’t have a fever."

temperature = float(input("Enter your temperature in Celsius: "))


if temperature >= 37:
print("You have a fever.")
else:
print("You don’t have a fever.")

2. Write a program that checks if a number entered by the user is a multiple


of 10.

number = int(input("Enter a number: "))

Untitled 13
if number % 10 == 0:
print("Multiple of 10")
else:
print("Not a multiple of 10")

3. Write a program to determine if a person’s age is even or odd.

age = int(input("Enter your age: "))


if age % 2 == 0:
print("Your age is even.")
else:
print("Your age is odd.")

4. Create a program that asks the user for their score and checks if they
passed or failed (passing mark is 40).

score = int(input("Enter your score: "))


if score >= 40:
print("You passed.")
else:
print("You failed.")

5. Write a program that checks if a given number is zero or non-zero.

number = int(input("Enter a number: "))


if number != 0:
print("The number is non-zero.")
else:
print("The number is zero.")

Untitled 14
For if-elif-else Statements
1. Write a program that takes the price of a product as input and assigns a
discount based on the price.

price = float(input("Enter the price of the product: "))


if price > 1000:
discount = price * 0.1
print(f"Discount applied: {discount}")
elif 500 <= price <= 1000:
discount = price * 0.05
print(f"Discount applied: {discount}")
else:
print("No discount available.")

2. Create a program that checks if a person’s weight falls into specific


categories.

weight = float(input("Enter your weight in kg: "))


if weight < 50:
print("Underweight")
elif 50 <= weight <= 70:
print("Normal weight")
else:
print("Overweight")

3. Write a program to input the amount of rainfall (in mm) and print rainfall
classification.

rainfall = float(input("Enter rainfall amount in mm: "))


if rainfall > 50:
print("Heavy Rain")
elif 20 <= rainfall <= 50:
print("Moderate Rain")

Untitled 15
else:
print("Light Rain")

4. Write a program that checks whether a student has passed, needs a


retake, or failed an exam.

marks = int(input("Enter your marks: "))


if marks >= 50:
print("Passed")
elif 40 <= marks < 50:
print("Retake required")
else:
print("Failed")

5. Write a program that takes a temperature in Fahrenheit and classifies it as


"Hot", "Warm", or "Cold".

temperature = float(input("Enter temperature in Fahrenheit: "))


if temperature > 85:
print("Hot")
elif 60 <= temperature <= 85:
print("Warm")
else:
print("Cold")

Untitled 16

You might also like