PyCharm Configuration for Windows OS

For installing PyCharm in your System go through the following steps:

  • Open a web browser (e.g., Google Chrome, Firefox, or Edge).1 2
  • Click on first link as shown in web browser ,go to the official JetBrains PyCharm website,or click Here .2 2
  • Visit the official PyCharm website at JETBRAINS and this web page will appear3 2
  • Once the page loads, you’ll see options for different editions of PyCharm.
    • Professional Edition: Paid version with advanced features.
    • Community Edition: Free version, ideal for Python programming.4 2
  • Click the Download button under the Community Edition section.5 2
  • You’ll be redirected to the download page.The website should automatically detect your operating system (Windows) and provide the correct installer.
    • If not, ensure Windows is selected in the operating system dropdown or button.
    • Click the Download button to start downloading the PyCharm Community Edition .exe installer.6 2
  • The installer file will begin downloading. Its name will look something like pycharm-community-<version>.exe.Wait for the download to finish. The file size is usually around 300–400 MB.
    • Locate the downloaded .exe file (usually in your Downloads folder).
    • Double-click the file to start the installation process.7 2
  • A setup wizard will appear. Follow these steps:
    • Welcome Screen: Click Next.
    • Choose Installation Path: Select or confirm the default location where PyCharm will be installed (e.g., C:\Program Files\JetBrains\PyCharm Community Edition). Then, click Next.8 2
  • Installation Options:
    • Check Create Desktop Shortcut (optional).
    • Check Update PATH variable (optional but recommended for easy access to PyCharm from the command line).
    • Check Add Open Folder as Project (optional).
    • Click Next.9 2
  • Choose Start Menu Folder: Leave the default or choose a custom folder for shortcuts. Click Install.
    • 10 2The installation will begin. This might take a few minutes.
    • 11 2
  • Once the installation is complete, check Run PyCharm Community Edition if you want to open it immediately.12 2
  • Open desktop and click on PyCharm Logo.13 2
  • This Dialogue Box will appear, when you click on desktop Shortcut .14 2
  • After PyCharm opens, create a new project:
    • Click New Project.
    • Choose a location and name for the project.15 1
  • If everything works as expected, your PyCharm setup is complete.16 1
  • Right Click on your project name and select new.17
  • In New select for New file Python file.18
  • Name your Python file , here “Trial”.19
  • Write a Trial program of printing a “Hello World” ,and to run that script right click on screen & select Run and Debug.22
  • This Will be the output of the “Trial”. # printing “Hello World “23

Python installation in Windows OS:

  • Open Google Chrome or any other web browser and search for Python. 1 1 e1737919354722
  • Visit the official Python website at python.org.2 1 e1737960267614
  • Navigate to the Downloads section and select the latest stable release for Windows.Choose the appropriate installer based on your system architecture:
  • For 64-bit systems: “Windows installer (64-bit)”
  • For 32-bit systems: “Windows installer (32-bit)”3 1 e1737960433455
  • Locate the downloaded installer file (e.g., python-3.x.x-amd64.exe) and double-click to run it.4 1
  • Check the box labeled “Add Python to PATH” to ensure you can run Python from the command line.Click on “Install Now” to proceed with the default installation.5 1
  • In the “Optional Features” section, you can select additional components like:
    • Documentation
    • pip (Python package installer)
    • tcl/tk and IDLE (Python’s Integrated Development and Learning Environment)
    • Python test suite
    • py launcher6 1
  • Click “Next” and in the “Advanced Options” section, you can:
    • Choose the installation location
    • Add Python to environment variables
    • Install for all users7 1
  • After selecting the desired options, click “Install” to begin the installation.8 19 1 e1737960510964
  • Verify the Installation:
    • Open the Command Prompt:
    • Press Win + R, type cmd, and press Enter.
  • pip --version run in command prompt and python --version.14 1 e1737961172208

Python Installation & Configuration

Python Installation for MacOS:

To install Python on macOS, ensure your system meets the basic requirements: macOS 10.9 or later with a stable internet connection. Download the latest Python installer from python.org, follow the on-screen instructions, and verify the installation via Terminal. Ensure sufficient storage and admin rights for installation.


mac os python install


Python Installation for Windows OS:

To install Python on Windows, ensure your system runs Windows 7 or later with an internet connection. Download the latest Python installer from python.org, run the installer, and select “Add Python to PATH.” Follow the on-screen instructions and verify the installation through Command Prompt.

an image with windows logo and python language logo

Python List

Python List Tutorial

Introduction:

Lists are one of the most commonly used data structures in Python. A list is a collection of elements, which can be of any type, including numbers, strings, and other lists etc. Lists are mutable, which means you can make changes in the list by adding, removing, or changing elements.

List declaration:

To declare a list in Python, you can use square brackets [] and separate the elements with commas. Here’s an example:

new_list = [ 1, 2, 3, 4, 5 ]

In the above example, we created a list called new_list that contains five integers.

You can also create an empty list by using the list() function or just an empty set of square brackets [].  Here are some examples:

list_1 = list()
list_2 = []

Both of the examples above create an empty list called empty_list_1 and list_2.

You can also create a list of a specific size filled with a default value using the * operator.  Here’s an example:

empty_list_1 = []
empty_list_2 = list()

In the example above, we created a list called my_list that contains three 1 values.

my_list = [1, 1, 1]

List Rules:

  1. List elements can be of different data types, including integers, floats, strings, booleans, and other objects.
  2. Lists are mutable, which means that we can modify it by adding, removing, or changing elements.
  3. Index of elements in the list starts from 0. We can access individual elements of a list by their index.
  4. We can use slicing to extract a subset of elements from a list. Slicing returns a new list that includes the specified range of elements.
  5. Lists can be concatenated using the ‘+’ operator.
  6. Lists can be nested, meaning that you can have a list of lists.
  7. Lists can be sorted in ascending or descending order using the sorted() function or the sort() method.
  8. We can use the len() function to get the number of elements in a list.
  9. We can iterate over the elements of a list using a for loop or list comprehension.
  10. Two lists can be compared for equality using the ‘==’ operator. Two lists are considered equal if they have the same elements in the same order.

Python list features:

  1. Mutable: Lists are mutable, meaning you can modify their elements by assigning new values to specific indices.
  2. Ordered: Lists maintain the order of elements as they are added. The first element added will be at index 0, the second element at index 1, and so on.
  3. Dynamic Size: Python lists can dynamically grow or shrink in size as elements are added or removed. You don’t need to specify the size beforehand.
  4. Heterogeneous Elements: Lists can contain elements of different data types. For example, a single list can store integers, floats, strings, or even other lists.
  5. Indexing and Slicing: You can access individual elements in a list using square brackets notation and their index. Additionally, you can slice lists to extract a portion of elements by specifying start and end indices.
  6. Iteration: Lists can be easily iterated over using loops or list comprehensions, allowing you to process each element or perform operations on the entire list.
  7. Built-in Functions: Python provides a range of built-in functions specifically designed for working with lists. These include functions like `len()`, `max()`, `min()`, `sum()`, `sorted()`, and more.
  8. Versatile Data Structure: Lists are a versatile data structure used in a variety of scenarios. They are commonly used for storing collections of related items, implementing stacks, queues, and other data structures, and for general-purpose data manipulation.
  9. List Comprehensions: Python allows you to create new lists by performing operations on existing lists using concise and expressive syntax called list comprehensions. This feature provides an efficient and readable way to manipulate lists.
  10. Extensive Methods: Python lists come with a range of built-in methods that enable various operations like adding or removing elements, sorting, reversing, searching, and more. These methods make it easy to work with lists and perform common list operations efficiently.

Python list advantages:

  1. Flexibility: Python lists are highly flexible and versatile. They can store elements of different data types, allowing you to create lists with a mix of integers, floats, strings, and other objects. This flexibility makes lists suitable for a wide range of applications.
  2. Dynamic Size: Lists in Python can grow or shrink dynamically as elements are added or removed. Unlike some other programming languages, you don’t need to specify the size of a list beforehand. This dynamic resizing capability makes it convenient to work with collections of varying lengths.
  3. Easy Element Manipulation: Python provides intuitive ways to manipulate list elements. You can easily access, modify, or delete elements based on their indices. This makes it convenient to update or rearrange elements within a list as needed.
  4. Iteration and Looping: Python lists can be easily iterated over using loops or list comprehensions. This allows you to process each element in a list sequentially or apply operations to the entire list, making it straightforward to perform calculations or transformations on list data.
  5. Built-in Functions and Methods: Python provides a rich set of built-in functions and methods specifically designed for working with lists. These functions and methods simplify common list operations such as sorting, searching, filtering, adding or removing elements, and more. This extensive set of tools saves you time and effort when working with lists.
  6. Powerful List Comprehensions: Python offers list comprehensions, which are concise and expressive ways to create new lists based on existing ones. List comprehensions allow you to apply transformations, conditions, and calculations to existing lists in a single line of code, making your code more readable and compact.
  7. Compatibility with Other Data Structures: Lists in Python can easily be converted to and from other data structures like tuples or arrays. This compatibility allows you to take advantage of the specific features and benefits offered by different data structures as needed.
  8. Common Data Structure: Python lists are widely used and well-supported. They are a fundamental data structure in Python, and you’ll find them extensively used in libraries, frameworks, and code examples. This popularity means that there is a wealth of resources, documentation, and community support available for working with lists.

Python list disadvantages:

  1. Slow for Large Data Sets: Python lists may become inefficient when dealing with large data sets or performing operations that require frequent insertions or deletions. As lists are dynamically resized, these operations can be time-consuming, particularly if the list needs to be resized multiple times.
  2. Sequential Search: When searching for an element in a list, Python performs a sequential search, iterating through each element until a match is found. This linear search approach can be slow for large lists, especially when compared to more efficient search algorithms like binary search available for sorted arrays.
  3. Fixed Overhead: Each element in a Python list requires additional memory to store its value and associated metadata, such as the data type and object reference. This fixed overhead per element can be significant when dealing with large lists, potentially consuming more memory than other data structures optimized for memory efficiency.
  4. Lack of Constant-Time Operations: Certain operations on Python lists, such as inserting or removing an element at a specific index, can be slow for large lists. These operations may require shifting or reassigning elements, resulting in a time complexity of O(n), where n is the number of elements in the list. In contrast, other data structures like arrays or linked lists can provide constant-time operations for these operations.
  5. Limited Sorting Options: Python’s built-in sorting method, `list.sort()`, uses a variant of the quicksort algorithm. While it is efficient in most cases, it may not be suitable for certain specialized sorting requirements. For such scenarios, you may need to implement custom sorting algorithms or explore external libraries for specific sorting needs.
  6. Not Suitable for Unique Elements: Python lists can contain duplicate elements. If you require a collection that only allows unique elements, you need to perform additional checks or use alternative data structures like sets or dictionaries.
  7. Mutable Nature: While mutability can be an advantage, it can also lead to unintended changes in list elements. If a list is shared among multiple parts of a program or passed as a parameter to functions, modifying the list can affect other parts of the code unintentionally. This can lead to potential bugs or unexpected behavior.

Python List Indexing and Slicing

In Python first element in the list has an index of 0. You can access elements in a list by their index using square brackets. Here’s an example:

# Define a list
my_list = ['apple', 'banana', 'cherry']

# Access the first element
first_element = my_list[0] # 'apple'

# Access the second element
second_element = my_list[1] # 'banana'

# Access the third element
third_element = my_list[2] # 'cherry'

# Print the elements
print("First element:", first_element)
print("Second element:", second_element)
print("Third element:", third_element)

You can also use negative indexing to access the list elements in the reverse order. Here’s an example:

# Define a list
my_list = ['apple', 'banana', 'cherry']

# Access the last element
last_element = my_list[-1] # 'cherry'

# Access the second-to-last element
second_last_element = my_list[-2] # 'banana'

# Access the third-to-last (or first) element
third_last_element = my_list[-3] # 'apple'

# Print the elements

print("Last element:", last_element)
print("Second-to-last element:", second_last_element)
print("Third-to-last element:", third_last_element)
Slicing rules to created sublist in python:

Here are the rules for slicing in Python:

  1. Slicing uses the colon : operator to specify a range of indices. The syntax is my_list[start_index:end_index:step].
  2. The start_index is the index of the first element to include in the slice. If not specified, it defaults to 0.
  3. The end_index is the index of the first element to exclude from the slice. If not specified, it defaults to the length of the list.
  4. The step parameter specifies the step size between elements in the slice. If not specified, it defaults to 1.
  5. All parameters can be negative, in which case they specify the index relative to the end of the list. For example, my_list[-1] refers to the last element of the list.
  6. Slicing returns a new list that contains the specified range of elements from the original list.

You can also use slicing to access a subset of the list. Slicing allows you to extract a range of elements from the list. Here’s an example:

# Define a list
my_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']

# Slice to get the first three elements
first_three = my_list[0:3] # ['apple', 'banana', 'cherry']

# Slice to get elements from index 2 to the end
from_second_onwards = my_list[2:] # ['cherry', 'date', 'elderberry']

# Slice to get the last two elements
last_two = my_list[-2:] # ['date', 'elderberry']

# Slice with a step of 2 (every second element)
every_second = my_list[::2] # ['apple', 'cherry', 'elderberry']

# Print the results
print("First three elements:", first_three)
print("From second onwards:", from_second_onwards)
print("Last two elements:", last_two)
print("Every second element:", every_second)

In the example above, we used slicing to extract a subset of the list that starts at index 0 and ends at index 3 ( not including index 3 ).

Python List Methods:

Lists in Python have many built-in methods that you can use to modify or manipulate the list. Here are some of the most commonly used methods:

  1. append() – It is used to add an element to the end of the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Add an element to the end of the list
my_list.append('date')

# Print the updated list
print(my_list)
  1. extend() – It is used to add the elements of another list to the end of the list or to combine two lists.
# Define a list
my_list = ['apple', 'banana']

# Extend the list with a tuple
my_list.extend(('cherry', 'date'))

# Extend the list with a set

my_list.extend({'elderberry', 'fig'})

# Print the updated list
print(my_list)
  1. insert() – It is used to insert an element at a specific position in the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Insert an element at index 1
my_list.insert(1, 'date')

# Print the updated list
print(my_list)

         4. remove() – It is used to remove the first occurrence of an element from the list.

# Define a list
my_list = ['apple', 'banana', 'cherry', 'banana']

# Remove the first occurrence of 'banana'
my_list.remove('banana')

# Print the updated list
print(my_list)
  1. pop() – It removes and returns the element at a specific position in the list.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Remove and return the last element
removed_element = my_list.pop()

# Print the updated list and the removed element
print("Updated list:", my_list)
print("Removed element:", removed_element)

          6. sort() – It sorts the elements of the list in ascending order.

# Define a list of numbers
my_list = [3, 1, 4, 1, 5, 9, 2, 6]

# Sort the list in descending order
my_list.sort(reverse=True)

# Print the sorted list
print(my_list)

          7 .reverse() – It reverses the order of the elements in the list.

# Define a list of strings
my_list = ['apple', 'banana', 'cherry']

# Reverse the list
my_list.reverse()

# Print the reversed list
print(my_list)
  1. clear() – It is used to remove all elements from a list, effectively emptying the list. After the clear() function is applied to a list, the list becomes empty with a length of 0.
# Define a list of strings
my_list = ['apple', 'banana', 'cherry']

# Clear all elements from the list
my_list.clear()

# Print the cleared list
print(my_list)
  1. copy() – It creates a shallow copy of a list. The shallow copy means that a new list is created with the same elements as the original list, but the elements themselves are not duplicated. Any changes made to the elements in the copied list will also affect the original list, and vice versa.
# Define a list with immutable elements
my_list = [1, 2, 3]

# Create a shallow copy of the list
my_list_copy = my_list.copy()

# Modify the copied list
my_list_copy.append(4)

# Print both lists
print("Original list:", my_list)
print("Copied list:", my_list_copy)
  1. index() – It is used to find the index of the first occurrence of a specified element within a list. If the element is not found in the list, it raises a ValueError.
# Define a list
my_list = ['apple', 'banana', 'cherry']

# Find the index of 'banana'
index_of_banana = my_list.index('banana')

# Print the index
print("Index of 'banana':", index_of_banana)
  1. count() – It is used to count the number of occurrences of a specified element in a list.
# Define a list
my_list = ['apple', 'banana', 'cherry', 'banana', 'apple']

# Count occurrences of 'banana'
banana_count = my_list.count('banana')

# Print the count
print("Count of 'banana':", banana_count)

Updating list values:

Lists in Python are mutable, and their values can be updated by using the slice and assignment the ( = ) operator.

# Define a list
my_list = [1, 2, 3, 4, 5]

# Remove elements at indices 1 to 3
my_list[1:4] = []

# Print the updated list
print(my_list)

Built-in function for Python lists:

Here are some examples of commonly used built-in functions for lists in Python:

  1. len(): It returns the length of the list.
# Define a list
my_list = [1, 2, 3, 4, 5]

# Get the length of the list
list_length = len(my_list)

# Print the length
print("Length of the list:", list_length)
  1. max(): It returns the largest element in the list.
# Define a list of numbers
my_list = [1, 5, 3, 9, 2]

# Get the largest element in the list
largest_element = max(my_list)

# Print the largest element

print("Largest element:", largest_element)
  1. min(): It returns the smallest element in the list.
# Define a list of numbers
my_list = [10, 5, 20, 3, 8]

# Get the smallest element in the list
smallest_element = min(my_list)

# Print the smallest element
print("Smallest element:", smallest_element)
  1. sum(): It returns the sum of all elements in the list.
# Define a list of numbers
my_list = [1, 2, 3, 4, 5]

# Calculate the sum of the elements in the list
total_sum = sum(my_list)

# Print the total sum
print("Sum of the list:", total_sum)

       5. sorted(): It returns a new sorted list.

# Define a list of numbers
my_list = [5, 2, 9, 1, 5, 6]

# Get a new sorted list
sorted_list = sorted(my_list)

# Print the sorted list
print("Sorted list:", sorted_list)
  1. list(): It converts an iterable to a list.
# Define a tuple
my_tuple = (1, 2, 3, 4)

# Convert the tuple to a list
my_list = list(my_tuple)

# Print the list
print("List from tuple:", my_list)

       7. any(): It returns True if at least one element in the list is True.

# Define a list of Boolean values
my_list = [False, False, True, False]

# Check if any element is True
result = any(my_list)

# Print the result
print("Any True in the list:", result)
  1. all(): It returns True if all elements in the list are True.
# Define a list of Boolean values
my_list = [True, True, True]

# Check if all elements are True
result = all(my_list)

# Print the result
print("All True in the list:", result)

        9. enumerate(): It returns an iterator that contains tuples of (index, element) pairs.

# Define a list
my_list = ['apple', 'banana', 'cherry']

# Use enumerate to get index and element
for index, element in enumerate(my_list):
print(f"Index: {index}, Element: {element}")
  1. zip(): It returns an iterator that aggregates elements from multiple lists into tuples.
# Define two lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

# Use zip to combine them into tuples
zipped = zip(list1, list2)

# Convert the zipped object to a list and print
zipped_list = list(zipped)
print(zipped_list)

        11.reversed(): It returns a reverse iterator that can be used to iterate over a list in reverse order.

# Define a list
my_list = [1, 2, 3, 4, 5]

# Convert the reversed iterator to a list
reversed_list = list(reversed(my_list))

# Print the reversed list
print(reversed_list)

Iterating over a list

We can use a for loop to iterate over the list elements. Here’s an example:

# Define a list of fruits
fruits = ['apple', 'banana', 'cherry', 'date']

# Use a for loop to iterate over the list
for fruit in fruits:
print(fruit)

Membership operator in list

We can use operator (i.e. in or not in) on list elements. If an element is in list then it returns True. If an element is not in list it return False. Here’s an example:

# Example list
fruits = ['apple', 'banana', 'cherry', 'date']

# Using 'in' to check if an element is in the list
print('apple' in fruits) # Output: True
print('orange' in fruits) # Output: False


# Using 'not in' to check if an element is not in the list
print('grape' not in fruits) # Output: True
print('banana' not in fruits)
# Output: False

Repetition on list

We can use (*) operator for repetition of list. Here’s an example:

# Example list
fruits = ['apple', 'banana', 'cherry']

# Using * operator for repetition
repeated_list = fruits * 3

print(repeated_list)
# Output: ['apple', 'banana', 'cherry', 'apple', 'banana', 'cherry', 'apple', 'banana', 'cherry']

Concatenation on list

We can use (+) operator for concatenation of list. Here’s an example:

# Example lists
list1 = ['apple', 'banana']
list2 = ['cherry', 'date']

# Using + operator for concatenation
combined_list = list1 + list2

print(combined_list)
# Output: ['apple', 'banana', 'cherry', 'date']

List Comprehension

List comprehension is a concise and expressive way of creating lists in Python. It allows you to define a list and its elements within a single line of code, combining the functionality of a for loop, optional if conditions, and even nested loops. List comprehensions are preferred for their readability and efficiency compared to traditional for loops.

  1. Simple For Loop List Comprehension:

This type of list comprehension is used to create a list by iterating over elements from an iterable (e.g., list, tuple, string) without any filtering or conditions. Here’s an example:

# Example list
numbers = [1, 2, 3, 4, 5]

# List comprehension without filtering or conditions
new_list = [num for num in numbers]

print(new_list) # Output: [1, 2, 3, 4, 5]
  1. Loop and If Condition List Comprehension:

This type of list comprehension includes an if condition to filter elements while iterating over the iterable. Only elements that satisfy the condition are included in the new list. Here’s an example:

# Example list
numbers = [1, 2, 3, 4, 5, 6]

# List comprehension with an if condition
even_numbers = [num for num in numbers if num % 2 == 0]

print(even_numbers) # Output: [2, 4, 6]
  1. Loop and If-Else Condition List Comprehension:

This type of list comprehension allows you to perform different operations based on the if-else condition while iterating over the iterable. Here’s an example:

# Example list
numbers = [1, 2, 3, 4, 5, 6]

# List comprehension with if-else condition
result = ['Even' if num % 2 == 0 else 'Odd' for num in numbers]

print(result)
# Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']
  1. Nested Loop List Comprehension:

This type of list comprehension allows you to use nested loops for creating more complex lists by iterating over multiple iterables simultaneously. Here’s an example:

# Example nested loops
colors = ['red', 'green', 'blue']
objects = ['ball', 'box', 'pen']

# List comprehension with nested loops
combinations = [f"{color} {obj}" for color in colors for obj in objects]

print(combinations)
# Output: ['red ball', 'red box', 'red pen', 'green ball', 'green box', 'green pen', 'blue ball', 'blue box', 'blue pen']

Shallow Copy and Deep Copy of Lists in Python:

In Python, when dealing with lists or other compound data structures, understanding the concepts of shallow copy and deep copy is crucial. Both concepts involve creating a new copy of an existing list, but they differ in how they handle nested objects within the list.

  1. Shallow Copy:

A shallow copy of a list creates a new list object but does not create copies of the elements inside the list. Instead, it copies references to the original objects. This means that changes made to nested objects within the copied list will affect the original list, and vice versa. To perform a shallow copy, you can use the `copy()` method or the slicing notation `[:]`. Example of Shallow Copy:

import copy

# Original list with a nested list
original_list = [[1, 2, 3], [4, 5, 6]]

# Shallow copy using the copy() method
shallow_copy1 = original_list.copy()

# Shallow copy using slicing notation
shallow_copy2 = original_list[:]

# Modifying a nested element in the copied list
shallow_copy1[0][0] = 99

print("Original List:", original_list)
# Output: Original List: [[99, 2, 3], [4, 5, 6]]

print("Shallow Copy 1:", shallow_copy1)
# Output: Shallow Copy 1: [[99, 2, 3], [4, 5, 6]]

print("Shallow Copy 2:", shallow_copy2)
# Output: Shallow Copy 2: [[99, 2, 3], [4, 5, 6]]
  1. Deep Copy:

A deep copy of a list creates a new list object and also recursively creates copies of all the nested objects within the original list. In other words, the copied list and its nested objects are entirely independent of the original list and its nested objects. To perform a deep copy, you need to use the `deepcopy()` function from the `copy` module. Example of Deep Copy:

import copy

# Original list with nested lists
original_list = [[1, 2, 3], [4, 5, 6]]

# Creating a deep copy
deep_copy = copy.deepcopy(original_list)

# Modifying a nested element in the deep copy
deep_copy[0][0] = 99

print("Original List:", original_list)
# Output: Original List: [[1, 2, 3], [4, 5, 6]]

print("Deep Copy:", deep_copy)
# Output: Deep Copy: [[99, 2, 3], [4, 5, 6]]

Shallow copy is faster and suitable when you want to create a new list but share references to nested objects. Deep copy is appropriate when you need an entirely independent copy of the original list and all its nested objects.

Python String

Python String Tutorials

Introduction:

A string is a sequence of characters. In Python, you can define a string using either single quotes () or double quotes (), or triple quotes (”’ or “””) for multiline strings. Here are some examples:

Python string features:

  1. Immutable: Strings in Python are immutable, meaning that once a string is created, its contents cannot be changed. If you want to modify a string, you need to create a new string with the desired changes.
  2. Sequence of Characters: Strings are a sequence of individual characters. Each character in a string is assigned an index, starting from 0 for the first character. This allows you to access and manipulate specific characters within a string using indexing and slicing operations.
  3. Unicode Support: Python strings support Unicode, allowing you to work with characters from different languages, including non-ASCII characters. This enables you to handle and process text in various encodings and writing systems.
  4. Concatenation: Strings can be concatenated using the “+” operator, allowing you to combine multiple strings into a single string. For example, “Hello” + ” ” + “World” results in the string “Hello World”.
  5. Length: You can obtain the length of a string using the `len()` function, which returns the number of characters in the string. This is useful for determining the size of a string or iterating over its characters.
  6. String Formatting: Python provides various methods for formatting strings. This includes the use of placeholders or format specifiers, such as `%` operator or the `format()` method, to insert variables or values into a string with specified formatting.
  7. String Operations and Methods: Python offers a wide range of built-in operations and methods specifically designed for working with strings. These include operations like string concatenation, repetition, and membership checks, as well as methods for case conversion, substring searching, replacing, splitting, stripping, and more.
  8. Escape Sequences: Strings in Python support escape sequences, which allow you to include special characters that are difficult to type directly. For example, using `n` represents a newline character, `t` represents a tab character, and `”` represents a double quote character within a string.
  9. String Comparison: Strings can be compared using operators such as `==`, `!=`, `<`, `>`, `<=`, and `>=`. Comparison is performed based on lexicographic (dictionary) ordering of characters, which compares each corresponding character’s Unicode value.
  10. String Iteration: Python allows you to iterate over a string using loops, enabling you to process each character individually or perform operations on the entire string.

Python string advantages:

  1. Versatility: Python strings are versatile and widely used for handling and manipulating text-based data. They can store and process alphanumeric characters, symbols, and even Unicode characters, making them suitable for various applications and internationalization needs.
  2. Immutable Nature: Python strings are immutable, meaning their contents cannot be changed once they are created. This immutability ensures the integrity of strings and prevents accidental modifications, making them reliable for operations like string matching, hashing, or as keys in dictionaries.
  3. Extensive String Methods: Python provides a rich set of built-in string methods that offer a wide range of operations. These methods allow you to perform tasks like searching, replacing, splitting, joining, formatting, case conversion, and more. The extensive set of string methods simplifies complex string manipulation tasks and saves you time and effort.
  4. Unicode Support: Python strings have excellent support for Unicode, making them capable of representing characters from various writing systems, including non-ASCII characters. This allows you to work with and process text in different languages and encodings, making Python strings suitable for internationalization and multilingual applications.
  5. String Formatting: Python offers flexible and powerful string formatting capabilities. With techniques like the `%` operator or the `format()` method, you can easily insert variables or values into a string with specified formatting. This makes it convenient for generating dynamic strings, constructing messages, or formatting output.
  6. String Interpolation: Python 3.6 and later versions introduce f-strings, which provide a concise and readable way to embed expressions within string literals. This feature, known as string interpolation, simplifies the process of combining variables and expressions with strings, improving code readability and reducing the need for concatenation.
  7. Compatibility with File Operations: Python strings integrate seamlessly with file handling operations. You can read or write strings to files, manipulate file paths as strings, and use string methods to parse or manipulate file content. This compatibility makes it easier to work with text files and perform file-related operations.
  8. Regular Expressions: Python’s `re` module offers support for regular expressions, providing powerful pattern matching and text manipulation capabilities. Regular expressions allow you to search for specific patterns, extract information, or perform complex text transformations, making them valuable for tasks like data validation, parsing, and text processing.
  9. Consistency and Familiarity: Python strings follow consistent syntax and behavior across different operations and methods. This consistency, combined with Python’s focus on readability and simplicity, makes working with strings in Python intuitive and easy for developers who are familiar with the language.
  10. Extensive Community and Documentation: Python is a widely adopted programming language, and as a result, there is a vast community of developers and extensive documentation available for working with strings. You can find libraries, tutorials, and resources to help with advanced string manipulation, handling special cases, or optimizing string-related operations.

Python string disadvantages:

  1. Immutability: While immutability can be an advantage in terms of data integrity, it can also be a disadvantage when it comes to efficiency. Since strings are immutable, any operation that involves modifying a string, such as concatenation or replacing characters, requires creating a new string object. This can be inefficient, especially when dealing with large strings or performing many operations.
  2. Memory Overhead: Each individual character in a Python string requires memory to store its Unicode value and other metadata. This fixed overhead per character can consume significant memory, especially when working with large strings or processing large amounts of text data. In scenarios with memory constraints, this overhead can become a limiting factor.
  3. Difficulty with Mutable Operations: Some string manipulation tasks, such as inserting or removing characters at specific positions, can be cumbersome and inefficient due to the immutability of strings. Achieving such operations often requires creating new string objects or converting the string to a mutable data structure like a list, performing the operation, and then converting it back to a string.
  4. Comparison Complexity: Comparing strings for equality or sorting them can have time complexity proportional to the length of the strings being compared. In cases where string comparison or sorting is a critical performance factor, more efficient data structures or algorithms, like tries or radix sort, might be more suitable.
  5. Limited Unicode Support in Older Versions: While Python has excellent Unicode support, there were limitations in earlier versions (pre-Python 3) regarding Unicode handling. Older versions required explicit encoding and decoding operations when working with non-ASCII characters, which could be a source of confusion or errors.
  6. Limited Mutable String Options: While Python strings are immutable, there may be scenarios where mutable string operations are desired. Python’s built-in string methods offer limited options for in-place modification, and workarounds like converting the string to a list and back can introduce additional complexity and potential performance drawbacks.
  7. Difficulty with Low-Level Operations: Python strings abstract away low-level memory access and manipulation, which can be advantageous for most applications. However, in certain scenarios where direct byte-level or bit-level manipulation is required, Python strings may not be the most suitable data structure, and using other byte-oriented data types or libraries may be more appropriate.
  8. Performance in Heavy String Manipulation: For scenarios that involve heavy string manipulation, such as text parsing or processing large volumes of text data, Python strings may not offer the best performance. In such cases, lower-level languages or specialized text processing libraries may provide more efficient options.

Re-assign Strings:

In Python, you can reassign a string to a new value by simply assigning the new value to the variable that holds the string.  Here’s an example:

# Initial string assignment
my_string = "Hello, World!"
print("Original string:", my_string)

# Reassigning the string to a new value
my_string = "Welcome to Python!"
print("Reassigned string:", my_string)

In the example above, the first print statement outputs “Hello, World!” because my_string is initially assigned that value. Then, my_string is reassigned to “Sqatools” and the second print statement outputs the new value.

It’s important to note that strings are immutable in Python, which means that once you create a string, you cannot modify it. When you “modify” a string by, for example, concatenating two strings or removing a character, you are actually creating a new string object. Here are some examples:

# Example to demonstrate string immutability in Python

# 1. String Concatenation
greeting = "Hello"
new_greeting = greeting + ", World!"
print("Original string (after concatenation):", greeting) # Output: Hello
print("New string (concatenation result):", new_greeting) # Output: Hello, World!

# 2. String Replacement
my_string = "Hello, Python!"
new_string = my_string.replace("Python", "World")
print("\nOriginal string (after replacement):", my_string) # Output: Hello, Python!
print("New string (replacement result):", new_string) # Output: Hello, World!

# 3. String Slicing
text = "Immutable"
sliced_text = text[:3] # Taking the first three characters
print("\nOriginal string (after slicing):", text) # Output: Immutable
print("Sliced string (slicing result):", sliced_text) # Output: Imm

Deleting string:

In Python, you cannot delete individual characters in a string because strings are immutable. However, you can delete the entire string object from memory using the del statement.  Here’s an example:

In the example above, the first print statement outputs the value of my_string, which is “Hello, World!”. Then, the del statement deletes the my_string object from memory. When we try to print my_string again, we get a NameError because the variable no longer exists.

String formatting methods:

Python provides several methods for formatting strings. Here are the most commonly used methods:

  1. The % operator: This operator allows you to format strings using placeholders, which are replaced with values at runtime. Here’s an example:
# Using the % operator for string formatting
name = "Alice"
age = 25

formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, %s and %d are placeholders for the name and age variables, respectively. The values of these variables are provided in a tuple that follows the % operator.

  1. The str.format() method: This method allows you to format strings using placeholders that are enclosed in curly braces. Here’s an example:
# Using the str.format() method for string formatting
name = "Alice"
age = 25

formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, {} is a placeholder for the name and age variables. The values of these variables are provided as arguments to the str.format() method.

  1. F-strings: It allows you to embed expressions inside placeholders that are enclosed in curly braces preceded by the f character. Here’s an example:
# Using f-strings for string formatting
name = "Alice"
age = 25

# Embedding variables directly into the string
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
# Output: My name is Alice and I am 25 years old.

In the example above, the f character before the string indicates that it is an f-string. The expressions inside the curly braces are evaluated at runtime and the resulting values are inserted into the string.

String operator:

In Python, strings support several operators that can be used to perform various operations on strings. Here are some of the most commonly used string operators:

  1. Concatenation (+): The + operator can be used to concatenate two or more strings. Here’s an example:
# Using the + operator to concatenate strings
str1 = "Hello"
str2 = "World"
combined_str = str1 + " " + str2 # Adding a space between the words

print(combined_str)
# Output: Hello World
  1. Repetition (*): The * operator can be used to repeat a string a certain number of times. Here’s an example:
# Using the * operator to repeat a string
str1 = "Hello "
repeated_str = str1 * 3 # Repeating the string 3 times

print(repeated_str)
# Output: Hello Hello Hello
  1. Membership (in): The in operator can be used to check if a substring exists within a string. It returns True if the substring is found, and False otherwise. Here’s an example:
# Using the 'in' operator to check membership
sentence = "Python is awesome!"

# Checking if a substring exists within the string
substring = "Python"
result = substring in sentence

print(result)
# Output: True
  1. Indexing ([]): The [] operator can be used to access individual characters within a string. You can use a positive index to access characters from the beginning of the string, and a negative index to access characters from the end of the string. Here’s an example:
# Using the [] operator for indexing a string
my_string = "Python"

# Accessing characters using positive indices
first_char = my_string[0] # First character
last_char = my_string[5] # Last character (index 5 for "n")

print("First character:", first_char) # Output: P
print("Last character:", last_char) # Output: n

# Accessing characters using negative indices
second_last_char = my_string[-2] # Second last character (index -2 for "o")
print("Second last character:", second_last_char) # Output: o
  1. Slicing ([start:end]): The [] operator can also be used to extract a substring (or slice) from a string. The start argument specifies the starting index of the slice (inclusive), and the end argument specifies the ending index of the slice (exclusive). Here’s an example:
# Using the [] operator for string slicing
my_string = "Python Programming"

# Extracting a substring using slicing
substring = my_string[0:6] # From index 0 to 5 (6 is exclusive)
print(substring) # Output: Python
  1. Comparison (==, !=, <, <=, >, >=): The comparison operators can be used to compare two strings alphabetically. The == operator returns True if the two strings are equal, and False otherwise. The != operator returns True if the two strings are not equal, and False otherwise. The < and > operators return True if the left string is alphabetically less than or greater than the right string, respectively. The <= and >= operators return True if the left string is alphabetically less than or equal to or greater than or equal to the right string, respectively. Here’s an example:
# Comparison of strings using various operators
string1 = "Apple"
string2 = "Banana"

# Checking if the strings are equal
print(string1 == string2) # Output: False

# Checking if the strings are not equal
print(string1 != string2) # Output: True

# Checking if string1 is alphabetically less than string2
print(string1 < string2) # Output: True

# Checking if string1 is alphabetically greater than string2
print(string1 > string2) # Output: False

# Checking if string1 is alphabetically less than or equal to string2
print(string1 <= string2) # Output: True

# Checking if string1 is alphabetically greater than or equal to string2
print(string1 >= string2) # Output: False

String indexing and slicing:

Indexing:

Indexing: Each character in a string is assigned an index starting from 0. You can access a particular character in a string using its index. Here’s an example:

# Using indexing to access characters in a string
my_string = "Python"

# Accessing individual characters using their indices
first_char = my_string[0] # First character
second_char = my_string[1] # Second character
last_char = my_string[5] # Last character

print("First character:", first_char) # Output: P
print("Second character:", second_char) # Output: y
print("Last character:", last_char) # Output: n
Slicing:

You can extract a portion of a string using slicing. Slicing is done using the [] operator, with two indices separated by a colon (:) inside the brackets. Here’s an example:

# Using slicing to extract a portion of a string
my_string = "Python Programming"

# Slicing from index 0 to 6 (exclusive of index 6)
substring = my_string[0:6] # This gives 'Python'

print(substring) # Output: Python

In the example above, my_string[0:5] returns the first five characters of the string, my_string[:5] returns all the characters up to the fifth character, and my_string[-5:] returns the characters from the fifth-last to the last character.

Note that the first index in a slice is inclusive and the second index is exclusive. So, my_string[0:5] returns characters from index 0 to index 4, but not the character at index 5.

In addition to the two indices separated by a colon, you can also add a third index to specify the step value. Here’s an example:

# Using slicing with a step
my_string = "Python Programming"

# Extracting every second character from index 0 to index 12
substring = my_string[0:13:2] # From index 0 to 12, taking every second character

print(substring) # Output: Pto rg

String functions:

  1. `len()`: Returns the length of a string. Here’s an example:
# Using len() to get the length of a string
my_string = "Python Programming"

# Get the length of the string
length = len(my_string)

print("The length of the string is:", length) # Output: 18
  1. `lower()`: Converts all characters in a string to lowercase. Here’s an example:
# Using lower() to convert string to lowercase
my_string = "Python Programming"

# Convert the string to lowercase
lowercase_string = my_string.lower()

print("Original string:", my_string) # Output: Python Programming
print("Lowercase string:", lowercase_string) # Output: python programming
  1. `upper()`: Converts all characters in a string to uppercase. Here’s an example:
# Using upper() to convert string to uppercase
my_string = "Python Programming"

# Convert the string to uppercase
uppercase_string = my_string.upper()

print("Original string:", my_string) # Output: Python Programming
print("Uppercase string:", uppercase_string) # Output: PYTHON PROGRAMMING
  1. `title()`: Capitalizes the first character of each word in a string. Here’s an example:
# Using title() to capitalize the first character of each word
my_string = "python programming is fun"

# Convert the string to title case
title_string = my_string.title()

print("Original string:", my_string) # Output: python programming is fun
print("Title case string:", title_string) # Output: Python Programming Is Fun
  1. `capitalize()`: Capitalizes the first character of a string. Here’s an example:
# Using capitalize() to capitalize the first character of a string
my_string = "python programming"

# Capitalize the first character
capitalized_string = my_string.capitalize()

print("Original string:", my_string) # Output: python programming
print("Capitalized string:", capitalized_string) # Output: Python programming
  1. `swapcase()`: Swaps the case of all characters in a string. Here’s an example:
# Using swapcase() to swap the case of all characters in a string
my_string = "Python Programming"

# Swap the case of all characters
swapped_string = my_string.swapcase()

print("Original string:", my_string) # Output: Python Programming
print("Swapped case string:", swapped_string) # Output: pYTHON pROGRAMMING
  1. `count()`: Returns the number of occurrences of a substring in a string. Here’s an example:
# Using count() to count occurrences of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Count the occurrences of the word "Python"
count_python = my_string.count("Python")

print("Occurrences of 'Python':", count_python) # Output: 2
  1. `find()`: Returns the index of the first occurrence of a substring in a string. Here’s an example:
# Using find() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."

# Find the index of the first occurrence of "Python"
index_python = my_string.find("Python")

print("Index of 'Python':", index_python) # Output: 0
  1. `rfind()`: Returns the index of the last occurrence of a substring in a string.
# Using rfind() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Find the index of the last occurrence of "Python"
last_index_python = my_string.rfind("Python")

print("Index of the last 'Python':", last_index_python) # Output: 36

       10. `index()`: Like `find()`, but raises a `ValueError` if the substring is not found.

# Using index() to find the index of the first occurrence of a substring
my_string = "Python programming is fun."

# Find the index of the first occurrence of "Python"
index_python = my_string.index("Python")

print("Index of 'Python':", index_python) # Output: 0
  1. `rindex()`: Like `rfind()`, but raises a `ValueError` if the substring is not found.
# Using rindex() to find the index of the last occurrence of a substring
my_string = "Python programming is fun. Python is easy to learn."

# Find the index of the last occurrence of "Python"
last_index_python = my_string.rindex("Python")

print("Index of the last 'Python':", last_index_python) # Output: 36
  1. `startswith()`: Returns `True` if a string starts with a specified prefix, otherwise `False`.
# Using startswith() to check if the string starts with a specified prefix
my_string = "Python programming is fun."

# Check if the string starts with "Python"
starts_with_python = my_string.startswith("Python")

print("Starts with 'Python':", starts_with_python) # Output: True
  1. `endswith()`: Returns `True` if a string ends with a specified suffix, otherwise `False`.
# Using endswith() to check if the string ends with a specified suffix
my_string = "Python programming is fun."

# Check if the string ends with "fun."
ends_with_fun = my_string.endswith("fun.")

print("Ends with 'fun.':", ends_with_fun) # Output: True
  1. `replace()`: Replaces all occurrences of a substring with another substring.
# Using replace() to replace all occurrences of a substring
my_string = "Python is fun. Python is awesome."

# Replace "Python" with "Java"
new_string = my_string.replace("Python", "Java")

print("Original string:", my_string)
print("New string:", new_string)

       15. `strip()`: Removes whitespace (or other characters) from the beginning and end of a string.





  1. `rstrip()`: Removes whitespace (or other characters) from the end of a string.
# Using rstrip() to remove trailing whitespace
my_string = "Hello, world! "

# Remove the trailing whitespace
new_string = my_string.rstrip()

print("Original string:", repr(my_string))
print("New string:", repr(new_string))
  1. `lstrip()`: Removes whitespace (or other characters) from the beginning of a string.
# Using lstrip() to remove leading whitespace
my_string = " Hello, world!"

# Remove the leading whitespace
new_string = my_string.lstrip()

print("Original string:", repr(my_string))
print("New string:", repr(new_string))
  1. `split()`: Splits a string into a list of substrings using a specified delimiter.
# Using split() to split a string into a list of words
my_string = "Python is fun!"

# Split the string by whitespace (default behavior)
words = my_string.split()

print("List of words:", words)
  1. `rsplit()`: Splits a string from the right into a list of substrings using a specified delimiter.
# Using rsplit() to split a string from the right
my_string = "Python is fun and Python is awesome"

# Split the string by whitespace from the right
words = my_string.rsplit()

print("List of words:", words)

The separator used is the comma, which is passed as an argument to the rsplit() method. The 1 argument is used to specify that only one splitting should occur, which in this case splits the last fruit from the first two. Finally, we print the list of fruits.

       20. `join()`: Joins a list of strings into a single string using a specified delimiter.

# Joining with a space
words = ["Hello", "world", "Python", "rocks!"]
sentence = " ".join(words)
print(sentence) # Output: "Hello world Python rocks!"

# Joining with a comma
items = ["apple", "banana", "cherry"]
csv_line = ",".join(items)
print(csv_line) # Output: "apple,banana,cherry"

# Joining with a hyphen
letters = ["a", "b", "c", "d"]
hyphenated = "-".join(letters)
print(hyphenated) # Output: "a-b-c-d"
  1. `isalnum()`: Returns `True` if a string contains only alphanumeric characters, otherwise `False`.
# String with only letters and numbers
print("Hello123".isalnum()) # Output: True

# String with only letters
print("Python".isalnum()) # Output: True

# String with only numbers
print("2024".isalnum()) # Output: True

# String with a space
print("Hello World".isalnum()) # Output: False

# String with special characters
print("Hello@123".isalnum()) # Output: False

# Empty string
print("".isalnum()) # Output: False
  1. `isalpha()`: Returns `True` if a string contains only alphabetic characters, otherwise `False`.
# String with only letters
print("Python".isalpha()) # Output: True

# String with a space
print("Hello World".isalpha()) # Output: False

# String with numbers
print("Python3".isalpha()) # Output: False

# String with special characters
print("Hello!".isalpha()) # Output: False

# Empty string
print("".isalpha()) # Output: False

  1. `isdigit()`: Returns `True` if a string contains only digits, otherwise `False`.
# String with only digits
print("12345".isdigit()) # Output: True

# String with letters
print("123abc".isdigit()) # Output: False

# String with a space
print("123 456".isdigit()) # Output: False

# Empty string
print("".isdigit()) # Output: False
  1. `islower()`: Returns `True` if all characters in a string are lowercase, otherwise `False`.
# All lowercase letters
print("hello".islower()) # Output: True

# Mixed case
print("Hello".islower()) # Output: False

# Digits and special characters are ignored
print("hello123!".islower()) # Output: True

# Contains an uppercase letter
print("helloWorld".islower()) # Output: False

# Empty string
print("".islower()) # Output: False

      25. `isupper()`: Returns `True` if all characters in a string are uppercase, otherwise `False`.

# All uppercase letters
print("HELLO".isupper()) # Output: True

# Mixed case
print("Hello".isupper()) # Output: False

# Includes digits and symbols
print("HELLO123!".isupper()) # Output: True

# Contains a lowercase letter
print("HELLOworld".isupper()) # Output: False

# Empty string
print("".isupper()) # Output: False
  1. `istitle()`: Returns `True` if a string is titlecased (i.e., the first character of each word is capitalized), otherwise `False`.
# Title-cased string
print("Hello World".istitle()) # Output: True

# Mixed case
print("Hello world".istitle()) # Output: False

# Uppercase string
print("HELLO WORLD".istitle()) # Output: False

# Lowercase string
print("hello world".istitle()) # Output: False

# Single title-cased word
print("Python".istitle()) # Output: True
  1. `isspace()`: Returns `True` if a string contains only whitespace characters, otherwise `False`.
# Only spaces
print(" ".isspace()) # Output: True

# Only tabs
print("\t\t".isspace()) # Output: True

# Newline characters
print("\n\n".isspace()) # Output: True

# Mixed whitespace characters
print(" \t\n".isspace()) # Output: True

# Empty string
print("".isspace()) # Output: False
  1. `maketrans()`: Creates a translation table to be used with the `translate()` function.
# Mapping characters 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table)) # Output: "123de"
  1. `translate()`: Returns a copy of a string with specified characters replaced.
# Create a translation table to replace 'a' -> '1', 'b' -> '2', 'c' -> '3'
trans_table = str.maketrans("abc", "123")
text = "abcde"
print(text.translate(trans_table)) # Output: "123de"
  1. `zfill()`: Pads a numeric string with zeros on the left until the specified width is reached.
# Example using zfill() to pad a string with leading zeros
number = "42"
padded_number = number.zfill(5)

print(padded_number) # Output: '00042'
  1. `expandtabs()`: Replaces tabs in a string with spaces.
# Example using expandtabs() to replace tabs with spaces
text = "Hello\tWorld\tPython"
expanded_text = text.expandtabs(4) # Replaces tabs with 4 spaces

print(expanded_text) # Output: 'Hello World Python'
  1. `encode()`: Encodes a string using a specified encoding.
# Encoding a string using UTF-8
my_string = "hello world"
encoded_string = my_string.encode("utf-8")

print(encoded_string) # Output: b'hello world'

In the example above, we have a string containing the phrase “hello world”. We then use the encode() method to encode the string using the UTF-8 encoding. The resulting encoded string is a bytes object, which is denoted by the “b” prefix in the output.

  1. `format_map()`: Formats a string using a dictionary.
# Using format_map() to format a string using a dictionary
person = {"name": "Alice", "age": 30}

# Format string using the dictionary
formatted_string = "My name is {name} and I am {age} years old.".format_map(person)

print(formatted_string)
  1. `isdecimal()`: Returns `True` if a string contains only decimal characters, otherwise `False`.
# Using isdecimal() to check if a string contains only decimal characters
my_string = "12345"

# Check if the string contains only decimal characters
is_decimal = my_string.isdecimal()

print(is_decimal) # Output: True
  1. `isnumeric()`: Returns `True` if a string contains only numeric characters, otherwise `False`.
# Using isnumeric() to check if a string contains only numeric characters
my_string = "12345"

# Check if the string is numeric
is_numeric = my_string.isnumeric()

print(is_numeric) # Output: True
  1. `partition()`:It split the string into parts based on the first occurrence of the substring.
# Using partition() to split a string based on the first occurrence of a substring
my_string = "Hello, world! Welcome to Python."

# Split the string at the first occurrence of ","
result = my_string.partition(",")

print(result)

Python Loops

Python Loops Tutorial

Introduction:

Loops are a fundamental concept in programming that allow you to repeatedly execute a block of code. In Python, there are mainly two types of loops: the for loop and the while loop.

Python loop features:

  1. Iteration: Loops in Python allow for iteration, which means executing a block of code repeatedly. This is useful when you need to perform the same operation multiple times.
  2. Loop Variables: In a `for` loop, you can define a loop variable that takes on each item from a sequence or iterable in each iteration. This allows you to perform operations on each item individually.
  3. Range-based Loops: Python provides the `range()` function, which generates a sequence of numbers that can be used with loops. It allows you to specify the start, end, and step size for the sequence.
  4. Loop Control Statements: Python loops offer control statements such as `break`, `continue`, and `pass` to modify the loop’s behavior.

    – `break` terminates the loop prematurely, and control transfers to the next statement outside the loop.

   – `continue` skips the remaining code in the current iteration and moves on to the next iteration.

   – `pass` is a placeholder statement that does nothing. It can be used when a statement is required syntactically, but you want to skip its execution.

  1. Nested Loops: Python allows nesting loops, meaning you can have loops within loops. This is useful for performing complex iterations or dealing with multi-dimensional data structures.
  2. While Loops: In addition to `for` loops, Python also supports `while` loops. While loops continue to execute a block of code as long as a given condition is true.
  3. Flexibility: Python loops provide flexibility and versatility in controlling the flow of execution. You can incorporate conditional statements, iterate over various data structures, and control the loop’s behavior using control statements.

Python loop advantages:

  1. Code Reusability: Loops allow you to write reusable code by performing repetitive tasks or operations on multiple elements or data. Instead of writing the same code multiple times, you can encapsulate it within a loop and iterate over the desired elements.
  2. Efficient Data Processing: Loops enable you to process large amounts of data or perform computations on collections of elements. By iterating over data structures like lists, tuples, or dictionaries, you can access and manipulate each item individually.
  3. Automation: Loops are essential for automating tasks and actions that need to be performed repeatedly. You can automate processes such as data parsing, file handling, or web scraping by utilizing loops to iterate over data sources or execute a series of actions.
  4. Dynamic Iteration: Python loops allow for dynamic iteration, where the number of iterations is determined during runtime. For example, you can use loops to iterate over a user-provided range of values or until a specific condition is met. This flexibility makes Python loops adaptable to various scenarios.
  5. Nested Looping: Python supports nested loops, allowing you to iterate over multiple dimensions or levels of data structures. This capability is useful when working with multi-dimensional arrays, matrices, or nested lists, as it allows you to process each element in a structured and organized manner.
  6. Control Flow: Python loops provide control flow statements such as `break`, `continue`, and `pass`. These statements offer greater control over the loop’s behavior and allow you to alter the normal flow of execution based on specific conditions. This flexibility enhances the efficiency and effectiveness of your code.
  7. Readability and Maintainability: Python’s syntax and indentation structure contribute to the readability and maintainability of loops. The clear and concise syntax makes it easier to understand and debug code that involves loops. Additionally, loops can be easily modified or extended, making them more maintainable in the long run.

Python loop disadvantages:

  1. Performance Impact: Depending on the complexity of the loop and the number of iterations, Python loops can sometimes be slower compared to other approaches such as vectorized operations or using built-in functions like `map()` or `filter()`. This can impact performance when dealing with large datasets or computationally intensive tasks.
  2. Nested Loops and Complexity: Nested loops, while providing flexibility, can result in increased code complexity. Managing multiple levels of iteration can make the code harder to read, understand, and maintain. It may also lead to potential bugs or errors, especially when dealing with larger nested loops.
  3. Inefficient Iteration over Large Data: When iterating over large data structures, such as lists or dictionaries, Python loops may not be the most efficient option. Certain operations like appending to a list within a loop can result in quadratic time complexity, leading to slower execution.
  4. Lack of Parallelization: Python loops typically execute sequentially, one iteration after another. This means they do not naturally lend themselves to parallelization or taking advantage of multiple processor cores. For computationally intensive tasks, parallelizing the code using techniques like multiprocessing or concurrent programming may be more efficient.
  5. Infinite Loop Possibility: In `while` loops, there is a risk of accidentally creating an infinite loop if the exit condition is not correctly defined or updated within the loop. This can lead to program freezing or consuming excessive resources.
  6. Code Duplication: Loops can sometimes lead to code duplication, especially if similar loop structures are used in different parts of the codebase. This duplication can make code maintenance more challenging, as changes or bug fixes may need to be applied to multiple sections.
  7. Readability Challenges: Complex loop structures or deeply nested loops may reduce code readability, particularly for those who are less familiar with Python or the specific codebase. It is important to strike a balance between using loops for efficiency and maintaining code clarity.

Python loop types:

  1. For loop: A `for` loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. It executes a set of statements for each item in the sequence. Here’s the syntax of a `for` loop in Python:




The loop variable (`item` in the example) takes on each item from the sequence in each iteration, allowing you to perform operations on it. The loop continues until all items in the sequence have been processed. Here’s an example of a `for` loop that prints each element in a list:





  1. While loop: A `while` loop is used to repeatedly execute a block of code as long as a certain condition is true. It continues iterating until the condition becomes false. Here’s the syntax of a `while` loop in Python:




The loop checks the condition before each iteration. If the condition is true, the code block is executed. The loop continues until the condition evaluates to false. Here’s an example of a `while` loop that prints numbers from 1 to 5:





In this example, the loop continues as long as the value of `count` is less than or equal to 5. The variable ‘count’ is incremented by 1 in each iteration.

Python loop control statement:

  1. Break statement: The `break` statement is used to exit a loop prematurely. When encountered inside a loop, the `break` statement immediately terminates the loop and transfers control to the next statement outside the loop. Here’s an example that uses a `break` statement to stop a loop when a certain condition is met:




In this example, the loop iterates over the `numbers` list. When the value of `value ` becomes 4, the `break` statement is encountered, causing the loop to terminate immediately.

  1. Continue statement: The `continue` statement is used to skip the remaining code inside a loop for the current iteration and move on to the next iteration. It allows you to bypass certain iterations based on a condition. Here’s an example that uses a `continue` statement to skip printing even numbers:




In this example, the loop iterates over the `numbers` list. When an even number is encountered (`value % 2 == 0`), the `continue` statement is executed, and the remaining code inside the loop is skipped for that iteration.

  1. Pass statement: The `pass` statement is a placeholder statement that does nothing. It is used when a statement is syntactically required, but you want to skip its execution. It can be used inside loops to create empty loops or as a placeholder for future code. Here’s an example that uses a `pass` statement inside a loop:




In this example, the loop iterates five times, but since there is no code inside the loop, it effectively does nothing.

These loop control statements provide flexibility and control over the execution flow within loops. They help in handling specific conditions or terminating loops when necessary.

Conditional statement with python loops:

  1. For loop – We can use conditional statements within a Python `for` loop to perform different actions based on specific conditions. Here’s an example:




In this example, we have a list of fruits. Within the `for` loop, we use conditional statements (`if`, `elif`, and `else`) to check the value of each `fruit` variable.

– If the `fruit` is ‘banana’, it will print “I like bananas!”.

– If the `fruit` is ‘apple’, it will print “Apples are my favorite”.

– For any other fruit, it will print “I enjoy eating” followed by the name of the fruit.

The `if` statement checks if the condition is true, and if it is, the corresponding code block is executed. The `elif` statement allows for additional conditions to be checked, and the `else` statement provides a default action when none of the previous conditions are true.

  1. While loop – We can use conditional statements within a Python `while` loop to control the loop’s execution based on specific conditions. Here’s an example:




In this example, we have a `while` loop that continues until the `count` variable reaches 6. Within the loop, we use a conditional statement (`if`) to check if the `count` is equal to 2.

– If the `count` is 2, it will print “Skipping count 2”, and then use the `continue` statement to skip the remaining code in the loop for that iteration and move on to the next iteration.

– For any other value of `count`, it will print “Current count:” followed by the value of `count`.

By updating the value of `count` within the loop, we ensure that the loop eventually terminates when the condition `count <= 5` becomes false.

Python DataTypes

Introduction :

In Python, every value has a specific data type associated with it. Data types define the nature of the variables, objects, or values you can work with in your code. Understanding different data types is crucial for effective programming. Let’s explore the commonly used data types in Python.

Numeric Types:

  • Integer (int): Represents whole numbers without decimal points.

In Python, the integer data type (int) represents whole numbers without any decimal points. Integers can be positive or negative, and they have no limit on their size, allowing you to work with both small and large numbers.

Example:

num1 = 10
  • Floating-Point (float): Represents decimal numbers.

In Python, the float data type represents decimal numbers. Floats are used to represent real numbers, including both positive and negative values. Unlike integers, floats can have decimal points and can represent numbers with fractional parts.

Example:

num2 = 3.14
  • Complex (complex): Represents numbers with real and imaginary parts.

In Python, the complex data type represents numbers with both real and imaginary parts. Complex numbers are often used in mathematical and scientific computations that involve complex arithmetic operations.

Example:

num3 = 4 + 5j

Sequence Types:

  • String (str): Represents a sequence of characters enclosed in quotes.

In Python, a string is a sequence of characters enclosed in single quotes (‘ ‘) or double quotes (” “). Strings are immutable, which means once created, they cannot be modified. However, you can create new strings based on existing ones.

In Python, a string is a sequence of characters enclosed in single quotes (‘ ‘) or double quotes (” “). Strings are immutable, which means once created, they cannot be modified. However, you can create new strings based on existing ones.

Example:

name = "John"
  • List (list): Represents an ordered collection of items enclosed in square brackets.

In Python, a list is a versatile and mutable data type that represents an ordered collection of items. Lists can contain elements of different data types, such as numbers, strings, or even other lists. Lists are denoted by square brackets [ ].

Example:

numbers = [1, 2, 3, 4, 5]
  • Tuple (tuple): Represents an ordered collection of items enclosed in parentheses.

In Python, a tuple is an ordered collection of elements, similar to a list. However, unlike lists, tuples are immutable, meaning they cannot be modified once created. Tuples are typically denoted by parentheses ( ) or can be created without any delimiters.

Example:

coordinates = (10, 20)

Dictionary (dict):

Represents a collection of key-value pairs enclosed in curly braces.

In Python, a dictionary is an unordered collection of key-value pairs. It is also known as an associative array or a hash map. Dictionaries are enclosed in curly braces { }, and each item in the dictionary is represented as a key-value pair separated by a colon (:).

Example:

person = {"name": "John", "age": 25, "city": "New York"}

Set Types:

Set (set): Represents an unordered collection of unique items enclosed in curly braces.

In Python, a set is an unordered collection of unique elements. Sets are denoted by curly braces { }. Each element in a set must be unique, and duplicate values are automatically removed. Sets are mutable, meaning you can modify them after creation.

Example:

fruits = {"apple", "banana", "orange"}

Boolean Type:

Boolean (bool): Represents either True or False.

In Python, the Boolean data type represents truth values. A Boolean value can be either True or False. Booleans are often used for logical operations and comparisons.

In Python, the keywords True and False (with the first letter capitalized) are used to represent Boolean values.

Example:

is_active = True
is_admin = False

Datatype Conversion:

Below is a table that demonstrates the conversion of various Python data types into other data types. Each entry in the table includes the original data type, the target data type, a code snippet to perform the conversion, and an example output.

Integer(int) : Convert int Data Type to all other Data Type.

Data TypeTarget Data TypeCodeOutput


int

floatnum_int = 10  

num_float = float(num_int)
10.0


int

strnum_int = 42

num_str = str(num_int)
’42’


int

complexnum_int = 5  

num_complex = complex(num_int)
(5+0j)


int

listnum_int = 123  

num_list = list(num_int)
TypeError: ‘int’ object is not iterable  
Conversion is not possible


int

dictnum_int = 1  

num_dict = dict(num_int)
TypeError: ‘int’ object is not iterable
Conversion is not possible


int

tuplenum_int = 7  

num_tuple = tuple(num_int)
TypeError: ‘int’ object is not iterable
Conversion is not possible
intboolnum_int = 0
num_bool = bool(num_int)
print(num_bool)  

num_int1 = 123
num_bool1 = bool(num_int1)
print(num_bool1)
False


True


Float: Convert Float Data Type to all other Data Type.

Data Type Target Data Type Code Output
floatintnum_float = 10.5  

num_int = int(num_float)
10
float

str

num_float = 3.14  

num_str = str(num_float)
‘3.14’
float

complex

num_float = 3.0  
num_complex = complex(num_float,4.5)
(3+4.5j)
float
list

num_float = 3.14  
num_list = list(num_float)
TypeError: ‘int’ object is not iterable   Conversion is not possible
float
dict

num_float = 2.5  
num_dict = dict(num_float)
TypeError: ‘int’ object is not iterable   Conversion is not possible
floattuple
num_float = 1.5  
num_tuple = float(num_float)
TypeError: ‘int’ object is not iterable   Conversion is not possible
floatboolnum_int = 0
num_bool = bool(num_int)
print(num_bool)  

num_int1 = 12.3
num_bool1 = bool(num_int1)
print(num_bool1)
False


True

Complex : Convert complex data type to all other data type.

Data Type Target Data TypeCodeOutput
complexintnum_complex = complex(3, 4)
 
num_int = int(num_complex)

TypeError: int() argument must be a string, a bytes-like object or a real number, not ‘complex’   Conversion is not possible.
complexfloat
i).
num_complex = complex(3, 4)
num_float = float(num_complex)


ii).
num_complex = complex(3, 4)
num_float = float(num_complex.real)
i).TypeError: float() argument must be a string or a real number, not ‘complex’   Conversion is not possible.



ii).  3
complexstr

num_complex = complex(1, 2)<br>num_str = str(num_complex)

‘(1+2j)’
complexlist
num_complex = complex(2, 3)

num_list = [num_complex.real, num_complex.imag]
[2.0, 3.0]
complexdict
num_complex = complex(2, 1)  

num_dict = {‘real’: num_complex.real, ‘imag’: num_complex.imag}
{‘real’: 2.0, ‘imag’: 1.0}
complextuple
num_complex = complex(4, 5)

num_tuple = (num_complex.real, num_complex.imag)
(4.0, 5.0)
complexbool
num_complex = complex(0, 0)  

num_bool = bool(num_complex)
False

String(str) : Convert str data type to all other data type.

Data TypeTarget Data TypeCodeOutput

str
int
num_str = ‘987’  

num_int = int(num_str)
987

str
float
num_str = ‘2.71’  

num_float = float(num_str)
2.71

str
complex
num_str = ‘1+2j’  

num_complex = complex(num_str)
(1+2j)

str
list
str_val = ‘hello’  

list_val = list(str_val)
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

str
dict
str_val = ‘hello’  

dict_val = {str_val: len(str_val)}
{‘hello’: 5}

str
tuple
str_val = ‘abc’  

tuple_val = tuple(str_val)
(‘a’, ‘b’, ‘c’)

str
bool
str_val = ‘True’  

bool_val = bool(str_val)
True

List(list) : Convert list data type to all other data type.

Data TypeTarget Data Type CodeOutput
listint
num_list = [1, 2, 3]  

num_int = int(”.join(map(str, num_list)))
123
listfloat
num_list = [3, 1, 4]  

num_float = float(”.join(map(str, num_list)))
314.0
liststr
num_list = [10, 20, 30]  

num_str = ‘, ‘.join(map(str, num_list))
’10, 20, 30′
listcomplex
num_list = [2, 3]  

num_complex = complex(num_list[0], num_list[1])
(2+3j)
listdict
num_list = [1, 2]  

num_dict = dict(zip(num_list, [‘one’, ‘two’]))
{1: ‘one’, 2: ‘two’}
listtuple
num_list = [7, 8, 9]  

num_tuple = tuple(num_list)
(7, 8, 9)
listbool
num_list = [0, 1, 0]  

num_bool = any(num_list)
True

Tuple(tuple) : Convert tuple data type to all other data type.

Data Type Target Data Type Code Output
tupleint
num_tuple = (4, 5, 6)  

num_int = int(”.join(map(str, num_tuple)))
456
tuplefloat
num_tuple = (1, 2)  

num_float = float(‘.’.join(map(str, num_tuple)))
1.2
tuplestr
num_tuple = (7, 8, 9)  

num_str = ‘, ‘.join(map(str, num_tuple))
‘7, 8, 9’
tuplecomplex
num_tuple = (3, 4)  

num_complex = complex(num_tuple[0], num_tuple[1])
(3+4j)
tuplelist
num_tuple = (10, 20)  

num_list = list(num_tuple)
[10, 20]
tupledict
num_tuple = (‘x’, 1)  

num_dict = dict([num_tuple])
{‘x’: 1}
tuplebool
num_tuple = (0, 0)  

num_bool = any(num_tuple)
False

Dictionary(dict) : Convert dict data type to all other data type.

Data Type Target Data Type Code Output
ictint
num_dict = {‘a’: 1}  

num_int = int(list(num_dict.keys())[0])
97
dictfloat
num_dict = {‘pi’: 3.14}  

num_float = float(list(num_dict.values())[0])
3.14
dictstr
num_dict = {1: ‘one’}  

num_str = str(list(num_dict.keys())[0])
‘1’
dictcomplex
num_dict = {3: 5}
 
num_complex = complex(list(num_dict.keys())[0], list(num_dict.values())[0])
(3+5j)
dictlist
num_dict = {‘a’: 1, ‘b’: 2}  

num_list = list(num_dict.items())
[(‘a’, 1), (‘b’, 2)]
dicttuple
num_dict = {‘x’: 10, ‘y’: 20}  

num_tuple = tuple(num_dict.items())
((‘x’, 10), (‘y’, 20))
dictbool
num_dict = {‘flag’: True}  

num_bool = bool(list(num_dict.values())[0])
True

Set : Convert set data type to all other data type.

Data Type Target Data Type CodeOutput
setint
num_set = {1, 2, 3}  

num_int = int(”.join(map(str, num_set)))
123
setfloat
num_set = {3, 1, 4}  

num_float = float(”.join(map(str, num_set)))
314.0
setstr
num_set = {10, 20, 30}  

num_str = ‘, ‘.join(map(str, num_set))
’10, 20, 30′
setcomplex
num_set = {2, 3}  

num_complex = complex(list(num_set)[0], list(num_set)[1])
(2+3j)
setlist
num_set = {1, 2, 3}  

num_list = list(num_set)
[1, 2, 3]
setdict
num_set = {1, 2, 3}  

num_dict = dict.fromkeys(num_set, ‘value’)
{1: ‘value’, 2: ‘value’, 3: ‘value’}
settuple
num_set = {7, 8, 9)  

num_tuple = tuple(num_set)
(8, 9, 7)
setbool
num_set = set()  

num_bool = bool(num_set)
False

Boolean(bool) : Convert bool data type to all other data type.

Data TypeTarget Data Type CodeOutput
boolint
num_bool = False  

num_int = int(num_bool)
0
boolfloat
num_bool = True  

num_float = float(num_bool)
1.0
boolstr
num_bool = True  

num_str = str(num_bool)
‘True
boolcomplex
num_bool = True  

num_complex = complex(int(num_bool), 0)
(1+0j)
boollist
num_bool = False  

num_list = [int(num_bool)]
[0]
booldict
num_bool = True  

num_dict = {str(num_bool): ‘boolean’}
{‘True’: ‘boolean’}
booltuple
num_bool = False  

num_tuple = (int(num_bool),)
(0,)

Python String Programs, Exercises, Examples

Python string is a sequence of characters, such as “hello”. They can be used to represent text in a programming language. Strings can be created by enclosing a sequence of characters between double quotes, such as “hello”, or by using the str() function.

1). Write a Python program to get a string made of the first and the last 2 chars from a given string. If the string length is less than 2, return instead of the empty string

2). Python string program that takes a list of strings and returns the length of the longest string.

3). Python string program to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2).

4). Python string program to reverse a string if it’s length is a multiple of 4.

5). Python string program to count occurrences of a substring in a string.

6). Python string program to test whether a passed letter is a vowel or consonant.

7). Find the longest and smallest word in the input string.

8). Print most simultaneously repeated characters in the input string.

9). Write a Python program to calculate the length of a string with loop logic.

10). Write a Python program to replace the second occurrence of any char with the special character $.
Input = “Programming”
Output = “Prog$am$in$”

11). Write a python program to get to swap the last character of a given string.
Input = “SqaTool”
Output = “IqaTooS”

12). Write a python program to exchange the first and last character of each word from the given string.
Input = “Its Online Learning”
Output = “stI enlino gearninL”

13). Write a python to count vowels from each word in the given string show as dictionary output.
Input = “We are Learning Python Codding”
output = {“We” : 1, “are” : 2, “Learning” : 3, “Python”:1, “Codding”}

14). Write a python to repeat vowels 3 times and consonants 2 times.
Input = “Sqa Tools Learning”
Ouput = “SSqqaaa TToooooollss LLeeeaaarrnniiinngg”

15). Write a python program to re-arrange the string.
Input = “Cricket Plays Virat”
Output = “Virat Plays Cricket”

16). Write a python program to get all the digits from the given string.
Input = “””
Sinak’s 1112 aim is to 1773 create a new generation of people who
understand 444 that an organization’s 5324 success or failure is
based on 555 leadership excellence and not managerial
acumen
“””
Output = [1112, 5324, 1773, 5324, 555]

17). Write a python program to replace the words “Java” with “Python” in the given string.
Input = “JAVA is the Best Programming Language in the Market”
Output = “Python is the Best Programming Language in the Market”

18). Write a Python program to get all the palindrome words from the string.
Input = “Python efe language aakaa hellolleh”
output = [“efe”, “aakaa”, “hellolleh”]

19). Write a Python program to create a string with a given list of words.
Input = [“There”, “are”, “Many”, “Programming”, “Language”]
Output = There are many programming languages.

20). Write a Python program to remove duplicate words from the string.
Input = “John jany sabi row john sabi”
output = “John jany sabi row”

21). Write a Python to remove unwanted characters from the given string.
Input = “Prog^ra*m#ming”
Output = “Programming”

Input = “Py(th)#@&on Pro$*#gram”
Output = “PythonProgram”

22). Write a Python program to find the longest capital letter word from the string.
Input = “Learning PYTHON programming is FUN”
Output = “PYTHON”

23). Write a Python program to get common words from strings.
Input String1 = “Very Good Morning, How are You”
Input String1 = “You are a Good student, keep it up”
Output = “You Good are”

24). Write a Python program to find the smallest and largest word in a given string.
Input = “Learning is a part of life and we strive”
Output = “a”, “Learning”

25). Check whether the given string is a palindrome (similar) or not.
Input= sqatoolssqatools
Output= Given string is not a palindrome

26). Write a program using python to reverse the words in a string.
Input= sqatools python
Output= slootaqs

27). Write a program to calculate the length of a string.
Input= “python”
Output = 6

28). Write a program to calculate the frequency of each character in a string.
Input = “sqatools”
Output = {‘s’:2, ‘q’:1, ‘a’: 1, ‘t’:1,‘o’:2, ‘l’:1, ‘s’:1}

29). Write a program to combine two strings into one.
Input: 
A = ’abc’
B = ’def’
Output = abcdef

30). Write a program to print characters at even places in a string.
Input = ‘sqatools’
Output = saol

31). Write a program to check if a string has a number or not.
Input = ‘python1’
Output = ‘Given string have a number’

32). Write a python program to count the number of vowels in a string.
Input= ‘I am learning python’
Output= 6

33). Write a python program to count the number of consonants in a string.
Input= ‘sqltools’
Output= 6

34). Write a program to print characters at odd places in a string.
Input = ‘abcdefg’
Output = ‘bdf’

35). Write a program to remove all duplicate characters from a given string in python.
Input = ‘sqatools’
Output = ‘sqatol’

36). Write a program to check if a string has a special character or not
Input = ‘python$$#sqatools’
Output =  ‘Given string has special characters

37). Write a program to exchange the first and last letters of the string
Input = We are learning python
Output = ne are learning pythoW

38). Write a program to convert all the characters in a string to Upper Case.
Input = ‘I live in pune’
Output = ‘I LIVE IN PUNE’

39). Write a program to remove a new line from a string using python.
Input = ‘objectorientedprogramming\n’
Output = ‘Objectorientedprogramming’

40). Write a python program to split and join a string
Input =‘Hello world’
Output = [‘Hello’, ‘world’]
                 Hello-world

41). Write a program to print floating numbers up to 3 decimal places and convert it to string.
Input = 2.14652
Output= 2.146

42). Write a program to convert numeric words to numbers.
Input = ‘five four three two one’
Output = 54321

43). Write a python program to find the location of a word in a string
Input Word = ‘problems’
Input string = ‘ I am solving problems based on strings’
Output = 4

44). Write a program to count occurrences of a word in a string.

Word = ‘food’
Input str = ‘ I want to eat fast food’
Occurrences output= 1

Word = ‘are’
Input str = “We are learning Python, wow are you”
Occurrences output = 2 

45). Write a python program to find the least frequent character in a string.
Input =  ‘abcdabdggfhf’
Output = ‘c’

46). Find the words greater than the given length.
Ex length = 3
Input = ‘We are learning python’
Output – ‘learning python’

47). Write a program to get the first 4 characters of a string.
Input = ‘Sqatools’
Output = ‘sqat’

48). Write a Python program to get a string made of the first 2 and the last 2 chars from a given string.
Input = ‘Sqatools’
Output = ‘Sqls’ 

49). Write a python program to print the mirror image of the string.
Input = ‘Python’
Output = ‘nohtyp 

50). Write a python program to split strings on vowels
Input = ‘qwerty’
Output = ‘qw rty’

51). Write a python program to replace multiple words with certain words.
Input = “I’m learning python at Sqatools”
Replace python with SQA  and sqatools with TOOLS 
Output = “I’m learning SQA at TOOLS “

52). Write a python program to replace different characters in the string at once.
Input = ‘Sqatool python’
Replace a with 1,
Replace t with 2,
Replace o with 3
Output = ‘sq1233l py2h3n”

53). Write a python program to remove empty spaces from a list of strings.
Input = [‘Python’, ‘ ‘, ‘ ‘, ‘sqatools’]
Output = [‘Python’, ‘sqatools’] 

54).  Write a python program to remove punctuations from a string
Input = ‘Sqatools : is best, for python’
Output = ‘Sqatools is best for python’

55).  Write a python program to find duplicate characters in a string
Input = “hello world”
Output = ‘lo’

56).  Write a python program to check whether the string is a subset of another string or not
Input str1 = “iamlearningpythonatsqatools”
str = ‘pystlmi’
Output = True

57). Write a python program to sort a string
Input = ‘xyabkmp’
Output = ‘abkmpxy’

58). Write a python program to generate a random binary string of a given length.
Input = 8
Output = 10001001

59). Write a python program to check if the substring is present in the string or not
Input string= ‘I live in Pune’
Substring= ‘I live ‘
Output = ‘Yes

60). Write a program to find all substring frequencies in a string.
Input str1 = “abab” 
Output = {‘a’: 2, ‘ab’: 2, ‘aba’: 1,‘abab’: 1, ‘b’: 2, ‘ba’: 1, ‘bab’: 1}  

61). Write a python program to print the index of the character in a string.
Input = ‘Sqatools’
Output = ‘The index of q is 1’

62). Write a program to strip spaces from a string.
Input = ‘    sqaltoolspythonfun     ‘ 
Output = ‘ sqaltoolspythonfun’

63). Write a program to check whether a string contains all letters of the alphabet or not.
Input = ‘abcdgjksoug’
Output = False

64). Write a python program to convert a string into a list of words.
Input = ‘learning python is fun’
Output = [learning, python, is, fun] 

65). Write a python program to swap commas and dots in a string.
Input = sqa,tools.python
Output = sqa.tools,python

66). Write a python program to count and display the vowels in a string
Input = ‘welcome to Sqatools’
Output = 7

67). Write a Python program to split a string on the last occurrence of the delimiter. 
Input = ‘l,e,a,r,n,I,n,g,p,y,t,h,o,n’
Output = [‘l,e,a,r,n,I,n,g,p,y,t,h,o ‘ ,’n’]

68). Write a Python program to find the first repeated word in a given string. 
Input = ‘ab bc ca ab bd’
Output = ‘ab’

69). Write a program to find the second most repeated word in a given string using python.
Input = ‘ab bc ac ab bd ac nk hj ac’
Output = (‘ab’, 2)

70). Write a Python program to remove spaces from a given string.
Input = ‘python at sqatools’
Output = ‘pythonatsqatools’

71). Write a Python program to capitalize the first and last letters of each word of a given string.
Input = ‘this is my first program’
Output = ‘ThiS IS MY FirsT PrograM’

72). Write a Python program to calculate the sum of digits of a given string.
Input = ’12sqatools78′
Output = 18

73). Write a Python program to remove zeros from an IP address. 
Input = 289.03.02.054
Output = 289.3.2.54

74). Write a program to find the maximum length of consecutive 0’s in a given binary string using python.
Input = 10001100000111
Output = 5 

75). Write a program to remove all consecutive duplicates of a given string using python.
Input = ‘xxxxyy’
Output = ‘xy’

76). Write a program to create strings from a given string. Create a string that consists of multi-time occurring characters in the said string using python.
Input = “aabbcceffgh”
Output = ‘abcf’

77). Write a Python program to create a string from two given strings combining uncommon characters of the said strings.  

Input string :
s1 = ‘abcdefg’
s2 = ‘xyzabcd’
Output string : ‘efgxyz’

78). Write a Python code to remove all characters except the given character in a string. 
Input = “Sqatools python”
Remove all characters except S
Output = ‘S’

79). Write a program to count all the Uppercase, Lowercase, special character and numeric values in a given string using python.
Input = ‘@SqaTools.lin’
Output:
Special characters: 1
Uppercase characters: 2
Lowercase characters: 8

80). Write a Python program to count a number of non-empty substrings of a given string.
Input a string = ‘sqatools12’
Number of substrings = 55

81). Write a program to remove unwanted characters from a given string using python.
Input = ‘sqa****too^^{ls’
Output = ‘Sqatools’

82). Write a program to find the string similarity between two given strings using python.
Input
Str1 = ‘Learning is fun in Sqatools’
Str2 = ‘Sqatools Online Learning Platform’

Output :
Similarity : 0.4

83). Write a program to extract numbers from a given string using python.
Input = ‘python 456 self learning 89’
Output = [456, 89]

84). Write a program to split a given multiline string into a list of lines using python.
Input =”’This string Contains
Multiple
Lines”’
Output = [‘This string Contains’, ‘Multiple’, ‘Lines’]

85). Write a program to add two strings as they are numbers using python.
Input :
a=’3′, b=’7′
Output  = ’10’

86). Write a program to extract name from a given email address using python.
Input = ‘student1@gmail.com’
Output = ‘student’

87). Write a  program that counts the number of leap years within the range of years using python. The range of years should be accepted as a string. 

(“1981-2001)  =  Total leap year 5

88). Write a program to insert space before every capital letter appears in a given word using python. 
Input = ‘SqaTools pyThon’
Output = ‘ Sqa Tools py Thon’ 

89). Write a program to uppercase half string using python.
Input = ‘banana’
Output = ‘banANA’

90). Write a program to split and join a string using “-“.
Input = ‘Sqatools is best’
Output = ‘Sqatools-is-best’

91). Write a python program to find permutations of a given string using in built function.
Input  = ‘CDE’
Output = [‘CDE’, ‘CED’ ‘EDC’, ‘ECD’, ‘DCE’, ‘DEC’]

92). Write a program to avoid spaces in string and get the total length
Input = ‘sqatools is best for learning python’
Output = 31

93). Write a program to accept a string that contains only vowels
Input = ‘python’
Output- ‘not accepted’

Input = ‘aaieou’
Output = ‘accepted’

94). Write a program to remove the kth element from the string
K=2
Input = ‘sqatools’
Output = ‘sqtools’

95). Write a program to check if a given string is binary or not.
Hint: Binary numbers only contain 0 or 1.

Input = ‘01011100’
Output = yes

Input = ‘sqatools 100’
Output = ‘No’

96). Write a program to add ‘ing’ at the end of the string using python.
Input = ‘xyz’
Output = ‘xyzing’

97). Write a program to add ly at the end of the string if the given string ends with ing.
Input = ‘winning’
Output = ‘winningly’

98). Write a program to reverse words in a string using python.
Input = ‘string problems’
Output = ‘problems string’

99). Write a program to print the index of each character in a string.
Input =  ‘sqatools’
Output :
Index of s is 0
Index of q is 1
Index of a is 2
Index of t is 3
Index of o is 4
Index of o is 5
Index of l is 6
Index of s is 7

100). Write a program to find the first repeated character in a string and its index.
Input = ‘sqatools’
Output = (s,0)

101). Write a program to swap cases of a given string using python.
Input = ‘Learning Python’
Output = ‘lEARNING pYTHON’

102). Write a program to remove repeated characters in a string and replace it with a single letter using python.
Input = ‘aabbccdd’
Output = ‘cabd’

103). Write a program to print a string 3 times using python.
Input = ‘sqatools’
Output = ‘sqatoolssqatoolssqatools’

104). Write a program to print each character on a new line using python.
Input = ‘python’
Output:
p
y
t
h
o
n

105). Write a program to get all the email id’s from given string using python.
Input str = “”” We have some employee whos john@gmail.com email id’s are randomly distributed jay@lic.com we want to get hari@facebook.com all the email mery@hotmail.com id’s from this given string.”””
Output = [‘john@gmail.com’, ‘ jay@lic.com’, ‘hari@facebook.com’, ‘mery@hotmail.com’ ]

106). Write a program to get a list of all the mobile numbers from the given string using python.
Input str = “”” We have 2233 some employee 8988858683 whos 3455 mobile numbers are randomly distributed 2312245566 we want 453452 to get 4532892234 all the mobile numbers 9999234355  from this given string.”””
Output = [‘8988858683’, ‘2312245566’, ‘4532892234’, ‘9999234355’]

Python Tuple Practice Programs, Exercises

Python tuple practice programs help students to improve their logic building.

1). Python tuple program to create a tuple with 2 lists of data.
Input lists:
list1 = [4, 6, 8]
list2 = [7, 1, 4]
Output= ((4, 7), (6, 1), (8, 4))

2). Python tuple program to find the maximum value from a tuple.
Input = (41, 15, 69, 55)
Output = 69

3). Python tuple program to find the minimum value from a tuple.
Input = (36,5,79,25)
Output = 5

4). Python tuple program to create a list of tuples from a list having a number and its square in each tuple.
Input = [4,6,3,8]
Output = [ (4, 16), (6, 36), (3, 27), (8, 64) ]

5). Python tuple program to create a tuple with different datatypes.
Output= ( 2.6, 1, ‘Python’, True, [5, 6, 7], (5, 1, 4), {‘a’: 123, ‘b’: 456})

6). Python tuple program to create a tuple and find an element from it by its index no.
Input = (4, 8, 9, 1)
Index = 2
Output = 9

7). Python tuple program to assign values of tuples to several variables and print them.
Input = (6,7,3)
Variables = a,b,c
Output:
a, 6
b, 7
c, 3

8). Python tuple program to add an item to a tuple.
Input= ( 18, 65, 3, 45)
Output=(18, 65, 3, 45, 15)

9). Python tuple program to convert a tuple into a string.
Input = (‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’, ‘l’, ‘s’)
Output = Sqatools

10). Python tuple program to get the 2nd element from the front and the 3rd element from the back of the tuple.
Input = (‘s’, ‘q’, ‘a’, ‘t’, ‘o’, ‘o’ ,’l’, ‘s’)
Output=
q
o

11). Python tuple program to check whether an element exists in a tuple or not.
Input = ( ‘p’ ,’y’, ‘t’, ‘h’, ‘o’, ‘n’)
P in A
Output=
True

12). Python tuple program to add a list in the tuple.
Input:
L=[12,67]
A=(6,8,4)
Output:
A=(6,8,4,12,67)

13). Python tuple program to find sum of elements in a tuple.
Input:
A=(4,6,2)
Output:
12

14). Python tuple program to add row-wise elements in Tuple Matrix
Input:
A = [[(‘sqa’, 4)], [(‘tools’, 8)]]
B = (3,6)
Output:
[[(‘sqa’, 4,3)], [(‘tools’, 8,6)]]

15). Python tuple program to create a tuple having squares of the elements from the list.
Input = [1, 9, 5,  7, 6]
Output = (1, 81, 25, 49, 36)

16). Python tuple program to multiply adjacent elements of a tuple.
Input = (1,2,3,4)
Output =  (2,6,12)

17). Python tuple program to join tuples if the initial elements of the sub-tuple are the same.
Input:
[(3,6,7),(7,8,4),(7,3),(3,0,5)]
Output:
[(3,6,7,0,5),(7,8,4,3)]

18). Python tuple program to convert a list into a tuple and multiply each element by 2.
Input = [12,65,34,77]
Output = (24, 130, 68, 154)

19). Python tuple program to remove an item from a tuple.
Input:
A=(p,y,t,h,o,n)
Output: (p,y,t,o,n)

20). Python tuple program to slice a tuple.
Input:
A=(5,7,3,4,9,0,2)
Output:
(5,7,3)
(3,4,9)

21). Python tuple program to find an index of an element in a tuple.
Input:
A=(s,q,a,t,o,o,l,s)
Index of a?
Output = 2

22). Python tuple program to find the length of a tuple.
Input:
A=(v,i,r,a,t)
Output=
5

23). Python tuple program to convert a tuple into a dictionary.
Input:
A=((5,s),(6,l))
Output = { s: 5, l: 6 }

24). Python tuple program to reverse a tuple.
Input = ( 4, 6, 8, 3, 1)
Output= (1, 3, 8, 6, 4)

25). Python tuple program to convert a list of tuples in a dictionary.
Input = [ (s, 2), (q, 1), (a, 1), (s, 3), (q, 2), (a, 4) ]
Output ={ s: [ 2, 3 ], q: [ 1, 2 ], a: [ 1 ,4 ] }

26). Python tuple program to pair all combinations of 2 tuples.
Input :
A=(2,6)
B=(3,4)
Output
[ (2, 3), (2, 4), (6, 3), (6, 4), (3, 2), (3, 6), (4, 2), (4, 6) ]

27). Python tuple program to remove tuples of length i.
Input = [ (2, 5, 7), (3, 4), ( 8, 9, 0, 5) ]
i=2
Output= [ (2, 5, 7), ( 8, 9, 0, 5) ]

28). Python tuple program to remove tuples from the List having an element as None.
Input = [(None, 2), (None, None), (5, 4), (1,6,7)]
Output= { (5, 4), (1, 6, 7) }

29). Python tuple program to remove Tuples from the List having every element as None.
Input = [(None,), (None, None), (5, 4), (1,6,7),(None,1)]
Output = [(5, 4), (1,6,7),(None,1)]

30). Python tuple program to sort a list of tuples by the first item.
Input = [ (1, 5), (7, 8), (4, 0), (3, 6) ]
Output = [ (1, 5), (3, 6), (4, 0), (7, 8) ]

31). Python tuple program to sort a list of tuples by the second item.
Input = [ (1, 5), (7, 8), (4, 0), (3, 6) ]
Output = [ (4, 0), (1, 5), (3, 6), (7, 8) ]

32). Python tuple program to sort a list of tuples by the length of the tuple.
Input = [(4, 5, 6), ( 6, ), ( 2, 3), (6, 7, 8, 9, 0 ) ]
Output=
[(6,),(2,3),(4,5,6),(6,7,8,9,0)]

33). Python tuple program to calculate the frequency of elements in a tuple.
Input=
(a, b, c, d, b, a, b)
Output=
{ a:2, b:3, c:1, d:1 }

34). Python tuple program to filter out tuples that have more than 3 elements.
Input=
[ (1, 4), (4, 5, 6), (2, ), (7, 6, 8, 9), (3, 5, 6, 0, 1) ]
Output= [(7, 6, 8, 9), (3, 5, 6, 0, 1)]

35). Python tuple program to assign the frequency of tuples to each tuple.
Input=
[ (s,q), (t, o, o, l), (p, y), (s, q) ]
Output= {(‘s’, ‘q’): 2, (‘t’, ‘o’, ‘o’, ‘l’): 1, (‘p’, ‘y’): 1}

36). Python program to find values of tuples at ith index number.
Input=
[ (1, 2, 3), (6, 5, 4), (7, 6, 8), (9, 0, 1) ]
I = 3
Output= (9,0,1)

37). Python tuple program to test whether a tuple is distinct or not.
Input=
(1,2,3,4)
(3,4,5,4,6,3)
Output=
Tuple is distinct
Tuple is not distinct

38). Python tuple program to convert a tuple to string datatype.
Input=
A=(4,1,7,5)
Output=
The given tuple is (4,1,7,5)

39). Python tuple program to remove empty tuples from a list of tuples.
Input=
[ (”,), (‘a’, ‘b’), (‘a’, ‘b’, ‘c’), (‘d’), () ]
Output=
[ (‘a’, ‘b’), (‘a’,  ‘b’,  ‘c’),  (‘d’) ]

40). Python tuple program to sort a tuple by its float element.
Input=
[(3,5.6),(6,2.3),(1,1.8)]
Output=
[(1,1.8),(6,2.3),(3,5.6)]

41). Python tuple program to count the elements in a list if an element is a tuple.
Input=
[1,6,8,5,(4,6,8,0),5,4)]
Output=
4

42). Python tuple program to multiply all the elements in a tuple.
Input=
(5,4,3,1)
Output=
60

43). Python tuple program to convert a string into a tuple.
Input=
“Sqatools”
Output=
(S,q,a,t,o,o,l,s)

44). Python tuple program to convert a tuple of string values to a tuple of integer values.
Input=
( ‘4563’, ’68’, ‘1,’ )
Output=
( 4563, 68, 1)

45). Python tuple program to convert a given tuple of integers into a number.
Input=
(4, 5, 3, 8)
Output=
4538

46). Python tuple program to compute the element-wise sum of tuples.
Input=
(1, 6, 7)
(4, 3, 0)
(2, 6, 8)
Output=
(7, 15, 15)

47). Python tuple program to convert a given list of tuples to a list of lists.
Input=
A=[(1,5),(7,8),(4,0)]
Output =
[ [1, 5], [7, 8], [4, 0] ]

48). Python tuple program to find all the tuples that are divisible by a number.
Input=
[(10,5,15),(25,6,35),(20,10)]
Output=
[(10,5,15),(20,10)]

49). Python tuple program to find tuples having negative elements.
Input=
[ (1, 7), (-4, -5), (0, 6), (-1, 3) ]
Output=
[(-4,-5),(-1,3)]

50). Python tuple program to find the tuples with positive elements.
Input=
[ (1, 7), (-4, -5), (0, 6), (-1, 3) ]
Output=
[ (1, 7), (0, 6) ]

51). Python tuple program to remove duplicates from a tuple.
Input=
(6, 4, 9, 0, 2, 6, 1, 3, 4)
Output=
(6, 4, 9, 0, 2, 1, 3)

52). Python tuple program to extract digits from a list of tuples.
Input=
[ (6, 87, 7), (4, 53), (11, 28, 3) ]
Output=
[ 1, 2, 3, 4, 5, 6, 7, 8 ]

53). Python tuple program to multiply ith element from each tuple from a list of tuples.
Input=
[ (4, 8, 3), (3, 4, 0), (1, 6, 2) ]
i=1
Output=
192

54). Python tuple program to flatten a list of lists into a tuple.
Input=
[ [s], [q], [a], [t], [o], [o], [l], [s] ]
Output=
(s, q, a, t, o, o, l, s)

55). Python tuple program to flatten a tuple list into a string.
Input=
[ (s, q, a), (t, o), (o, l, s) ]
Output=
‘s q a t o o l s’

56). Python tuple program to convert a tuple into a list by adding the string after every element of the tuple.
Input=
A=(1, 2, 3, 4), b=’sqatools’
Output=
[1, “sqatools”, 2, “sqatools”, 3, “sqatools”, 4, “sqatools”]

57). Write a program to convert a tuple to tuple pair.
Input=
(1, 2, 3)
Output=
[ (1, 2), (1, 3) ]

59). Python tuple program to convert a list of lists to a tuple of tuples.
Input=
[ [‘sqatools’], [‘is’], [‘best’]]
Output=
( (‘sqatools’), (‘is), (‘best’) )

60). Python tuple program to extract tuples that are symmetrical with others from a list of tuples.
Input=
[ (a, b, c), (d, e), (c, b, a) ]
Output=
(a, b, c)

61). Python tuple program to return an empty set if no tuples are symmetrical.
Input=
[(1, 5, 7), (3, 4), (4, 9, 0)]
Output=
set()

62). Python tuple program to remove nested elements from a tuple.
Input=
( ‘s’, ‘q’, ‘a’, (‘t’, ‘o’, ‘o’, ‘l’, ‘s’), ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’ )
Output=
(‘s’, ‘q’, ‘a’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’ ,’t’)

63). Python tuple program to sort a tuple by the maximum value of a tuple.
Input=
[ (1, 5, 7), (3, 4, 2), (4, 9, 0) ]
Output=
[ (4, 9, 0), (1, 5, 7), (3, 4, 2) ]

64). Python tuple program to sort a list of tuples by the minimum value of a tuple.
Input=
[(1,5,7),(3,4,2),(4,9,0)]
Output=
[(4,9,0),(1,5,7),(3,4,2)]

65). Python tuple program to concatenate two tuples.
Input=
(‘s’,’q’,’a)
(‘t’,’o’,’o,’l’)
Output=
((‘s’,’q’,’a),(‘t’,’o’,’o,’l’))

66). Python tuple program to order tuples by external list.
Input=
a=[(‘very’,8),(‘i’,6),(‘am,5),(‘happy’,0)]
List=[‘i’,’am’,’very’,’happy’]
Output=
[(‘i’,6),(‘am’,5),(‘very’,8),(‘happy’,0)]

67). Python tuple program to find common elements between two lists of tuples.
Input=
A=[(1,5),(4,8),(3,9)]
B=[(9,3),(5,6),(5,1),(0,4)]
Output=
{(3,9),(1,5)}

68). Python tuple program to convert a binary tuple to an integer.
Input=
A=(1,0,0)
Output=
4
Explanation=
2^2+0+0=4

69). Python tuple program to count the total number of unique tuples.
Input=
[ (8, 9), (4, 7), (3, 6), (8, 9) ]
Output=
3

70). Python tuple program to calculate the average of the elements in the tuple.
Input=
(5, 3, 9, 6)
Output=
5.75

71). Python tuple program to swap tuples.
Input=
A=(7,4,9)
B=(3,)
Output=
A=(3,)
B=(7,4,9)

72). Python tuple program to check the type of the input and return True if the type is a tuple and False if it is not a tuple.
Input=
A=( 7, 4, 9, 2, 0 )
Output=
True

73). Python tuple program to find the last element of a tuple using negative indexing.
Input=
A=(‘p’,y’,’t’,’o’,’n’)
Output=
n

Python If else Practice Programs, Exercises

Python If else practice programs help beginners to get expertise in conditional programming login. The if-else statement is a conditional statement in programming. It executes a set of instructions if a particular condition is true, and another set of instructions if the condition is false.

1). Python program to check given number is divided by 3 or not.

2). If else program to get all the numbers divided by 3 from 1 to 30.

3). If else program to assign grades as per total marks.
marks > 40: Fail
marks 40 – 50: grade C
marks 50 – 60: grade B
marks 60 – 70: grade A
marks 70 – 80: grade A+
marks 80 – 90: grade A++
marks 90 – 100: grade Excellent
marks > 100: Invalid marks

4). Python program to check the given number divided by 3 and 5.

5). Python program to print the square of the number if it is divided by 11.

6). Python program to check given number is a prime number or not.

7). Python program to check given number is odd or even.

8). Python program to check a given number is part of the Fibonacci series from 1 to 10.

9). Python program to check authentication with the given username and password.

10). Python program to validate user_id in the list of user_ids.

11). Python program to print a square or cube if the given number is divided by 2 or 3 respectively.

12). Python program to describe the interview process.

13). Python program to determine whether a given number is available in the list of numbers or not.

14). Python program to find the largest number among three numbers.

15). Python program to check any person eligible to vote or not
age > 18+ : eligible
age < 18: not eligible

16). Python program to check whether any given number is a palindrome.
Input: 121
Output: palindrome

17). Python program to check if any given string is palindrome or not.
Input: ‘jaj’
output = palindrome

18). Python program to check whether a student has passed the exam. If marks are greater than 35 students have passed the exam.
Input = Enter marks: 45
Output = Pass

19). Python program to check whether the given number is positive or not.
Input = 20
Output = True

20). Python program to check whether the given number is negative or not.
Input = -45
Output = True

21). Python program to check whether the given number is positive or negative and even or odd.
Input = 26
Output = The given number is positive and even

22). Python program to print the largest number from two numbers.
Input:
25, 63
Output = 63

23). Python program to check whether a given character is uppercase or not.
Input = A
Output = The given character is an Uppercase

24). Python program to check whether the given character is lowercase or not.
Input = c
Output = True

25). Python program to check whether the given number is an integer or not.
Input = 54
Output = True

26). Python program to check whether the given number is float or not.
Input = 12.6
Output = True

27). Python program to check whether the given input is a string or not.
Input = ‘sqatools’
Output = True

28). Python program to print all the numbers from 10-15 except 13
Output:
10
11
12
14

29). Python program to find the electricity bill. According to the following conditions:
Up to 50 units rs 0.50/unit
Up to 100 units rs 0.75/unit
Up to 250 units rs 1.25/unit
above 250 rs 1.50/unit
an additional surcharge of 17% is added to the bill
Input = 350
Output = 438.75

30). Python program to check whether a given year is a leap or not.
Input = 2000
Output = The given year is a leap year

31). Python Python program to check whether the input number if a multiple of two print “Fizz” instead of the number and for the multiples of three print “Buzz”. For numbers that are multiples of both two and three print “FizzBuzz”.
Input = 14
Output = Fizz
Input = 9
Output = Buzz
Input = 6
Output = FizzBuzz

32). Python program to check whether an alphabet is a vowel.
Input = A
Output = True

33). Python program to check whether an alphabet is a consonant.
Input = B
Output = True

34).  Python program to convert the month name to the number of days.
Input = February
Output = 28/29 days

35). Python program to check whether a triangle is equilateral or not. An equilateral triangle is a triangle in which all three sides are equal.
Input:
Enter the length of the sides of the triangle
A=10
B=10
C=10
Output = True

36). Python program to check whether a triangle is scalene or not. A scalene triangle is a triangle that has three unequal sides.
Input:
Enter the length of the sides of the triangle
A=10
B=15
C=18
Output = True

37). Python program to check whether a triangle is isosceles or not. An isosceles triangle is a triangle with (at least) two equal sides.
Input:
Enter the length of the sides of the triangle
A=10
B=15
C=10
Output = True

38). Python program that reads month and returns season for that month.
Input = February
Output = Summer

39). Python program to check whether the input number is a float or not if yes then round up the number to 2 decimal places.
Input = 25.3614
Output = 25.36

40). Python program to check whether the input number is divisible by 12 or not.
Input = 121
Output = True

41). Python program to check whether the input number is a square of 6 or not.
Input = 37
Output = False

42). Python program to check whether the input number is a cube of 3 or not.
Input = 27
Output = True

43). Python program to check whether two numbers are equal or not.
Input:
A=26,B=88
Output = The given numbers are not equal

44). Python program to check whether the given input is a complex type or not.
Input:
a=5+6j
Output: True

45). Python program to check whether the given input is Boolean type or not.
Input:
a=True
Output = The given variable is Boolean

46). Python program to check whether the given input is List or not.
Input:
a=[1,3,6,8]
Output = True

47). Python program to check whether the given input is a dictionary or not.
Input:
A={‘name’:’Virat’,’sport’:’cricket’}
Output = True

48). Python program to check the eligibility of a person to sit on a roller coaster ride or not. Eligible when age is greater than 12.
Input = 15
Output = You are eligible

49). Python program to create 10 groups of numbers between 1-100 and find out given input belongs to which group using python nested if else statements.
Input= 36
Output = The given number belongs to 4th group

50). Python program to find employees eligible for bonus. A company decided to give a bonus of 10% to employees. If the employee has served more than 4 years. Ask the user for years served and check whether an employee is eligible for a bonus or not.
Input = Enter Years served: 5
Output = You are eligible for a bonus

51). Take values of the length and breadth of a rectangle from the user and check if it is square or not using the python if else statement.
Input:
Length= 4
Breadth= 5
Output = It is not a square

52). A shop will give a 10% discount if the bill is more than 1000, and 20% if the bill is more than 2000. Using the python program Calculate the discount based on the bill.
Input = 1500
Output = Discount amount: 150

53). Python program to print the absolute value of a number defined by the user.
Input = -1
Output = 1

54). Python program to check the student’s eligibility to attend the exam based on his/her attendance. If attendance is greater than 75% eligible if less than 75% not eligible.
Input = Enter attendance: 78
Output = You are eligible

55). Python program to check whether the last digit of a number defined by the user is divisible by 4 or not.
Input = 58
Output = The last digit is divisible by 4

56). Python program to display 1/0 if the user gives Hello/Bye as output.
Input = Enter your choice: Hello
Output = 1
Input = Enter your choice: Bye
Output = 0

57). Python program to accept the car price of a car and display the road tax to be paid according to the following criteria:
Cost price<500000 –> tax:15000
Cost price<1000000 –> tax:50000
Cost price<1500000 –> tax:80000
Input = Car Price: 1200000
Output = Tax payable: 50000

58). Using a python program take input from the user between 1 to 7 and print the day according to the number. 1 for Sunday 2 for Monday so on.
Input = Enter number: 7
Output = Saturday

59). Python program to accept the city name and display its monuments (take Pune and Mumbai as cities).
Input = Enter city name: Pune
Output:
Shaniwar vada
Lal mahal
Sinhgad fort

60). Python program to check whether the citizen is a senior citizen or not. An age greater than 60 than the given citizen is a senior citizen.
Input = Enter age: 70
Output = The given citizen is a senior citizen

61). Python program to find the lowest number between three numbers.
Input:
A=45
B=23
C=68
Output = 23

62). Python program to accept the temperature in Fahrenheit and check whether the water is boiling or not.
Hint: The boiling temperature of water in Fahrenheit is 212 degrees
Input = Enter temperature: 190
Output = Water is not boiling

63). Python program to accept two numbers and mathematical operations from users and perform mathematical operations according to it.
Input:
A=30
B=45
Operation = +
Output = 75

64). Python program to accept marks from the user allot the stream based on the following criteria.
Marks>85: Science
Marks>70: Commerce
35<Marks<70: Arts
Marks<35: Fail
Input = Marks: 88
Output = Science