×

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

Standard GUI Unit Converter using PyQt5 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...

6 minutes read.

Python ascii() Function

Python ascii() Function The ascii() function returns a readable version of any object (Strings, Tuples, Lists, etc). This function will replace any non-ascii characters with escape characters. Syntax ascii(object) Parameter object:  An object, like String, List, Tuple, Dictionary, etc. Return This...

1 minute read.

Convert XML to JSON in Python

XML conversion is very useful if we work on an API that returns data in JSON format and the source of data is in XML format. JSON A JSON file reserves the...

4 minutes read.

Python Project Ideas for Advanced Developers

Best Python Project Ideas for Advanced Developers Python is an object-oriented, high-level, interpreted programming language created by a developer known Guido Van Rossum. Python is one of the languages that gathered...

9 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Algorithm for Factorial of a number in Python

What is a Factorial Number? In mathematics, the factorial of a positive integer n, denoted by n!. It is the product of all positive integers less than or equal to n. For...

3 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Python coding platform

Python is a popular general-purpose programming language with many applications. High-level data structures, datatypes, dynamic binding, and many other features make it useful for both designing complex applications and "glue...

6 minutes read.

How to Configure Python Interpreter in Eclipse

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

How to check if the dictionary is empty in Python?

What is a dictionary in Python? A directory is a collection of data but data is not ordered. Unlike other data types, it does not hold a single value as its...

3 minutes read.

Python BytesIO

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.

Composition in Python

Composition in Python Composition is one of the important concepts of Object-oriented programming (OOPs). Composition basically enables us for creating complex types objects by combining other types of objects in the...

6 minutes read.

How to Make an App with Python

In this age of mobiles, rapid mobile application development has got a lot of traction. Moreover, app developers are high in demand because of the increase in digitization. Generally, Python is...

4 minutes read.

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Comment starts with the symbol in Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

__init__ in python

Every programmer will enclose to object-oriented programming (OOP) these days. As we know, that python is the latest and most modern programming language; python supports to implementation of object-oriented philosophy....

5 minutes read.