Author: Saim Khalid

  • Generate a Random Number

    Python Program to Generate a Random Number

    To understand this example, you should have the knowledge of the following Python programming topics:


    To generate random number in Python, randint() function is used. This function is defined in random module.


    Source Code

    # Program to generate a random number between 0 and 9
    
    # importing the random module
    import random
    
    print(random.randint(0,9))
    

    Output

    5
    

    Note that we may get different output because this program generates random number  in range 0 and 9. The syntax of this function is:

    random.randint(a,b)
    

    This returns a number N in the inclusive range [a,b], meaning a <= N <= b, where the endpoints are included in the range.

  • Swap Two Variables

    Python Program to Swap Two Variables

    To understand this example, you should have the knowledge of the following Python programming topics:


    Source Code: Using a temporary variable

    Code Visualization: Want to see exactly how variable swapping works? Step through each line with our new code visualizer. Try it yourself!

    # Python program to swap two variables
    
    x = 5
    y = 10
    
    # To take inputs from the user
    #x = input('Enter value of x: ')
    #y = input('Enter value of y: ')
    
    # create a temporary variable and swap the values
    temp = x
    x = y
    y = temp
    
    print('The value of x after swapping: {}'.format(x))
    print('The value of y after swapping: {}'.format(y))
    

    Output

    The value of x after swapping: 10
    The value of y after swapping: 5
    

    In this program, we use the temp variable to hold the value of x temporarily. We then put the value of y in x and later temp in y. In this way, the values get exchanged.


    Source Code: Without Using Temporary Variable

    In Python, there is a simple construct to swap variables. The following code does the same as above but without the use of any temporary variable.

    x = 5
    y = 10
    
    x, y = y, x
    print("x =", x)
    print("y =", y)
    

    If the variables are both numbers, we can use arithmetic operations to do the same. It might not look intuitive at first sight. But if you think about it, it is pretty easy to figure it out. Here are a few examples

    Addition and Subtraction

    x = x + y
    y = x - y
    x = x - y
    

    Multiplication and Division

    x = x * y
    y = x / y
    x = x / y
    

    XOR swap

    This algorithm works for integers only

    x = x ^ y
    y = x ^ y
    x = x ^ y
    

    Also Read:

  • Solve Quadratic Equation

    Python Program to Solve Quadratic Equation

    To understand this example, you should have the knowledge of the following Python programming topics:


    The standard form of a quadratic equation is:

    ax2 + bx + c = 0, where
    a, b and c are real numbers and
    a ≠ 0

    The solutions of this quadratic equation is given by:

    (-b ± (b ** 2 - 4 * a * c) ** 0.5) / (2 * a)

    Source Code

    # Solve the quadratic equation ax**2 + bx + c = 0
    
    # import complex math module
    import cmath
    
    a = 1
    b = 5
    c = 6
    
    # calculate the discriminant
    d = (b**2) - (4*a*c)
    
    # find two solutions
    sol1 = (-b-cmath.sqrt(d))/(2*a)
    sol2 = (-b+cmath.sqrt(d))/(2*a)
    
    print('The solution are {0} and {1}'.format(sol1,sol2))

    Output

    Enter a: 1
    Enter b: 5
    Enter c: 6
    The solutions are (-3+0j) and (-2+0j)

    We have imported the cmath module to perform complex square root. First, we calculate the discriminant and then find the two solutions of the quadratic equation.

    You can change the value of ab and c in the above program and test this program.


    Also Read:

    Before we wrap up, let’s put your understanding of this example to the test! Can you solve the following challenge?

    Challenge:

    Write a function to solve a quadratic equation.

    • Define a function that takes three integers as input representing the coefficients of a quadratic equation.
    • Return the roots of the quadratic equation.
    • Hint: The quadratic formula is x = [-b ± sqrt(b^2 - 4ac)] / (2a).
    • The term inside the square root, b^2 - 4ac, is called the discriminant.
    1. If it’s positive, there are two real roots.
    2. If it’s zero, there’s one real root.
    3. If it’s negative, there are two complex roots.
    • While returning the list, make sure the solution of [-b + sqrt(b^2 – 4ac)] / (2a) appears as the first solution.
    1. import math

    2. def solve_quadratic(a, b, c):

  • Calculate the Area of a Triangle

    Python Program to Calculate the Area of a Triangle

    To understand this example, you should have the knowledge of the following Python programming topics:


    If ab and c are three sides of a triangle. Then,

    s = (a+b+c)/2
    area = √(s(s-a)*(s-b)*(s-c))

    Source Code

    # Python Program to find the area of triangle
    
    a = 5
    b = 6
    c = 7
    
    # Uncomment below to take inputs from the user
    # a = float(input('Enter first side: '))
    # b = float(input('Enter second side: '))
    # c = float(input('Enter third side: '))
    
    # calculate the semi-perimeter
    s = (a + b + c) / 2
    
    # calculate the area
    area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
    print('The area of the triangle is %0.2f' %area)

    Run Code

    Output

    The area of the triangle is 14.70
    

    In this program, area of the triangle is calculated when three sides are given using Heron’s formula.

    If you need to calculate area of a triangle depending upon the input from the user, input() function can be used.


    Also Read:

    Before we wrap up, let’s put your understanding of this example to the test! Can you solve the following challenge?

    Challenge:

    Write a function to find the area of a right angled triangle rounded off to two decimal places.

    • For example, for inputs 3 and 4, the output should be 6.0.
    • Reason: The area of a right-angled triangle is given by (1/2)*base*height. So, for base = 3 and height = 4, it’s (1/2)*3*4 = 6.0.

    1 def triangle_area(base, height):

    2

  • Find the Square Root

    Python Program to Find the Square Root

    To understand this example, you should have the knowledge of the following Python programming topics:


    Example: For positive numbers

    # Python Program to calculate the square root
    
    # Note: change this value for a different result
    num = 8 
    
    # To take the input from the user
    #num = float(input('Enter a number: '))
    
    num_sqrt = num ** 0.5
    print('The square root of %0.3f is %0.3f'%(num ,num_sqrt))
    

    Output

    The square root of 8.000 is 2.828
    

    In this program, we store the number in num and find the square root using the ** exponent operator. This program works for all positive real numbers. But for negative or complex numbers, it can be done as follows.

    Source code: For real or complex numbers

    # Find square root of real or complex numbers
    # Importing the complex math module
    import cmath
    
    num = 1+2j
    
    # To take input from the user
    #num = eval(input('Enter a number: '))
    
    num_sqrt = cmath.sqrt(num)
    print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.real,num_sqrt.imag))
    

    Output

    The square root of (1+2j) is 1.272+0.786j

    In this program, we use the sqrt() function in the cmath (complex math) module.

    Note: If we want to take complex number as input directly, like 3+4j, we have to use the eval() function instead of float().

    The eval() method can be used to convert complex numbers as input to the complex objects in Python. To learn more, visit Python eval() function.

    Also, notice the way in which the output is formatted. To learn more, visit string formatting in Python.

  • Add Two Numbers

    Python Program to Add Two Numbers

    To understand this example, you should have the knowledge of the following Python programming topics:


    In the program below, we’ve used the + operator to add two numbers.

    Example 1: Add Two Numbers

    # This program adds two numbers
    
    num1 = 1.5
    num2 = 6.3
    
    # Add two numbers
    sum = num1 + num2
    
    # Display the sum
    print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
    

    Run Code

    Output

    The sum of 1.5 and 6.3 is 7.8

    The program below calculates the sum of two numbers entered by the user.

    Example 2: Add Two Numbers With User Input

    # Store input numbers
    num1 = input('Enter first number: ')
    num2 = input('Enter second number: ')
    
    # Add two numbers
    sum = float(num1) + float(num2)
    
    # Display the sum
    print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
    

    Run Code

    Output

    Enter first number: 1.5
    Enter second number: 6.3
    The sum of 1.5 and 6.3 is 7.8

    In this program, we asked the user to enter two numbers and this program displays the sum of two numbers entered by user.

    We use the built-in function input() to take the input. Since, input() returns a string, we convert the string into number using the float() function. Then, the numbers are added.

    Alternative to this, we can perform this addition in a single statement without using any variables as follows.

    print('The sum is %.1f' %(float(input('Enter first number: ')) + float(input('Enter second number: '))))
    

    Run Code

    Output

    Enter first number: 1.5
    Enter second number: 6.3
    The sum of 1.5 and 6.3 is 7.8

    Although this program uses no variable (memory efficient), it is harder to read.

    Before we wrap up, let’s put your understanding of this example to the test! Can you solve the following challenge?

    Challenge:

    Write a function to add 10 to a given number.

    • For example, for input 5, the output should be 15.

    1 def add_ten(n):

    2

  • Python Examples

    Python Program to Print Hello world!

    To understand this example, you should have the knowledge of the following Python programming topics:


    Source Code

    # This program prints Hello, world!
    
    print('Hello, world!')
    

    Run Code

    Output

    Hello, world!
    

    In this program, we have used the built-in print() function to print the string Hello, world! on our screen.

    By the way, a string is a sequence of characters. In Python, strings are enclosed inside single quotes, double quotes, or triple quotes.

  • Web Scraper

    1. Create a web scraper using libraries like BeautifulSoup or Scrapy to collect data from websites. For example, you can scrape news headlines or product prices and store them in a database.

    import requests
    from bs4 import BeautifulSoup

    def web_scraper():
    url = “https://quotes.toscrape.com/”
    response = requests.get(url)

    soup = BeautifulSoup(response.text, 'html.parser')
    
    quotes = soup.find_all("span", class_="text")
    authors = soup.find_all("small", class_="author")
    
    print("Quotes and Authors:")
    for quote, author in zip(quotes, authors):
    
    print(f"Quote: {quote.get_text()}")
    print(f"Author: {author.get_text()}")
    print("-" * 50)</code></pre>

    Run the scraper

    web_scraper()

    1. Personal Finance Dashboard
      • Build a web-based personal finance dashboard that pulls in transaction data from APIs (like PayPal or bank APIs) and displays them in graphical formats using libraries like Plotly or Matplotlib.
    2. Django/Flask Blog App
      • Build a blogging platform where users can create accounts, post articles, comment on posts, and like articles. This can be a full-stack project using Django or Flask for the backend and a simple HTML/CSS/JS front end.
    3. AI-based Sentiment Analysis
      • Create a sentiment analysis tool that uses machine learning to analyze text and predict whether the sentiment is positive, negative, or neutral. You can use libraries like TextBlob or NLTK for this project.
    4. Social Media Automation
      • Build a bot that can automate tasks on social media platforms (like Twitter or Instagram) using their respective APIs. The bot could post updates, follow users, or respond to comments.
  • Number Guessing Game

    Build a simple number guessing game where the program randomly selects a number, and the player has to guess it. You can provide hints like “too high” or “too low.”

      import random

      def number_guessing_game():
      print(“Welcome to the Number Guessing Game!”)
      print(“I am thinking of a number between 1 and 100.”)

      # Generate a random number between 1 and 100
      number_to_guess = random.randint(1, 100)
      
      attempts = 0
      guessed = False
      
      while not guessed:
      
      guess = int(input("Make a guess: "))
      attempts += 1
      if guess &lt; number_to_guess:
          print("Too low. Try again!")
      elif guess &gt; number_to_guess:
          print("Too high. Try again!")
      else:
          print(f"Congratulations! You guessed the number in {attempts} attempts.")
          guessed = True</code></pre>

    1. Immutable Data Structures

      The Python Immutable data structures are the data structures that once created, cannot be changed. This means that any attempt to modify the data structure will result in a new instance being created rather than altering the original. Immutable data structures are useful for ensuring that data remains constant throughout the execution of a program which can help prevent bugs and make code easier to understand and maintain.

      Before proceeding deep into this topic let’s have a quick recall of what is datastructure? The Data structures are specialized formats for organizing, processing, retrieving and storing data. They define how data is arranged in memory and how operations such as accessing, inserting, deleting and updating can be performed efficiently.

      Different Immutable Data Structures in Python

      Immutable data structures are essential in Python for their stability, thread-safety and ease of use. Here are the different immutable data structures in Python −

      • Tuples: These are the ordered collections of items that cannot be changed after their creation. They can contain mixed data types and are useful for representing fixed collections of related items.
      • Strings: These Data structures are sequences of characters and are immutable. Any operation that modifies a string will create a new string.
      • Frozensets: These are immutable versions of sets. Unlike regular sets, frozensets do not allow modification after creation.
      • Named Tuples: These are a subclass of tuples with named fields which provide more readable and self-documenting code. They are immutable like regular tuples.

      Now, let’s proceed about the each Immutable data structures in detail.

      Tuples

      Tuples in Python are immutable sequences of elements which means once created, they cannot be modified. They are defined using parentheses ‘()’ and can hold a collection of items such as numbers, strings and even other tuples.

      Creating Tuples

      Tuples are created using parentheses ‘()’ and elements separated by commas ‘,’. Even tuples with a single element require a trailing comma to distinguish them from grouped expressions.

      Following is the example of creating a tuple by assigning parentheses ‘()’ to a variable −

      empty_tuple =()
      single_element_tuple =(5,)# Note the comma after the single elementprint("Single element tuple:", single_element_tuple)
      multi_element_tuple =(1,2,'Tutorialspoint',3.14)print("Multi elements tuple:", multi_element_tuple)
      nested_tuple =(1,(2,3),'Learning')print("Nested tuple:", nested_tuple)

      On executing the above code we will get the following output −

      Single element tuple: (5,)
      Multi elements tuple: (1, 2, 'Tutorialspoint', 3.14)
      Nested tuple: (1, (2, 3), 'Learning')
      

      Understanding Tuple Immutability in Python

      Here we are going understand the immutability of the tuples in python. Below is the example −

      # Define a tuple
      my_tuple =(1,2,3,'hello')# Attempt to modify an element (which is not possible with tuples)# This will raise a TypeErrortry:
         my_tuple[0]=10except TypeError as e:print(f"Error: {e}")# Even trying to append or extend a tuple will result in an errortry:
         my_tuple.append(4)except AttributeError as e:print(f"Error: {e}")# Trying to reassign the entire tuple to a new value is also not allowedtry:
         my_tuple =(4,5,6)except TypeError as e:print(f"Error: {e}")print("Original tuple:", my_tuple)

      On executing the above code we will get the following output −

      Error: 'tuple' object does not support item assignment
      Error: 'tuple' object has no attribute 'append'
      Original tuple: (4, 5, 6)
      

      Strings

      Strings in Python are sequences of characters which are used to represent and manipulate textual data. They are enclosed within either single quotes  or double quotes  with the option to use triple quotes “”” for multi-line strings.

      Key characteristics include immutability which means once created those strings cannot be changed, ordered indexing where characters are accessed by position and support for various operations such as concatenation, slicing and iteration.

      Strings are fundamental in Python for tasks such as text processing, input/output operations and data representation in applications offering a versatile toolset with built-in methods for efficient manipulation and formatting of textual information.

      Creating Strings

      Each type of string creation method i.e. ‘, “, “”” has its own use case depending on whether we need to include quotes within the string, handle multi-line text or other specific formatting requirements in our Python code.

      Following is the example of creating the string with the help od three types of quotes ‘, “, “”” −

      # Single line string
      single_quoted_string ='Hello, Welcome to Tutorialspoint'# Double quoted string
      double_quoted_string ="Python Programming"# Triple quoted string for multi-line strings
      multi_line_string ="""This is a 
      multi-line 
      string"""print(single_quoted_string)print(double_quoted_string)print(multi_line_string)

      On executing the above code we will get the following output −

      Hello, Welcome to Tutorialspoint
      Python Programming
      This is a
      multi-line
      string
      

      Understanding String Immutability in Python

      With the help of following example we are going to understand the immutability of the strings in python.

      # Example demonstrating string immutability
      my_string ="Hello"# Attempting to modify a string will create a new string instead of modifying the original
      modified_string = my_string +" Learners"print(modified_string)# Output: Hello Learners# Original string remains unchangedprint(my_string)# Output: Hello# Trying to modify the string directly will raise an errortry:
         my_string[0]='h'# TypeError: 'str' object does not support item assignmentexcept TypeError as e:print(f"Error: {e}")

      On executing the above code we will get the following output −

      Hello Learners
      Hello
      Error: 'str' object does not support item assignment
      

      Frozen Sets

      A frozen set in Python is an immutable version of a set. Once created its elements cannot be changed, added or removed. Frozen sets are particularly useful in situations where we need a set that remains constant throughout the execution of a program especially when we want to use it as a key in a dictionary or as an element in another set.

      Creating Frozen Sets

      We can create a frozen set using the frozenset() constructor by passing an iterable such as a list or another set as an argument. Following is the example of creating the Frozen set −

      # Creating a frozen set
      fset =frozenset([1,2,3,4])# Printing the frozen setprint(fset)

      On executing the above code we will get the following output −

      frozenset({1, 2, 3, 4})
      

      Understanding Frozen Sets Immutability in Python

      Here’s an example shows how frozensets being immutable and do not allow modifications after creation.

      # Creating a frozenset
      frozen_set =frozenset([1,2,3,4])# Attempting to add an element to the frozenset will raise an errortry:
         frozen_set.add(5)except AttributeError as e:print(f"Error: {e}")# Attempting to remove an element from the frozenset will also raise an errortry:
         frozen_set.remove(2)except AttributeError as e:print(f"Error: {e}")# The original frozenset remains unchangedprint("Original frozenset:", frozen_set)

      On executing the above code we will get the following output −

      Error: 'frozenset' object has no attribute 'add'
      Error: 'frozenset' object has no attribute 'remove'
      Original frozenset: frozenset({1, 2, 3, 4})
      

      Named Tuples

      A Named tuple in Python is a lightweight data structure available in the collections module that behaves same as a tuple but allows us to access its elements using named attributes as well as indices.

      It combines the advantages of tuples such as immutable, memory-efficient with the ability to refer to elements by name, enhancing readability and maintainability of code.

      Creating Named Tuples

      we can define a named tuple using the namedtuple() factory function from the collections module. It takes two arguments such as a name for the named tuple type and a sequence i.e. string of field names or iterable of strings which specifies the names of its fields.

      from collections import namedtuple
      
      # Define a named tuple type 'Point' with fields 'x' and 'y'
      Point = namedtuple('Point',['x','y'])# Create an instance of Point
      p1 = Point(1,2)# Access elements by index (like a tuple)print(p1[0])# Access elements by nameprint(p1.x)print(p1.y)

      On executing the above code we will get the following output −

      1
      1
      2
      

      Understanding Named Tuples Immutability in Python

      The Named tuples in Python are provided by the collections.namedtuple factory functions are indeed immutable. They behave similarly to regular tuples but have named fields by making them more readable and self-documenting.

      from collections import namedtuple
      
      # Define a named tuple called Point with fields 'x' and 'y'
      Point = namedtuple('Point',['x','y'])# Create an instance of Point
      p = Point(x=1, y=2)print(p)# Attempt to modify the named tuple# This will raise an AttributeError since named tuples are immutabletry:
         p.x =10except AttributeError as e:print(f"Error occurred: {e}")# Accessing elements in a named tuple is similar to accessing elements in a regular tupleprint(p.x)print(p.y)

      On executing the above code we will get the following output −

      Point(x=1, y=2)
      Error occurred: can't set attribute
      1
      2