×

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 String isupper() method

Python String isupper() method The String.isupper() method in Python returns a boolean value ‘true’ if all cased characters in the string are uppercase else for any other value is returns false. Syntax String.isupper() Parameter NA Return This...

2 minutes read.

Python IDE names

Python is one of the most renowned programming languages. It has different execution conditions and a great many compilers to execute the python programs, e.g., PyCharm, PyDev, Jupyter Notebook, Visual...

6 minutes read.

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary In Python, dictionaries are a useful and commonly used data structure in...

3 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

Python Euclidean Distance

Euclidean distance is the distance between two points with whatever of dimensions. We are using NumPy library to find and calculate the Euclidean distance. The NumPy library is used for...

1 minute read.

Python memoryview() Function

Python memoryview() Function The memoryview() function in Python returns a memory view object from a specified object. Syntax memoryview(obj) Parameter obj: This parameter represents a Bytes object or a bytearray object. Return This function returns a “memory view” object...

1 minute read.

How to Fix an EOF Error in Python?

Introduction An EOF (End-of-File) error occurs when a program tries to read beyond the end of a file or a stream, causing it to return an error message. It can happen...

8 minutes read.

Get index of element in array in python

Index : Index is a number where the element is located in the given list. In other words it is the position of the element in the list. Index can also...

4 minutes read.

Weight Conversion GUI using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

3 minutes read.

Working with files in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has an...

5 minutes read.

Python TypeError

What is TypeError in python? TypeError is one of the exceptions in the python programming language. This exception occurs when an operation is performed on an unsupported object type or can...

6 minutes read.

Subprocess in Python

In this tutorial, we will understand what is a subprocess in python and will understand how to use it. Subprocess A subprocess is a very prevailing portion of the python library. It...

3 minutes read.

SKLearn Clustering

These are ml methods thatare responsible for detecting patterns and the similarities within the data.The clustering methods are unsupervised.Here the data is clustered to form groups with the help of...

3 minutes read.

Python Scikit-image | Image Processing Using Scikit-Image

What is Image Processing? The world is defined with images and, every image has its different specialties. An image can contain much-needed information that can be helpful in various ways. The process...

4 minutes read.

Python Set intersection_update() method

Python Set intersection_update() method The set.intersection_update() method in Python removes the items that is not present in both sets. It is different from the set.intersection() method, because the intersection()method returns a new set, with only  the common elements...

2 minutes read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.

Python String expandtabs() method

Python String expandtabs() method The string.expandtabs() method in Python returns a copy of the string where all tab characters are expanded using spaces. Syntax String.expandtabs([tabsize]) Parameter tabsize: This parameter specifies the number of characters to...

1 minute read.