×

Python Examples

In this tutorial, we will see some examples related to python. This will include some basic example questions and their code in Python.

  • Write a program to print “Hello Python”.
print(‘Hello Python’)

Output

Hello Python

Explanation

In the above line of code, we can print any line using just one line of code.

  • Write a program to find the maximum between two numbers.

Without using a function

a = 2
b = 4      
if a >= b:
    print (a)
else:
    print (b)

Using function

def max(x, y):
      
    if x >= y:
        return x
    else:
        return y
      
      
x = 2
y = 4
print(max(x, y))

Output

4

Explanation

In the above program, we solved the problem using two methods. We can write the code for finding the maximum between two numbers using a function and without using a function. In the first code, we have just used the conditional statement to compare the two numbers and whoever is larger will get printed. In the second code, we used a function for finding the maximum value. We have created a function name max( ) and passed the two values as parameters. Inside that function, we have used the if-else statement to find the maximum value. At last, we return the maximum value using the return statement.

  • Write a program to find the factorial of a number.

Using Recursion

def fact(n):
     
    # single line to find factorial
    if n==1 or n==0:
         return 1 
    else:
         return n * fact(n - 1);
 


num = 5;
x = fact(num)
print("Factorial of",num,"is",x)

Using Iterative

def fact(n):
    if n < 0:
        return 0
    elif n == 0 or n == 1:
        return 1
    else:
        fact = 1
        while(n > 1):
            fact *= n
            n -= 1
        return fact
 


num = 5;
x = fact(num)
print("Factorial of",num,"is",x)

Output

Factorial of 5 is 120

Explanation

In the above program, we have used two methods for finding the factorial between two numbers. In the first code, we used recursion for finding the factorial between two numbers. We have created a function name as fact() and inside that function, we have used the recursive method to find the factorial. In the second code, we used the iterative method for finding the factorial between two numbers. In this code, inside the function, we have used a while loop.

  • Write a program to find the nth Fibonacci number.

Using Recursion

# First Fibonacci number is 0
# Second Fibonacci number is 1
def fibo(n):
    if n<= 0:
        print("Incorrect input")
    
    elif n == 1:
        return 0
    
    elif n == 2:
        return 1
    else:
        return fibo(n-1)+fibo(n-2)
 


print(fibo(5))

Output

3

Explanation

In the above line of code, we have used a recursive function for finding the nth Fibonacci number. We have used a function name fibo() and inside that function, we have passed the position as the parameter to calculate the nth position Fibonacci number.

  • Write a program to find if the number is a Prime number.
x = int(input("Enter a number: "))
  
if x > 1:
    for i in range(2, int(x/2)+1):
          if (x % i) == 0:
            print(num, "is not a prime number")
            break
    else:
        print(x, "is a prime number")
  
else:
    print(x, "is not a prime number")

Input

5

Output

5 is a prime number

Explanation

In the above code, we have used loop and conditional statements for finding if a number is prime or not.

  • Write a program to find the sum of the square of the first n natural number.
def square_sum(n) :
  
    sum = 0
    for i in range(1, n+1) :
        sum = sum + (i * i)
      
    return sum
  


n = 5
print(square_sum(n))

Output

55

Explanation

Sum = 1 + 4 + 9 + 16 + 25 = 55

In the above line of code, we have calculated the sum of squares of the first n natural number using a for loop. We used a variable name sum for storing the sum of squares number in each loop. After the loop end, we return the value stored in the variable sum.

  • Write a program to print the ASCII value of any given character.
ch = 'a'


print("The ASCII value of '" + ch + "' is", ord(ch))

Output

The ASCII value of 'a' is 97

Explanation

ASCII values are used to convert a character into an integer.
ASCII (A,…..,Z) = (65,…..,90)
ASCII (a,……,z) = (97,…..,122)

In the above code, we can print the ASCII value of an alphabet using the function name ord().

Note: ord() function is used to convert characters into integers in Python.

  • Write a program to find the area of a circle.
Area of circle: π * (r*r)
where r is the radius of the circle.

Code

# Area of circle
def area(r):
    pi = 3.142
    return pi * (r*r);


print("Area is %.2f" % area(3));

Output

Area is 28.28

Explanation

The area() function calculates the area of circle, and its value is returned. Since an area can be an integer and a float value, we have used %.2f to print the value. This means the value will be printed in a float value, and after the decimal, only two digits will be printed.

  • Write a program to find the largest element in an array.
def largest(arr,n):
  
    # Initialize maximum element
    max = arr[0]
  
    # Traverse array from second element
    
    for i in range(1, n):
        if arr[i] > max:
            max = arr[i]
    return max
  


arr = [6, 77, 320, 60, 100]
x = len(arr)
lar_num = largest(arr,x)
print ("Largest in given array is", lar_num)

Input

arr = [66, 77, 320, 60, 100]

Output

Largest in given array is 320

Explanation

In the above code, we have declared an array with given values. After that, we are calling a function name largest() with arguments as array and size of the array. We have used the function largest to find the largest element of an array by comparing the selected index value with the rest index value on its right side.  The returned value from the array is stored in a variable name lar_num.

  • Write a program to add of two matrices.

a = [[1,2,3],
    [11 ,12,13],
    [111 ,112,113]]
 
b = [[4,5,6],
    [14,15,16],
    [114,115,116]]
 
c = [[0,0,0],
       [0,0,0],
        [0,0,0]]
 
# iterate through rows and then column 
for i in range(len(a)):  
    for j in range(len(a[0])):
        c[i][j] = a[i][j] + b[i][j]
 
for r in c:
    print(r)

Input

a = [[1,2,3],
    [11 ,12,13],
    [111 ,112,113]]
 
b = [[4,5,6],
    [14,15,16],
    [114,115,116]]


c = a+b
c = [(1+4), (2+5), (3+6)]
      [(11+14), (12+15), (13+16)]
      [(111+114), (112+115), (113+116)]

Output:

[5, 7, 9]
[25, 27, 29]
[225, 227, 229]

Explanation

In the above code, for adding two matrices, we have used two loops which will be iterating over all the rows and columns of both the matrix, and then used another matrix for storing the added value.


Related Topics

Python program to count the number of a substring in a string

Python program to count the number of a substring in a string A part of the string is called a substring. This article explains the Python program to find how many...

1 minute read.

Uint8 Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

FOO in Python

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute read.

Spell Corrector GUI using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

3 minutes read.

Iterate a Dictionary in Python

In this tutorial, we will learn how to Iterate a Dictionary in Python. Dictionary: In Python, a dictionary is an unordered collection of data values that is used to store data values,...

3 minutes read.

App Config Python

An XML file called App. Config serves as the document for any programme. In other terms, you can modify any configuration inside of it without going to edit the code...

7 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Difference between Mutable and Immutable Objects

Difference between Mutable and Immutable Objects As we all know that Python is an object-oriented programming language. Object-oriented programming approach is based on the objects and the classes’ stores the data...

4 minutes read.

How to Open a file in python with Path

In this tutorial, we will see rather than the traditional way of opening a file by locating or navigating it from our desktops; we will learn how to open the...

2 minutes read.

How to import pandas in python

How to Install Pandas in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

What does the if __name__ == "__main__" do in Python

In this article, you will learn about the If__name__==__main__ is a statement in python to define modules and the names of the modules. This statement plays a vital role in...

3 minutes read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Program of Cumulative Sum in Python

Introduction This tutorial, explains what is meant by lists, the cumulative total, several approaches to calculating the cumulative sum of digits in a list, etc. Learn the straightforward Python codes for...

5 minutes read.

Defaultdict in Python

In this tutorial, we will study What is defaultdict in Python We will understand it with the aid of certain examples. Before this, we will have a look at dictionaries...

3 minutes read.

Performing Transaction Using Python MySQL

Transaction A Transaction contains a set of SQL commands used to change the data in the dataset. If we say transaction, it means that the data in the database has changed....

3 minutes read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.