Python

Python 3 Code Examples for Beginners69 min read

Table of Contents

Python Programs for Practice

Welcome to our section dedicated to the Python programming language. You will find a set of information related to this language (course support, code examples, …).

Here is a small examples of python programming language.

How to Print “Hello World!” in Python




Python 3 Code:

This simple program uses the print() function to output the string “Hello, world!” to the console. This is a common first program for people learning a new programming language, as it helps to ensure that the development environment is set up correctly and that the programmer knows how to write and run a program.

In python the print() function is used for displaying output on the console.It takes one or more parameters, which are the values to be printed. Each parameter is separated by a comma. In this case, “Hello, world!” is passed as the only parameter to the print function.

In Python 3 , print is a function, so it needs to be called with paranthesis. But in python 2 print is not a function so it dont need paranthesis.

It’s also worth noting that the string “Hello, world!” is enclosed in quotation marks, which indicate that it is a string of characters. In Python, strings are enclosed in either single quotes (‘) or double quotes (“), and they can contain any combination of letters, numbers, and symbols.

When you run this program, the following will be output to the console:

 This is the string “Hello, world!” that was passed as a parameter to the print() function.

You can run this program by saving it in a file with a .py extension and then running the file using the python interpreter. you can also do that by writing the code in the interpreter(running python in the command line) and it will directly give the output.

How to Add Two Variables in Python

Python 3 Code:

This program correctly adds two numbers, num1 and num2, and then prints out the result. Here’s a breakdown of what each line of the code is doing:

num1 = 5.5: This line assigns the value 5.5 to the variable num1.

num2 = 1.15: This line assigns the value 1.15 to the variable num2.

sum = float(num1) + float(num2): This line takes the values of num1 and num2, converts them to float and add them and assigns the result to the variable sum.

print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)): This line uses the print() function to output a string containing the sum of num1 and num2. The format() method is used to insert the values of num1, num2, and sum into the string. The {0}, {1}, and {2} are placeholders for the values of num1, num2, and sum respectively, that will be formatted into the string.

This is a simple program that demonstrates the basic use of variables and the arithmetic operation in python. You can also perform arithmetic operation in the same way as in mathematical expressions.

For instance sum = num1 + num2 would also work and this line will also give the same result.

You will get the output as:

How to  Find the Square Root in Python

Python 3 Code:

This program correctly calculates the square root of a number entered by the user and prints out the result. Here’s a breakdown of what each line of the code is doing:

num = float(input('Enter a number: ')): This line uses the input() function to prompt the user to enter a number, which is then stored as a floating-point value in the variable num.

num_sqrt = num ** 0.5: This line calculates the square root of the number stored in num. It uses the ** operator to raise the value of num to the power of 0.5.

print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)): This line uses the print() function to output a string containing the square root of the number entered by the user. The string contains placeholders for the values of num and num_sqrt which are formatted into the string using the % operator. The %0.3f is used to format the floating-point number, where 0.3 represents the width of the field and f represents the type of number (floating-point).

Note that the math module also provides a function sqrt() which can be used to calculate the square root of a number, this code snippet is a simple example of how you can use mathematical operations in python to calculate square root of a number

When you run the program, it will ask the user to enter a number, and then it will calculate and print the square root of that number rounded upto 3 decimal points.

When you run this program, the following output will be displayed on the console:

When the program is run, it will first prompt the user to enter a number. Once the user enters a number and press enter, the program will calculate the square root of the number, and then it will print out the result in the following format The square root of 9.000 is 3.000, where 9.000 is the input number and 3.000 is the square root of that number rounded upto 3 decimal points.

As you can see the program is asking user to enter the number, and then it’s printing the square root of that number rounded upto 3 decimal points.

How to Calculate the Area of a Triangle in Python

Python 3 Code:

this program correctly calculates the area of a triangle given the lengths of its three sides, and prints out the result. Here’s a breakdown of what each line of the code is doing:

a = float(input('Enter first side: ')), b = float(input('Enter second side: ')), c = float(input('Enter third side: ')): These lines use the input() function to prompt the user to enter the three side lengths of the triangle (a, b, c), which are then stored as floating-point values.

s = (a + b + c) / 2: This line calculates the semi-perimeter of the triangle using the formula (a+b+c)/2, where a, b and c are the sides of the triangle.

area = (s*(s-a)*(s-b)*(s-c)) ** 0.5: This line calculates the area of the triangle using Heron’s formula. Heron’s formula is a formula that can be used to find the area of a triangle when you know the lengths of all three sides. It states that the area of a triangle is equal to the square root of s(s-a)(s-b)(s-c), where s is the semi-perimeter and a,b and c are the sides of the triangle.

print('The area of the triangle is %0.2f' %area): This line uses the print() function to output a string containing the area of the triangle. The %0.2f is used to format the floating-point number, where 0.2 represents the width of the field and f represents the type of number (floating-point).

When you run this program, it will first prompt the user to enter the three side lengths of the triangle (a, b, c), once the user enter the values for the sides the program will calculate the area of the triangle and will produce the following output:

Where 3, 4 and 5 are the sides entered by the user and 6.00 is the area of the triangle rounded upto 2 decimal points. This output is calculated using Heron’s formula and assuming that the sides provided form a valid triangle.

How to Calculate the Area of a Circle in Python

Python Code:

This program correctly calculates the area of a circle, given the radius and prints out the result. Here’s a breakdown of what each line of the code is doing:

def findArea(r):: This line defines a function named findArea, which takes a single parameter r, which represents the radius of the circle.

PI = 3.142: This line assigns a value of 3.142 to the constant PI.

return PI * (r*r): This line calculates the area of a circle with the given radius and returns the value to the calling function. It uses the formula for the area of a circle, which is PI * r^2. Where PI is a mathematical constant and r is the radius of the circle.

num=float(input("Enter r value:")): This line prompts the user to enter the value of the radius of the circle and

stores the input as a floating point value in the variable num using input() function.

  1. print("Area is %.6f" % findArea(num)): This line calls the findArea() function with the value of num as the argument, calculates the area of the circle, and stores the result in a variable. The print() statement is then used to print the area rounded upto 6 decimal points by using the string formatting %.6f.

When you run the program, it will prompt the user to enter the value of the radius of the circle, then it will calculate and print the area of the circle rounded upto 6 decimal points.

Example output:

Here, user enters 5 as the radius of the circle and the program calculates the area of the circle with radius 5, and prints the area rounded upto 6 decimal points which is 78.539816.

How to Solve Quadratic Equation in Python

This program correctly solves the quadratic equation ax^2 + bx + c = 0, given the values of the coefficients a, b and c, and prints out the solutions. Here’s a breakdown of what each line of the code is doing:

import cmath: This line imports the cmath module, which provides support for complex number arithmetic.

a = float(input('Enter a: ')), b = float(input('Enter b: ')), c = float(input('Enter c: ')) : These lines use the input() function to prompt the user to enter the values of the coefficients (a, b, and c) which are then stored as floating-point values.

d = (b**2) - (4*a*c): This line calculates the discriminant using the formula b^2 – 4ac, where b, a and c are the coefficients of the equation.

sol1 = (-b-cmath.sqrt(d))/(2*a) , sol2 = (-b+cmath.sqrt(d))/(2*a): These lines use the quadratic formula to calculate the two solutions for the equation. The quadratic formula is (-b+-√(b^2-4ac))/2a. The cmath.sqrt() is used to get the square root of the discriminant. Using the cmath.sqrt instead of the math.sqrt returns complex numbers if the discriminant is negative.

print('The solution are {0} and {1}'.format(sol1,sol2)): This line uses the print() function to output the two solutions of the quadratic equation which are stored in variables sol1 and sol2.

The program takes 3 coefficients as input and it will return the two roots of the quadratic equation. It is important to note that, when the discriminant is negative, the solutions will be complex numbers, which will be represented in the form of a + bj, where a and b are real numbers, and j represents the square root of -1.

How to Swap Two Variables in Python

This program correctly swaps the values of two variables, x and y, and then prints out the new values of the variables. Here’s a breakdown of what each line of the code is doing:

x = input('Enter value of x: ') and y = input('Enter value of y: '): These lines use the input() function to prompt the user to enter the values of x and y, which are then stored as strings.

temp = x: This line assigns the value of x to a temporary variable temp.

x = y and y = temp: These lines swap the values of x and y by assigning the value of y to x and the value of the temporary variable to y.

print('The value of x after swapping: {}'.format(x)) and print('The value of y after swapping: {}'.format(y)): These lines use the print() function to output the new values of the variables x and y after the swap. The .format() method is used to insert the values of x and y into the string.

This program uses a temporary variable to swap the values of x and y. This is the most common way to swap values of two variables. This method is not limited to swapping integers or floats, but also it can be used with string, or any other datatype.

When you run this program, it will prompt the user to enter the values of x and y, and then it will swap the values of the two variables and produce the following output:

Here, user entered 5 for x and 10 for y, the program swaps the value of x and y, so now the value of x is 10 and the value of y is 5. These values will be displayed as the output of the program.

How to Generate a Random Number in Python

This program generates a random integer between 0 and 100 (inclusive) and prints it out. Here’s a breakdown of what each line of the code is doing:

import random: This line imports the random module, which provides a suite of functions for generating random numbers.

print(random.randint(0,100)): This line generates a random integer between 0 and 100 (inclusive) using the random.randint() function, and then it uses the print() function to output the result. random.randint(0,100) will return a random integer between 0 and 100.

Keep in mind that the numbers generated by this function are determined by a starting seed, which you can set with random.seed() if you want to obtain the same sequence of random numbers again.

The output of this program will be a single random integer between 0 and 100 (inclusive) each time the program is executed. For example, some possible outputs could be:

How to Convert Kilometers to Miles in Python

Yes, this program correctly converts a distance given in kilometers to miles, and prints out the result. Here’s a breakdown of what each line of the code is doing:

kilometers = float(input("Enter value in kilometers")): This line prompts the user to enter a distance in kilometers, which is then stored as a floating-point value in the variable kilometers using the input() function.

conv_fac = 0.621371: This line assigns a value of 0.621371 to the variable conv_fac, which represents the conversion factor from kilometers to miles.

miles = kilometers * conv_fac: This line calculates the equivalent distance in miles by multiplying the distance in kilometers by the conversion factor.

print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles)): This line uses the print() function to output a string containing the original distance in kilometers and the equivalent distance in miles. The %0.3f is used to format the floating-point numbers, where 0.3 represents the width of the field and f represents the type of number (floating-point).

When you run this program, it will prompt the user to enter a distance in kilometers, and then it will convert it to miles using the conversion factor and produce the following output:

Here, user entered 10 for the distance in kilometers, the program converts the kilometers to miles using the conversion factor and displays the output rounded upto 3 decimal places. Keep in mind that the output will be different each time depending on the value entered by user.

 How to Convert Celsius To Fahrenheit in Python

this program correctly converts a temperature given in celsius to fahrenheit, and prints out the result. Here’s a breakdown of what each line of the code is doing:

celsius= float(input("Enter value in celsius")): This line prompts the user to enter a temperature in celsius, which is then stored as a floating-point value in the variable celsius using the input() function.

fahrenheit = (celsius * 1.8) + 32: This line calculates the equivalent temperature in fahrenheit by using the formula (C * 1.8) + 32, where C is the temperature in celsius.

print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)): This line uses the print() function to output a string containing the original temperature in celsius and the equivalent temperature in fahrenheit. The %0.1f is used to format the floating-point numbers, where 0.1 represents the width of the field and f represents the type of number (floating-point).

The program prompts the user to enter the temperature in celsius, and then it converts it to fahrenheit using the conversion factor and displays the output rounded upto 1 decimal place.

When you run this program, it will prompt the user to enter a temperature in celsius, and then it will convert it to fahrenheit using the conversion formula and produce the following output:

Here, user entered 20 for the temperature in celsius, the program converts the celsius to fahrenheit using the conversion formula and displays the output rounded upto 1 decimal places. Keep in mind that the output will be different each time depending on the value entered by user.

How to Find the Sum of Numbers in a List in Python

Example Code:

This program is a simple implementation of a function in Python that calculates the sum of elements in a given array.

The program defines a function called _sum() that takes in two arguments, an array arr and an integer n. The function uses the built-in sum() function in Python to find the sum of all the elements in the array arr.

The driver function creates an empty array called arr and then assigns a list of integers to it (120, 30, 24, 5). The program then calculates the length of the array using the len() function and assigns it to the variable n.

It then calls the _sum() function, passing in arr and n as arguments. The function then finds the sum of elements of array and assigns to variable ans.

Finally, the program uses the print() function to display the sum of the elements in the array. The output of the program will be a single line of text:

In this example, the _sum(arr, n) is calling the sum() function with arr as argument and returning the sum of all the elements in the array, which is 179 and it is then printed using the print statement.

How to to Check if a Number is Positive, Negative or 0 in Python

This program takes a single input from the user, which is expected to be a decimal number (float). It then uses an if-elif-else statement to determine whether the number is positive, zero, or negative.

The program starts by using the input() function to prompt the user to enter a number, which is then assigned to the variable num. The float() function is used to convert the user’s input into a floating-point number.

The program then uses an if-elif-else statement to check the value of num against several conditions. The if statement checks whether num is greater than 0. If it is, the program will print the message “Positive number” to the console. The elif statement that follows checks whether num is equal to 0, and if it is, the program will print the message “Zero” to the console. If none of these conditions are met, the program will execute the code in the else block, which will print the message “Negative number” to the console.

The output of the program will depend on the input provided by the user, if user enters -5, then the output will be:

If user enters 5, the output will be:

If user enters 0, the output will be:

The program checks for the user input number if it is greater than 0, equal to zero or less than 0. Based on the input, it will print the appropriate output as Positive number, Zero or Negative number.

How to Check if a Number is Odd or Even in Python

This program takes a single input from the user, which is expected to be an integer. It then uses an if-else statement to determine whether the number is even or odd.

The program starts by using the input() function to prompt the user to enter a number, which is then assigned to the variable num. The int() function is used to convert the user’s input into an integer.

The program then uses an if-else statement to check the value of num against a single condition. The condition is checking whether num % 2 is equal to 0 or not. The modulus operator % returns the remainder after division, so num % 2 will give a remainder of 0 if num is even, and a remainder of 1 if num is odd.

If the remainder is 0, the program will print the message “{0} is Even” to the console. If the remainder is 1, program will print the message “{0} is Odd” to the console. This is done by using string formatting and the format() method to substitute the value of num into the placeholders ({0}) in the string.

The output of the program will depend on the input provided by the user. If user enters 4, the output will be

If user enters 5, the output will be

This program is using simple mathematical logic of dividing a number by 2, if it gives a remainder of zero then it is an even number otherwise it is an odd number. Using input() function, it is taking input from the user and then using if-else statements it is printing the output if the number is even or odd.

How to Check Leap Year in Python

This program takes an input year from the user and checks whether it is a leap year or not.

A leap year is a year that is divisible by 4, except for end-of-century years which must be divisible by 400. So, this program uses the modulo operator (%) to check if the year is divisible by 4, 100, and 400.

The first if statement checks if the year is divisible by 4, using the modulo operator. If it is, then the program goes to the next step.

The second if statement checks if the year is divisible by 100. If it is, the program goes to the next step, otherwise it prints that the input year is a leap year.

The third and final if statement checks if the year is divisible by 400. If it is, then the program prints that the input year is a leap year. If not, then it prints that it is not a leap year.

For example, if the user enters the year 2000, the program would output: “2000 is a leap year” 2000 is divisible by 4, and by 100, and by 400.

If the user enters the year 1999, the program would output: “1999 is not a leap year” 1999 is divisible by 4 but not divisible by 100.

It is important to note that this program does not check for negative values of year or for years before the gregorian calender.

The output of this program would depend on the input provided by the user. When the program runs, it prompts the user to enter a year and it will check whether the year is a leap year or not. It will then output a message stating whether the year is a leap year or not based on the results of the calculations performed in the if-else statements.

Example:

Input: Enter a year: 2000

Output: 2000 is a leap year

Another example: Input: Enter a year: 1999

Output: 1999 is not a leap year

Note that this program does not check for invalid input such as negative numbers, letters or other special characters. It will crash for such inputs. If you want the program to handle invalid input and give a proper error message, you can put it inside try-except block or use input validation method to check for valid inputs.

 How to Find the Largest Among Three Numbers in Python

This program takes three input numbers from the user and then uses if-elif-else statements to determine which of the three numbers is the largest.

The program starts by asking the user to input three numbers, which are then stored in the variables num1, num2, and num3.

The first if statement checks if num1 is greater than or equal to num2 and also greater than or equal to num3. If both conditions are true, then the variable largest is set to num1.

The second elif statement checks if num2 is greater than or equal to num1 and also greater than or equal to num3. If both conditions are true, then the variable largest is set to num2.

The else statement is executed if both if and elif conditions are false, which means that num3 is the largest number.

Then the program prints a message with the largest number along with all input numbers.

For example, if the user enters 3, 4, and 2 as the three numbers, the program would output: “The largest number between 3.0 , 4.0 and 2.0 is 4.0”

It is important to note that the program input is not validating the inputs, and the program will fail if non-numeric values are entered and the input is expected to be float but if the user enters the number in int format it will also fail.

If you would like to handle such cases then you can put the code inside try-except block and check for valid inputs using input validation method.

The output of this program would depend on the input provided by the user.

When the program runs, it prompts the user to enter three numbers, and it then uses if-elif-else statements to determine which of the three numbers is the largest.

It will then output a message with the largest number along with the input numbers.

Example:

Input: Enter first number: 45 Enter second number: 67 Enter third number: 32

Output: The largest number between 45.0 , 67.0 and 32.0 is 67.0

Another example:

Input: Enter first number: 12 Enter second number: 7 Enter third number: 14

Output: The largest number between 12.0 , 7.0 and 14.0 is 14.0

As previously noted, the program does not check for invalid input such as letters or special characters, and it will fail if non-numeric input are provided. If you’d like the program to handle these cases, you can put the code inside try-except block and check for valid inputs using input validation method.

How to Check Prime Number in Python

This code prompts the user to enter a number, and then uses a series of conditions to determine whether the number is prime or not.

First, it checks if the input number is greater than 1, because prime numbers are greater than 1. If the number is less than or equal to 1, it immediately prints “is not a prime number” and exits the script.

If the number is greater than 1, the code enters a for loop that iterates over a range of numbers from 2 to (num-1).

Inside the loop, it checks if the input number is divisible by the current loop variable (i.e., if (num % i) == 0). If the remainder is 0, it means that the number is divisible by the current loop variable and is not prime, so it prints “is not a prime number” and the factor that the number is divisible by. After this it break out of the loop

If the loop completes without finding any factors, it means that the number is prime, so it prints “is a prime number”.

The output of the program depends on the input number that the user enters. If the user enters a prime number, the output will be “X is a prime number” (where X is the input number). If the user enters a composite number, the output will be “X is not a prime number” and it will also show the first factor which the number is divisible by.

For example, if the user enters the number 17, the output will be “17 is a prime number” because 17 is a prime number and is only divisible by 1 and 17. If user enters the number 15, the output will be “15 is not a prime number” and it will also show the first factor which is divisible by “3 times 5 is 15”

How to Print all Prime Numbers in an Interval in Python

This code prompts the user to enter two numbers, the lower and upper range for an interval, and then uses a nested loop structure to find and display all the prime numbers within that interval.

  • The first part of the code prompts the user to enter a lower and upper range for the interval, and assigns these values to the variables lower and upper respectively.
  • Next, it prints a message indicating the range of numbers being searched for prime numbers.
  • The outer loop iterates over a range of numbers from lower to upper, assigning each number to the variable num
  • Inside this loop, it checks if the current number is greater than 1 (as prime numbers are greater than 1)
  • Then there’s an inner loop, which runs from 2 to (num-1), and checks if the current number is divisible by any of the numbers in that range using if (num % i) == 0. If the remainder is 0, it means that the number is divisible by the current loop variable and is not prime, so it breaks out of the inner loop.
  • If the inner loop completes without finding any factors, it means that the number is prime, so it prints the number.

The output of the program will be all the prime numbers between the lower and upper range that the user has entered. The prime numbers are separated by newline. The user can change the values of lower and upper to get a different result.

The output of the program will be all the prime numbers between the lower and upper range that the user has entered. The prime numbers are separated by newline.

For example, if the user enters the lower range as 10 and upper range as 50, the output will be:

It should be noted that the program does not validate if the lower value is smaller than the upper value, meaning that if a user enters the upper value smaller than the lower value, the program will give an empty output.

How to Find the Factorial of a Number in Python

This code prompts the user to enter a number, and then uses a series of conditions and a loop to calculate the factorial of the input number.

  • First, it prompts the user to enter a number, and assigns the value to the variable num.
  • Next, it initializes a variable factorial to 1
  • The code uses an if-elif-else statement to check if the input number is negative, zero, or positive.
  • If the number is negative, the code prints a message saying “factorial does not exist for negative numbers”
  • If the number is zero, the code prints “The factorial of 0 is 1”
  • If the number is positive, the code enters a for loop that iterates over a range of numbers from 1 to (num + 1)
  • Inside the loop, it multiplies the current value of factorial with the current loop variable and assigns the result back to factorial. This way it will keep on calculating the factorial for each iteration
  • After the loop completes, it prints a message indicating the factorial of the input number.

The output of the program depends on the input number entered by the user.

  • If user entered a positive number, it will print the factorial of that number
  • If user entered 0, it will print “The factorial of 0 is 1”
  • If user entered negative number, it will print “factorial does not exist for negative numbers”

For example, if the user enters the number 5, the output will be: “The factorial of 5 is 120”

How to Display the multiplication Table in Python

This code prompts the user to enter a number (num), and then uses a for loop to generate and display the multiplication table of the entered number.

  • The first line prompts the user to enter a number and assigns it to the variable num
  • The code then enters a for loop that iterates over a range of numbers from 1 to 11 using range(1, 11)
  • Inside the loop, it calculates the product of num and the current loop variable (i) using the * operator and assigns the result to num*i
  • Then it prints the value of num, the current value of the loop variable i, and the product num*i using string concatenation.

The output of the program depends on the input number that the user enters. If the user enters the number 5, the output will be:

It shows the multiplication table of 5. The output shows num and the loop variable separated by ‘x’, and the product of num and the loop variable separated by ‘=’. If the user enters any other number, it will show the corresponding multiplication table.

How to Print the Fibonacci sequence in Python

This code prompts the user to enter a number (nterms), and then uses a series of conditions and a while loop to generate and display the Fibonacci sequence up to the nterms-th term.

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1.

  • First, it prompts the user to enter a number (nterms)
  • Next, it initializes three variables: n1 and n2 to 0 and 1 respectively, and count to 0. These variables are used to generate the Fibonacci sequence.
  • The code then uses an if-elif-else statement to check if the input number is positive or zero or negative.
  • If the number of terms is zero or negative, it prints “Please enter a positive integer”
  • If the number of terms is 1, it prints the first number of the sequence (0)
  • If the number of terms is greater than 1, it enters a while loop, which will continue until count is equal to nterms
  • Inside the loop, it prints the current value of n1 and add n1 and n2 and assign the value to nth
  • then it updates the values of n1 and n2 with the value of nth
  • Finally, it increments the value of count by 1
  • The loop will repeat until count is equal to nterms, and the program will print the first nterms numbers of the Fibonacci sequence.

The output of the program depends on the input number that the user enters. If the user enters the number 5, the output will be:

It shows the Fibonacci sequence of upto 5 numbers, Separated by comma. If user enters 1, it will print “Fibonacci sequence upto 1 : 0” If user enters 0 or negative number, it will print “Please enter a positive integer”

How to Check Armstrong Number in Python

This is the same code that I explained earlier. It prompts the user to enter a number and then uses a while loop to check if the number is an Armstrong number or not. An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits.

To check if the number is Armstrong or not, it first calculates the number of digits of the input number using a while loop that divides the number by 10 and counts the number of iterations. After that, it checks if the number is equal to the sum of each digit raised to the power of the number of digits. If the number is equal to this sum, it is an Armstrong number, otherwise, it’s not.

For example, if the user enters 153, the output will be “153 is an Armstrong number” because 1^3 + 5^3 + 3^3 = 153. If the user enters 123, the output will be “123 is not an Armstrong number”

The output of the program depends on the input number that the user enters.

  • If the user enters 153, the output will be “153 is an Armstrong number”
  • If the user enters 123, the output will be “123 is not an Armstrong number”

The output will be a string, which is the concatenation of the input number and whether it’s an Armstrong number or not. So the output will be of string type showing the input number and whether it is Armstrong or not, depending on the input number given by the user.

How to Find Armstrong Number in an Interval in Python

This code prompts the user to enter two numbers, lower and upper range and then uses a for loop to check for all the numbers in the range (lower to upper) if they are Armstrong numbers or not.

An Armstrong number is a number that is equal to the sum of its own digits each raised to the power of the number of digits.

First, it prompts the user to enter the lower and upper range of numbers

Then, it enters a for loop that iterates over a range of numbers from lower to upper+1

Inside the loop, it calculates the number of digits of the current number using len(str(num)) and assigns the value to order

Then it initializes a variable sum to 0. This variable will be used to store the sum of the digit raised to the power of the number of digits of the current number

Then it assigns the value of num to temp and enters a while loop that continues until temp is greater than 0.

Inside the loop, it calculates the last digit of the number using the modulus operator (temp % 10) and assigns it to the variable digit

Then, it adds the digit raised to the power of order to sum using the += operator

Finally, it updates the value of temp to remove the last digit using floor division (temp //= 10)

After that, the loop will check for next number in the range and repeat the process for all numbers till upper range.

The output of the program depends on the input number that the user enters for the range. For example, if the user enters lower range as 100 and upper range as 1000, the output will be:

It shows the Armstrong numbers between 100 and 1000. If there are no armstrong numbers in the given range, the program will output nothing.

It’s important to note that this program is not optimized for large range inputs as the running time increases rapidly as the range gets larger. The calculation of the power and the modulus operator can be expensive operations and if the range is very large it can take a long time to finish execution.

How to Find the Sum of Natural Numbers in Python

This code prompts the user to enter a number (num), and then uses a while loop to calculate the sum of all the natural numbers up to that number.

A natural number is a positive integer, 1, 2, 3, 4, 5, 6…

First, it prompts the user to enter a number and assigns it to the variable num

It then uses an if-else statement to check if the number is less than zero

If the number is less than zero, it prints “Enter a positive number”

Else, it initializes a variable sum to 0, which will be used to store the sum of the natural numbers.

Then it enters a while loop that continues until num is greater than 0.

Inside the loop, it adds num to sum using the += operator.

Then it decrements the value of num by 1 using num -= 1

After the loop completes, it prints the sum of natural numbers up to that number

The output of the program depends on the input number that the user enters. It will be an integer that indicates the sum of the natural numbers up to that number.

For example, If the user enters the number 5, the output will be “The sum is 15” (1+2+3+4+5). If the user enters 0, the output will be “The sum is 0”. If the user enters negative number, it will print “Enter a positive number”.

So the output will be a single integer, as well as a string indicating the message that “The sum is” and the number obtained by adding the natural numbers till entered number.

How to Display Powers of 2 Using Anonymous Function in Python

This code prompts the user to enter a number (terms) and then uses the map() function along with a lambda function to calculate the powers of 2 up to the number of terms entered.

The map() function applies a given function to all the items in an input list, and it returns an iterator that generates the output. In this case, the lambda function is used to calculate 2**x, where x is the current value of the input range (0 to terms-1) and 2 is the base number.

The list() function is used to convert the iterator returned by the map() function into a list.

  • First, it prompts the user to enter the number of terms and assigns it to the variable terms
  • It then uses the map() function along with a lambda function to calculate the powers of 2 up to the number of terms entered.
  • The lambda function takes the current value of the input range and raises 2 to the power of that value.
  • Next, the result of the map() function is converted into a list using the list() function and assigned to the variable result
  • Then it enters a for loop that iterates over a range of numbers from 0 to terms-1
  • Inside the loop, it prints the current power of 2 and the corresponding value from the result list

The output of the program depends on the input number that the user enters. For example, If the user enters the number 5, the output will be:

This code uses Anonymous function (lambda) which is a small function without a name. Here lambda function is used as single-use function, without having to explicitly define a function using def.

So the output will be a list of integers with terms numbers showing the power of 2 raised to that term.

How to Find Numbers Divisible by Another Number in Python

This code takes a list of numbers (my_list) and uses the filter() function along with a lambda function to filter out the numbers that are divisible by 15.

The filter() function filters the items of an input list by applying a given function to each item and returns an iterator that generates the output. In this case, the lambda function is used to check if the current item (x) is divisible by 15 (x % 15 == 0). If the current item is divisible by 15, it is included in the output list, otherwise, it’s not.

  • First, it takes a list of numbers and assigns it to the variable my_list
  • It then uses the filter() function along with a lambda function to filter out the numbers that are divisible by 15
  • The lambda function takes the current item of the input list and checks if it is divisible by 15 (x % 15 == 0)
  • Next, the result of the filter() function is converted into a list using the list() function and assigned to the variable result
  • Finally, it prints the final list of numbers that are divisible by 15.

The output of the program will be a list of integers that are divisible by 15 from the given list.

For example, if the input list is [300, 45, 65, 12, 77, 145, 5], the output will be [45, 105, 165, 225, 285].

In this code too, like previous, Anonymous function (lambda) is used, which is a small function without a name. Here lambda function is used as single-use function, without having to explicitly define a function using def.

How to Convert Decimal to Binary, Octal and Hexadecimal in Python

This code prompts the user to enter a decimal number (dec) and uses the built-in functions bin(), oct(), and hex() to convert the decimal number into binary, octal and hexadecimal number systems respectively.

The bin() function takes an integer as an argument and returns a string that represents the binary equivalent of the decimal number. The oct() function takes an integer as an argument and returns a string that represents the octal equivalent of the decimal number. The hex() function takes an integer as an argument and returns a string that represents the hexadecimal equivalent of the decimal number.

  • First, it prompts the user to enter a decimal number and assigns it to the variable dec
  • Then it uses the bin(), oct(), and hex() functions to convert the decimal number into binary, octal, and hexadecimal number systems respectively
  • Next, it prints the decimal value along with its binary, octal, and hexadecimal equivalents

The output of the program will be a decimal number along with its equivalent in binary, octal and hexadecimal number systems

For example, if the input decimal number is 42, the output will be:

Here 0b is prefixed for binary, 0o for octal and 0x for hexadecimal representation.

How to Find ASCII Value of Character in Python

This code prompts the user to enter a character and uses the built-in function ord() to find the ASCII value of that character.

The ord() function takes a character as an argument and returns an integer representing the Unicode code point of that character.

  • First, it prompts the user to enter a character and assigns it to the variable c
  • Then it uses the ord() function to find the ASCII value of that character
  • Next, it prints the ASCII value along with the character by concatenating the string.

The output of the program will be a character along with its ASCII value

For example, if the input character is ‘a’, the output will be:

It takes any character and returns its corresponding ASCII value.

How to Find HCF or GCD in Python

This code prompts the user to enter two numbers and uses a user-defined function computeHCF() to find the highest common factor (H.C.F) of those two numbers.

The computeHCF() function takes two arguments x and y and uses a for loop to iterate over a range of numbers from 1 to the smaller of the two input numbers. Inside the loop, it checks if the current number is a common factor of both input numbers by using the modulus operator %. If a number is a common factor, it assigns it to the variable hcf and continues the loop. Finally, it returns the value of hcf as the H.C.F of the two input numbers.

  • First, it prompts the user to enter two numbers, assigns them to the variables num1 and num2
  • Then it calls the computeHCF() function and pass num1 and num2 as argument to the function
  • Inside the function, it first finds the smaller number and assigns it to smaller
  • Next, it enters a for loop that iterates over a range of numbers from 1 to the smaller of the two input numbers.
  • Inside the loop, it checks if the current number is a common factor of both input numbers. If yes, it assigns it to hcf and continue the loop.
  • After the loop, it returns the value of hcf as the H.C.F of the two input numbers.
  • Finally, it prints the H.C.F of the two numbers

The output of the program will be an integer which is the highest common factor of the two input numbers

How to Find LCM in Python

This code prompts the user to enter two numbers and uses a user-defined function lcm() to find the least common multiple (L.C.M) of those two numbers.

The lcm() function takes two arguments x and y and first it finds the greater number and assigns it to the variable greater. Then, it enters an infinite loop and checks if greater is divisible by both x and y using the modulus operator %. If greater is divisible by both numbers, it assigns it to the variable lcm and breaks the loop. If not, it increments the value of greater by 1 and continues the loop. Finally, it returns the value of lcm as the L.C.M of the two input numbers.

  • First, it prompts the user to enter two numbers, assigns them to the variables num1 and num2
  • Then it calls the lcm() function and pass num1 and num2 as argument to the function
  • Inside the function, it first finds the greater number and assigns it to greater
  • Next, it enters an infinite loop that and check whether greater is divisible by both x and y using the modulus operator %
  • If greater is divisible by both numbers, it assigns it to the variable lcm and breaks the loop.
  • If not, it increments the value of greater by 1 and continues the loop.
  • After the loop, it returns the value of lcm as the L.C.M of the two input numbers.
  • Finally, it prints the L.C.M of the two numbers

The output of

the program will be an integer which is the least common multiple of the two input numbers.

It is worth noting that the L.C.M of two numbers can be found by multiplying the two numbers and then dividing the result by their H.C.F. This way is more efficient than the current implementation.

Additionally, It is also worth noting that this implementation can also be optimised by using mathematical formula for L.C.M, which is LCM(a,b) = (a*b)/hcf(a,b), where hcf is the highest common factor. This way it would not require an infinite loop.

How to Find Factors of Number in Python

This code prompts the user to enter a number and uses a user-defined function print_factors() to find and display the factors of that number.

The print_factors() function takes one argument x and uses a for loop to iterate over a range of numbers from 1 to the input number. Inside the loop, it checks if the current number is a factor of the input number by using the modulus operator %. If a number is a factor, it is printed.

  • First, it prompts the user to enter a number, assigns it to the variable num
  • Then it calls the print_factors() function and passes num as an argument to the function
  • Inside the function, it enters a for loop that iterates over a range of numbers from 1 to the input number.
  • Inside the loop, it checks if the current number is a factor of the input number. If yes, it prints it.
  • After the loop, all factors of the number have been printed.

The output of the program will be a list of integers, the factors of the input number.

How to Make a Simple Calculator in Python

This code creates a simple calculator that can perform four basic arithmetic operations: addition, subtraction, multiplication, and division.

The program defines four functions: add(), subtract(), multiply(), and divide(), each function takes two arguments, performs a specific arithmetic operation and returns the result. The program then prompts the user to select an operation from a menu of options using a series of print statements.

Once the user has selected an operation, the program prompts the user to enter two numbers, then uses an if-elif block to determine which operation the user selected, and then calls the appropriate function, passing the user-entered numbers as arguments.

The output of the program will be a simple statement with the result of the arithmetic operation applied on the two numbers entered by the user.

For example, if the user inputs “1” as the choice, and “5” and “6” as the two numbers, the program will output “5 + 6 = 11”. And if the user inputs 4 and 3 as the two numbers and divide as the option it will print the division of 4 and 3 , 4/3.

In case if the user inputs any other value then 1,2,3 and 4 it will print Invalid input, as the input is not valid and not present in the options provided to the user.

How to Display Calendar in Python

This code uses the calendar module in Python to display the calendar of a given month of a given year. The code first prompts the user to enter the year and month for which they want to see the calendar, then it stores those values in the variables yy and mm.

The calendar.month() function is then used to display the calendar. This function takes two arguments: the year and the month, and it returns a multi-line string that represents the calendar for that month. The returned string is then passed to the print() function to display the calendar on the screen.

The calendar.month() function is responsible for drawing the calendar. This function will return the month’s calendar as a multi-line string, for the given year and month, ready for printing.

For example, if the user inputs “2022” as the year and “6” as the month, the program will output a calendar for the month of June in the year 2022, something similar to this

It could be used to generate the calendar of any month and any year which the user wants to see.

How to Display Fibonacci Sequence Using Recursion in Python

This program uses a recursive function called recur_fibo(n) to generate the Fibonacci sequence. The function takes an integer argument n which represents the number of terms to be generated in the sequence.

The function checks if the input value of n is less than or equal to 1, if so, it returns the value of n as the first and second terms of the Fibonacci sequence are 0 and 1 respectively. If n is greater than 1, the function calls itself with the values (n-1) and (n-2) as arguments and returns the sum of these recursive calls.

The program then takes user input for the number of terms to be generated in the Fibonacci sequence. The program checks if the input is a positive integer, if not it prompts the user to enter a positive integer. If the input is valid the program uses a for loop to iterate from 0 to nterms and calls the recur_fibo(i) function at each iteration. Finally it prints the output as Fibonacci sequence

When the program runs, it will prompt the user to enter the number of terms to be generated in the sequence, and then it will display the Fibonacci sequence with that many number of terms. This will be done by calling the function recur_fibo(i) inside the for loop and printing the returned value of the function.

For the output, since program uses recursion, the output will be the Fibonacci sequence. The first two terms will be 0 and 1, and the remaining terms will be the sum of the previous two terms. If you give input as 10, the output will be Fibonacci sequence from 0-9, that is 0,1,1,2,3,5,8,13,21,34.

How to Find Sum of Natural Numbers Using Recursion in Python

The above program uses a recursive function recur_sum(n) to find the sum of natural numbers up to a given number n. The function takes one parameter n which is the upper limit of the natural numbers to be added.

When the program is run, it first prompts the user to enter a number. The entered number is stored in the variable num.

The program checks if the entered number is less than 0, If num is less than 0, it prints a message “Enter a positive number”. If num is greater than 0, it calls the recursive function recur_sum(n) and passes the entered number num as the argument. The function is called recursively until the base case is reached which is when n is less than or equal to 1.

The base case of the function returns the value of n as the sum of natural numbers. In each recursive call, the function adds the current value of n and the previous value returned by the function and returns the result.

Finally, the program prints the final returned value which is the sum of natural numbers up to the entered number.

When the program runs it will prompt user to input a number and the program will return the sum of natural numbers upto that number.

The output of the program will be a single line that shows the sum of natural numbers up to the input number entered by the user. for example, if the user inputs the number 5, the output will be “The sum is 15” because 1 + 2 + 3 + 4 + 5 = 15

How to Find Factorial of Number Using Recursion in Python

This program is used to find the factorial of a given number using recursion. The program takes an input from the user, and assigns it to the variable num.

A function recur_factorial(n) is defined that takes an input n, which is the number for which we are supposed to find the factorial. The function first checks if n is 1, if it is then it returns n as the factorial of n, because the factorial of 1 is 1. If n is not equal to 1, then it returns n multiplied by the factorial of n-1, which is the recursive step.

Then the program checks if the input number is negative, and if it is, it prints an error message. If the input number is 0, it prints that the factorial of 0 is 1. If the input number is positive, it calls the function recur_factorial() on the input number and prints the output.

It will output the factorial of entered number by user in the given format.

The output of the program will be the factorial of the number provided by the user, as long as it’s a positive number. In case of a negative or zero input, the program will print error or special case message respectively.

How to Convert Decimal to Binary Using Recursion in Python

This code is a Python program that converts a decimal number to binary using recursion. The convertToBinary function takes an integer argument n and uses recursion to convert it to binary.

The function works by first checking if n is greater than 1. If it is, the function calls itself with the argument n//2, which is equivalent to n divided by 2 (integer division). The function then uses the modulus operator % to find the remainder when n is divided by 2, which will be either 0 or 1. This remainder is then printed using the print function with the end parameter set to an empty string, which means that the output will not be followed by a newline character.

The program prompts the user to enter a decimal number, which is then passed as an argument to the convertToBinary function. When the function finishes running, the binary equivalent of the decimal number will be printed on the screen.

The output will be the binary representation of the entered decimal number.

How to Add Two Matrices in Python

This code first defines two matrices X and Y as a list of lists. Then a variable result is defined as a list of lists containing three rows and three columns of zeroes. This variable will be used to store the result of the matrix addition.

The program then uses nested loops to iterate through the rows and columns of the matrices. In each iteration of the nested loops, it performs the following action: result[i][j] = X[i][j] + Y[i][j] This adds the element at position i, j in matrix X to the element at position i, j in matrix Y, and assigns the result to the corresponding position in the result matrix.

Finally, the result matrix is printed by iterating over it, and inside the inner loop, each sublist of matrix is printed

Another way of adding two matrix is using numpy. numpy has a function called add() which add two matrices element wise. Here is an example,

In this example, instead of using nested loop the numpy add function is used to add the matrices. Here you can see the simplicity and readability of the code is improved.

This is the result of matrix addition of X and Y element wise. Similarly, in the second code snippet, the result will also be the matrix addition of X and Y element wise and would have the same shape as X and Y.

How to Transpose a Matrix in Python

The matrix X is defined as a list of lists, with each inner list representing a row of the matrix.

The program defines a variable result, which is initialized as a list of lists containing two rows and three columns of zeroes. This variable will be used to store the transposed matrix.

The outer loop uses the range function to iterate over the rows of the matrix, with the variable i representing the current row. The inner loop uses the range function to iterate over the columns of the matrix, with the variable j representing the current column.

In each iteration of the nested loops, the program performs the following action: result[j][i] = X[i][j] This takes the element at position i, j in matrix X and assigns it to the position j, i in the result matrix. Because this is done for all elements in the matrix, this operation effectively swaps the rows and columns of the matrix, which is the definition of transposition.

Then the transposed matrix is printed by iterating over it, and inside the inner loop, each sublist of matrix is printed.

So, the output will be the transposed version of X with rows becoming columns and columns becoming rows. It will have same number of rows as the number of columns in the matrix X and same number of columns as the number of rows in the matrix X

How to Multiply Two Matrices in Python

The matrices X and Y are defined as a list of lists, with each inner list representing a row of the matrix.

The program defines a variable result, which is initialized as a list of lists containing three rows and four columns of zeroes. This variable will be used to store the result of the matrix multiplication.

The outermost loop uses the range function to iterate over the rows of matrix X. The variable i represents the current row of matrix X being processed.

The next inner loop uses the range function to iterate over the columns of matrix Y. The variable j represents the current column of matrix Y being processed.

The innermost loop uses the range function to iterate over the rows of matrix Y. The variable k represents the current row of matrix Y being processed.

In each iteration of the nested loops, the program performs the following action: result[i][j] += X[i][k] * Y[k][j] This performs a dot product operation of the current row of matrix X and the current column of matrix Y being processed. And the product is accumulated in result[i][j], which is the same position in the resulting matrix.

Finally, the resulting matrix is printed by iterating over it, and inside the inner loop, each sublist of matrix is printed.

It’s important to note that this code will only work when number of columns of X is equal to the number of rows of Y and the resulting matrix will have shape of number of rows of X and number of columns of Y.

How to Check Whether a String is Palindrome or Not in Python

A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization).

The program first defines a variable my_str which contains the string to be checked. It then makes it suitable for caseless comparison by using the casefold() method.

Next, it creates a new variable rev_str which is the reversed version of my_str by using the reversed() function which returns an iterator, so it needs to be casted to list.

Finally, the program checks if the original string is equal to the reversed string by comparing them as lists. If they are equal, it prints that the string is a palindrome. If they are not equal, it prints that the string is not a palindrome.

In this case, ‘ababa’ will be a palindrome because if you read it in forward or backward direction it will be same. The output will be:

How to Remove Punctuations From a String in Python

This code is a Python program that removes punctuation marks from a given string.

The program first defines a string variable punctuations which contains a list of punctuation marks that are to be removed from the input string.

It then prompts the user to enter a string which is stored in the variable my_str.

The program then creates an empty string no_punct which will be used to store the modified string without punctuation marks.

It then uses a for loop to iterate through each character in my_str. For each character, the program checks if it is present in the punctuations variable. If it is not present, the character is added to the no_punct variable, otherwise it’s skipped.

Finally, the unpunctuated string is displayed using the print function. This will output the input string without any punctuation marks.

This code will remove all the punctuations from the given string. The output will be the string without any punctuation marks.

How to Sort Words in Alphabetic Order in Python

This program takes a string input from the user and breaks it down into a list of words by using the split() method. The resulting list is then sorted alphabetically using the sort() method. The program then iterates through the sorted list and prints each word on a new line.

The program starts by prompting the user to enter a string, which is stored in the variable my_str using the input() function.

Next, the program uses the split() method to break down the input string into a list of words. The split() method, by default, splits a string at whitespace characters, so it separates the words in the input string into a list.

The sort() method is then used to sort the list of words alphabetically.

The program then uses a for loop to iterate through the sorted list of words, and it prints each word on a new line using the print() function.

And the final output of this program is a sorted string words in alphabetically.

How to Illustrate Different Set Operations in Python

This program demonstrates how to perform different set operations in Python. Here’s what the code does:

The program starts by defining three sets: E, N. E is defined as {0, 2, 4, 6, 8} and N is defined as {1, 2, 3, 4, 5}.

Next, the program uses the union operator | to find the union of sets E and N, and the result is stored in the variable Union.

The program then uses the intersection operator & to find the intersection of sets E and N, and the result is stored in the variable Intersection.

Then, the program uses the difference operator - to find the difference between the sets E and N, and the result is stored in the variable Difference.

Finally, the program uses the symmetric difference operator ^ to find the symmetric difference between sets E and N, and the result is stored in the variable Symmetric Difference

The program prints the results of the set operations using the print() function.

The final output of the program will be the Union, Intersection, Difference and symmetric difference of the given two sets.

How to Count the Number of Each Vowel in Python

This program takes a string input from the user, and it uses a dictionary to count the number of each vowel that appears in the input string. Here’s what the code does, step by step:

The program starts by defining a string of vowels called vowels, which contains the characters ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’.

It then prompts the user to enter a string, which is stored in the variable ip_str using the input() function.

Next, the casefold() method is used to convert the input string to lowercase so that the program can perform case-insensitive comparisons.

The program then creates an empty dictionary called count using the fromkeys() method and passing vowels as the argument. This method creates a dictionary containing the vowels as keys and assigns 0 as the value for each key.

Next, the program uses a for loop to iterate through each character in the input string, and it uses an if statement to check if the character is a vowel by checking if it exists in the count dictionary.

If the character is a vowel, it increments the value associated with the key for that vowel in the count dictionary.

The final step, print(count) will give the output of the number of occurrences of each vowel in the input string.

Leave a Comment