Python

Python 3 Code Examples44 min read

In this article, we offer examples of beginners to teach the Python programming language. The best way to learn a programming language is to examine examples of that programming language.

What is python programming language

Python is a high-level, interpreted programming language that is widely used for web development, data analysis, machine learning, and scientific computing. It is known for its simplicity, readability, and flexibility, which makes it a great language for beginners to learn.




Python has a large and active community of users, which means there are many resources available for learning the language, including online tutorials, books, and forums. It also has a large standard library, which means there are many built-in modules and functions that can be used for common tasks, such as connecting to a database, reading and writing files, and working with data.

Python is used by companies and organizations around the world, including Google, NASA, and the New York Stock Exchange. It is also a popular choice for scientific computing, data analysis, and machine learning, due to the many powerful libraries and frameworks available for these tasks.

Python is generally considered to be a beginner-friendly programming language. Its simple syntax and intuitive structure make it easy to learn, especially for those with little or no programming experience.

There are many resources available for learning Python, including online tutorials, books, and interactive courses. Many of these resources are designed specifically for beginners, and they provide a step-by-step guide to the basics of Python.

That being said, like any programming language, Python does have a learning curve, and it may take some time and practice to become proficient in it. However, many people find it to be a rewarding and enjoyable language to learn, and the skills you gain from learning Python can be applied to a wide range of programming tasks and projects.

Python is a popular programming language for many reasons, including its simplicity, readability, and flexibility. Here is a more detailed explanation of the points you listed:

  1. The program shortens the development process, so it is written faster: Python is known for its simplicity and concise syntax, which makes it faster to write and easier to read than some other programming languages. This can make the development process more efficient, as you can write and test code more quickly.
  2. In contrast to the programming languages ​​above, a separate compiler is not required: Python is an interpreted language, which means that it does not need to be compiled before it is run. This means you can write and run Python code directly, without the need for a separate compiler.
  3. It has both more legible and cleaner codic syntax: Python’s syntax is designed to be easy to read and understand. It uses indentation to denote blocks of code, rather than curly braces or keywords, which can make the code more legible and easier to follow.
  4. Due to this and similar features of Python, large organizations worldwide (such as Google, Yahoo! and Dropbox) always need Python programmers: Python is a popular language for many large companies and organizations, including Google, Yahoo!, and Dropbox. These companies often need Python programmers to develop and maintain their software and systems.

Python 3 Code Examples

Example 1 : Print “Hello world” in Python

This code will print the string “Hello, WORLD!” to the console.

In Python, the print function is used to output text or data to the console. The text or data to be printed is passed as an argument to the print function, which is enclosed in parentheses. In this case, the argument is the string “Hello, WORLD!”, which will be printed to the console when the code is run.For example, if you were to run this code in a Python interpreter or script, the output would be:

Output:

Python Hello World Example
Python Hello World Example

Example 2: Find the Square Root in Python

This code calculates the square root of a number entered by the user. Here is a breakdown of what the code does:

The user is prompted to enter a number using the input function. The user’s input is stored in the num variable as a string.

The int function is used to convert the num string to an integer, so that it can be used in calculations.

The square root of num is calculated using exponentiation (**) with a power of 0.5. The result is stored in the numSqrt variable.

The print function is used to output the square root of num to the console, along with a message. The %0.3f format specifier is used to print the values as floating point numbers with 3 decimal places.

For example, if the user enters the number 16, the output will be:

Output:

Example : Find the Square Root in Python
Example : Find the Square Root in Python

Example 3: Add 2 numbers in Python

This code adds two numbers together and prints the result to the console. Here is a breakdown of what the code does:

Two variables, num1 and num2, are defined and assigned values. num1 is an integer, and num2 is a floating point number.

The int function is used to convert num1 to an integer, and the float function is used to convert num2 to a floating point number. These values are then added together and stored in the sum variable.

The print function is used to output the sum of num1 and num2 to the console, along with a message. The format method is used to insert the values of num1, num2, and sum into the string.

For example, if the code is run, the output will be:

Output:

Example : Add 2 numbers in Python
Example : Add 2 numbers in Python

Example 4: Calculate the Average of Numbers in a Given List in Python

This code calculates the average of a list of numbers entered by the user. Here is a breakdown of what the code does:

The user is prompted to enter the number of elements in the list using the input function. The user’s input is stored in the num variable as a string and converted to an integer using the int function.

An empty list called arr is created.

A for loop is used to iterate num times, and for each iteration, the user is prompted to enter an element using the input function. The element is stored in the elem variable as a string and converted to an integer using the int function. The element is then appended to the arr list.

The sum function is used to calculate the sum of the elements in the arr list, and the result is divided by num to calculate the average. The result is stored in the avg variable.

The print function is used to output the average to the console, along with a message. The round function is used to round the avg value to 2 decimal places.

For example, if the user enters the following elements: 12, 52, 10, 58, etc. the output will be:

Output:

Example: Calculate the Average of Numbers in a Given List in Python
Example: Calculate the Average of Numbers in a Given List in Python

Example 5: Reverse a Given Number in Python

This code reverses a number entered by the user. Here is a breakdown of what the code does:

The user is prompted to enter a number using the input function. The user’s input is stored in the num variable as a string and converted to an integer using the int function.

A variable called rev is initialized to 0. This variable will be used to store the reversed number.

A while loop is used to iterate until num is greater than 0. Inside the loop, the last digit of num is extracted using the modulus operator (%) and stored in the dig variable.

The rev variable is multiplied by 10 and the value of dig is added to it, to shift the digits of rev one place to the left and add the new digit to the right.

The num variable is updated by dividing it by 10 using integer division (//). This removes the last digit of num, so that the loop can continue until num is 0.

After the loop completes, the print function is used to output the reversed number to the console, along with a message.

For example, if the user enters the number 123456, the output will be:

Example : Reverse a Given Number in Python
Example : Reverse a Given Number in Python

Example 6: Exchange the Values of Two Numbers Without Using a Temporary Variable in Python

This code swaps the values of two variables, a and b. Here is a breakdown of what the code does:

The user is prompted to enter the values of a and b using the input function. The user’s input is stored as strings and converted to integers using the int function.

The value of a is added to the value of b and the result is stored back in a.

The value of b is updated by subtracting the original value of a from the new value of a. This leaves the value of b as the original value of a.

The value of a is updated by subtracting the original value of b from the new value of a. This leaves the value of a as the original value of b.

The values of a and b are printed to the console using the print function, along with a message.

For example, if the user enters the values 78 for a and 12 for b, the output will be:

Example : Exchange the Values of Two Numbers Without Using a Temporary Variable in Python
Example : Exchange the Values of Two Numbers Without Using a Temporary Variable in Python

Example 7: Add two numbers entered by user in Python

This code adds two numbers entered by the user and prints the result to the console. Here is a breakdown of what the code does:

The user is prompted to enter two numbers using the input function. The user’s input is stored in the num1 and num2 variables as strings.

The float function is used to convert num1 and num2 to floating point numbers, and then they are added together and the result is stored in the sum variable.

The print function is used to output the sum to the console, along with a message. The format method is used to insert the value of sum into the string.

For example, if the user enters the numbers 7 and 15, the output will be:

Example : Add two numbers entered by user in Python
Example : Add two numbers entered by user in Python

Example 8: Check if a Number is a Palindrome in Python

This code checks if a number entered by the user is a palindrome, which means it reads the same forwards and backwards. Here is a breakdown of what the code does:

The user is prompted to enter a number using the input function. The user’s input is stored in the num variable as a string and converted to an integer using the int function.

The value of num is stored in a temporary variable called temp.

A variable called rev is initialized to 0. This variable will be used to store the reversed version of num.

A while loop is used to iterate until num is greater than 0. Inside the loop, the last digit of num is extracted using the modulus operator (%) and stored in the dig variable.

The rev variable is multiplied by 10 and the value of dig is added to it, to shift the digits of rev one place to the left and add the new digit to the right.

The num variable is updated by dividing it by 10 using integer division (//). This removes the last digit of num, so that the loop can continue until num is 0.

After the loop completes, an if statement is used to check if temp is equal to rev. If it is, a message is printed to the console saying that the number is a palindrome. If it

Output:

Example : Check if a Number is a Palindrome in Python
Example : Check if a Number is a Palindrome in Python

Example 9: Print an Inverted Star Pattern in Python

This code prints a pattern of asterisks to the console. Here is a breakdown of what the code does:

The user is prompted to enter the number of rows for the pattern using the input function. The user’s input is stored in the num variable as a string and converted to an integer using the int function.

A for loop is used to iterate over a range of numbers from num down to 1. The loop variable is called i.

Inside the loop, a string of spaces is printed to the console using the print function. The number of spaces is calculated by subtracting i from num and multiplying the result by a single space character.

After the spaces, another string of asterisks is printed to the console. The number of asterisks is equal to i.

For example, if the user enters the number 8, the output will be:

Example : Print an Inverted Star Pattern in Python
Example : Print an Inverted Star Pattern in Python

Example 10: Calculate Area and Perimeter of Rectangle in Python

This code calculates and prints the area and perimeter of a rectangle to the console. Here is a breakdown of what the code does:

The user is prompted to enter the length and width of the rectangle using the input function. The user’s input is stored in the l and w variables as strings and converted to integers using the int function.

The area of the rectangle is calculated by multiplying l and w together and storing the result in the area variable.

The perimeter of the rectangle is calculated by multiplying 2 by the sum of l and w, and adding the result to l and w. The result is stored in the perimeter variable.

The print function is used to output the area and perimeter of the rectangle to the console, along with a message.

For example, if the user enters the length 5 and the width 10, the output will be:

Example 11: Calculate Area and Perimeter of Square in Python

This code calculates and prints the area and perimeter of a square to the console. Here is a breakdown of what the code does:

The user is prompted to enter the side length of the square using the input function. The user’s input is stored in the s variable as a string and converted to an integer using the int function.

The area of the square is calculated by multiplying s by itself and storing the result in the area variable.

The perimeter of the square is calculated by multiplying 4 by s and storing the result in the perimeter variable.

The print function is used to output the area and perimeter of the square to the console, along with a message.

For example, if the user enters the side length 5, the output will be:

Example 12: Calculate Area and Perimeter of Circle in Python

This code calculates and prints the area and perimeter of a circle to the console. Here is a breakdown of what the code does:

The user is prompted to enter the radius of the circle using the input function. The user’s input is stored in the r variable as a string and converted to a floating point number using the float function.

The area of the circle is calculated by multiplying 3.14 (the approximate value of π) by r and r, and storing the result in the area variable.

The perimeter of the circle (also known as the circumference) is calculated by multiplying 2 by 3.14 and r, and storing the result in the perimeter variable.

The print function is used to output the area and perimeter of the circle to the console, along with a message.

For example, if the user enters the radius 5.0, the output will be:

Example 13: Compare Two Numbers in Python

This code compares two numbers entered by the user and prints a message indicating which one is greater, or if they are equal. Here is a breakdown of what the code does:

The user is prompted to enter two numbers using the input function. The user’s input is stored in the num1 and num2 variables as strings and converted to integers using the int function.

An if statement is used to check if num1 is greater than num2. If it is, a message is printed to the console saying that “Number1 is greater than Number2”.

If num1 is not greater than num2, an elif clause is used to check if num1 is less than num2. If it is, a message is printed to the console saying that “Number1 is less than Number2”.

If num1 is neither greater than nor less than num2, the else clause is executed and a message is printed to the console saying that “Number1 is equal to Number2”.

For example, if the user enters 10 for num1 and 20 for num2, the output will be:

Example 14: Count the Number of Digits in a Number in Python

This code counts the number of digits in a number entered by the user. Here is a breakdown of what the code does:

The user is prompted to enter a number using the input function. The user’s input is stored in the num variable as a string and converted to an integer using the int function.

A variable called count is initialized to 0. This variable will be used to store the count of digits in num.

A while loop is used to iterate until num is greater than 0. Inside the loop, the value of count is incremented by 1.

The num variable is updated by dividing it by 10 using integer division (//). This removes the last digit of num, so that the loop can continue until num is 0.

After the loop completes, the print function is used to output the count of digits to the console, along with a message.

For example, if the user enters the number 12345, the output will be:

Example 15: Find the Sum of Digits in a Number

This code calculates the sum of the digits in a number entered by the user. Here is a breakdown of what the code does:

The user is prompted to enter a number using the input function. The user’s input is stored in the num variable as a string.

A variable called sum is initialized to 0. This variable will be used to store the sum of the digits in num.

A for loop is used to iterate over each character (i.e., digit) in num. The loop variable is called n.

Inside the loop, the int function is used to convert n to an integer and add it to the sum variable.

After the loop completes, the print function is used to output the sum of digits to the console.

For example, if the user enters the number 12345, the output will be:

Example 16: Reverse a String in Python

This code allows the user to enter a string and then prints the reversed version of the string to the console. Here is a breakdown of what the code does:

The user is prompted to enter a string using the input function. The user’s input is stored in the string variable.

An if statement is used to check if the user entered 'x' as the string. If they did, the program exits using the exit function. If the user did not enter 'x', the else clause is executed.

The revstring variable is assigned the reversed version of string using slicing. The slice [::-1] returns a reversed version of the string.

The print function is used to output the original string and the reversed string to the console, along with messages.

For example, if the user enters the string "hello", the output will be:

Example 17: Make a Simple Calculator in Python

This code is a simple calculator that allows the user to perform basic arithmetic operations on two numbers. Here is a breakdown of what the code does:

The program prints a menu of options to the console: addition, subtraction, multiplication, division, and exit.

The user is prompted to enter their choice using the input function. The user’s input is stored in the choice variable as a string and converted to an integer using the int function.

An if statement is used to check if choice is between 1 and 4 (inclusive). If it is, the user is prompted to enter two numbers using the input function. The user’s input is stored in the num1 and num2 variables as strings and converted to integers using the int function.

Inside the if statement, another if statement is used to check the value of choice and perform the appropriate operation on num1 and num2. The result is stored in the res variable and printed to the console using the print function.

If choice is not between 1 and 4, an elif clause is used to check if choice is equal to 5. If it is, the program exits using the exit function.

If choice is not any of the valid options, an else clause is executed and an error message is printed to the console.

For example, if the user enters 1 for choice, 5 for num1, and 10 for num2, the output will be:

Example 18: Check whether a number is prime or not in Python

This code checks if a number entered by the user is a prime number or not. Here is a breakdown of what the code does:

The user is prompted to enter a number using the input function. The user’s input is stored in the num variable as a string and converted to an integer using the int function.

An if statement is used to check if num is greater than 1. If it is, a for loop is used to iterate over the range 2 to num-1. The loop variable is called i.

Inside the loop, an if statement is used to check if num is divisible by i. If it is, a message is printed to the console saying that num is not a prime number and the factors of num. The loop is then exited using the break statement.

If the for loop completes without finding any factors of num, an else clause is executed and a message is printed to the console saying that num is a prime number.

If num is not greater than 1, an else clause is executed and a message is printed to the console saying that num is not a prime number.

For example, if the user enters 127, the output will be:

Example 18: Check whether a number is prime or not in Python
Example 18: Check whether a number is prime or not in Python

Example 19: Find the Factorial of a Number in Python

This code calculates the factorial of a number entered by the user. The factorial of a number is the product of all the positive integers less than or equal to that number. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120. Here is a breakdown of what the code does:

The user is prompted to enter a number using the input function. The user’s input is stored in the num variable as a string and converted to an integer using the int function.

A variable called factorial is initialized to 1. This variable will be used to store the result of the factorial calculation.

An if statement is used to check if num is less than 0. If it is, a message is printed to the console saying that the factorial does not exist for negative numbers.

You may also like: Python format() Examples

If num is not less than 0, an elif clause is used to check if num is equal to 0. If it is, a message is printed to the console saying that the factorial of 0 is 1.

If num is neither less than 0 nor equal to 0, an else clause is executed. A for loop is used to iterate over the range 1 to num+1. The loop variable is called i.

Inside the loop, the factorial variable is updated by multiplying it by i.

After the loop completes, the print function is used to output the result of the factorial calculation to the console, along with a message.

For example, if the user enters 7, the output will be:

Example : Find the Factorial of a Number in Python
Example : Find the Factorial of a Number in Python

Example 20: Calculate the Area of a Triangle in Python

Here is an explanation of the code:

This code calculates the area of a triangle given the lengths of its three sides. It does so using Heron’s formula, which states that the area of a triangle with sides of lengths a, b, and c is:

area = sqrt(s(s – a)(s – b)(s – c))

where s is the semiperimeter of the triangle, given by:

s = (a + b + c) / 2

The code first prompts the user to enter the three sides of the triangle, a, b, and c. It then calculates the semiperimeter of the triangle and uses it, along with the values of a, b, and c, to calculate the area of the triangle using Heron’s formula. Finally, it prints the area of the triangle to the user, with two decimal places of precision.

If you ran this code and entered the values 3, 4, and 5 for the sides of the triangle, the output would be:

This is the area of the triangle with sides of lengths 3, 4, and 5, calculated using Heron’s formula. The area is printed to the screen with two decimal places of precision.

Example 21: Generate a Random Number in Python

This code generates a random integer between 0 and 9 (inclusive). It does so by importing the random module and using the randint() function, which takes two arguments: the lower and upper bounds of the range from which to generate the random integer.

In this case, the code generates a random integer between 0 and 9 (inclusive), and then prints it to the screen.

Here is an example of the output that might be produced by this code:

This output indicates that the program generated the random integer 4. If you ran the program again, it might generate a different random integer.

The random module provides various functions for generating random numbers and selecting random elements from lists and other data structures. You can use these functions to perform tasks such as shuffling a deck of cards, selecting a random element from a list, or simulating the roll of a dice.

Example 22: Convert Kilometers to Miles in Python

This code converts a value from kilometers to miles. It does so by prompting the user to enter a value in kilometers, and then using a conversion factor to calculate the equivalent distance in miles.

The conversion factor used in this code is 0.62137, which is the number of miles in one kilometer. To convert from kilometers to miles, the code multiplies the distance in kilometers by this conversion factor.

Finally, the code prints the original distance in kilometers and the equivalent distance in miles, with three decimal places of precision.

Here is an example of the output that might be produced by this code:

Example 22: Convert Kilometers to Miles in Python
Example 22: Convert Kilometers to Miles in Python

In this example, the user entered a value of 12 kilometers, which was converted to 7.456 miles using the conversion factor. The original value in kilometers and the equivalent value in miles were then printed to the screen.

Example 23: Convert Celsius To Fahrenheit in Python

This code converts a temperature from Celsius to Fahrenheit. It does so by prompting the user to enter a temperature in Celsius, and then using the following formula to calculate the equivalent temperature in Fahrenheit:

Fahrenheit = (Celsius * 1.8) + 32

The code then prints the original temperature in Celsius and the equivalent temperature in Fahrenheit, with one decimal place of precision.

Here is an example of the output that might be produced by this code:

Example 23: Convert Celsius To Fahrenheit in Python
Example 23: Convert Celsius To Fahrenheit in Python

In this example, the user entered a temperature of 45 degrees Celsius, which was converted to 113 degrees Fahrenheit using the conversion formula. The original temperature in Celsius and the equivalent temperature in Fahrenheit were then printed to the screen.

Example 24: Check if a Number is Positive, Negative or 0 in Python

This code determines whether a given number is positive, negative, or zero. It does so by prompting the user to enter a number and then using an if statement to check the value of the number.

If the number is greater than zero, the code prints the message “Positive”. If the number is equal to zero, the code prints the message “Zero”. If the number is less than zero, the code prints the message “Negative”.

Here are some examples of the output that might be produced by this code:

In these examples, the user entered the numbers 5, 0, and -3, respectively. The code correctly identified each of these numbers as positive, zero, and negative, and printed the appropriate message to the screen.

Example 25: Check if a Number is Odd or Even in Python

This code determines whether a given number is even or odd. It does so by prompting the user to enter a number, and then using an if statement to check whether the number is evenly divisible by 2.

If the number is evenly divisible by 2, it is even, and the code prints a message stating that the number is even. If the number is not evenly divisible by 2, it is odd, and the code prints a message stating that the number is odd.

Here are some examples of the output that might be produced by this code:

In these examples, the user entered the numbers 4 and 7, respectively. The code correctly identified each of these numbers as even and odd, and printed the appropriate message to the screen.

Note that the code first converts the user input to an integer using the int() function, which ensures that the input is treated as a whole number rather than a decimal value. This is important, as even and odd numbers are determined by whether they are divisible by 2, which is not possible for decimal values.

Example 26: Check Leap Year in Python

This code determines whether a given year is a leap year or not. A leap year is a year that is divisible by 4, except for years that are both divisible by 100 and not divisible by 400.

You may also like: Python if Examples

The code first prompts the user to enter a year. It then uses a series of if statements to check whether the year is a leap year according to the rules described above. If the year is a leap year, it prints a message stating that the year is a leap year. If the year is not a leap year, it prints a message stating that the year is not a leap year.

Here are some examples of the output that might be produced by this code:

In these examples, the user entered the years 2000, 1900, and 2012, respectively. The code correctly identified each of these years as a leap year or not a leap year according to the rules described above.

Example 27: Find the Largest Among Three Numbers in Python

This code determines the largest of three numbers. It does so by prompting the user to enter three numbers, and then using a series of if statements to compare the values of the numbers and determine which one is the largest.

The code first checks whether the first number is greater than or equal to the second number and the third number. If it is, it sets the value of the largest variable to the first number. If the first number is not the largest, the code checks whether the second number is greater than or equal to the first number and the third number. If it is, it sets the value of the largest variable to the second number. If the second number is not the largest, the code sets the value of the largest variable to the third number.

Finally, the code prints a message stating the largest number and the values of the three input numbers.

Here is an example of the output that might be produced by this code:

In this example, the user entered the numbers 5, 2, and 7. The code determined that the largest of these numbers is 7, and printed a message stating this fact.

Example 28: Find the Sum of Natural Numbers in Python

This code calculates the sum of the positive integers up to a given number. It does so by prompting the user to enter a number, and then using a while loop to iterate over the positive integers up to that number and add them together.

The code first checks whether the number entered by the user is positive or negative. If it is negative, the code prints an error message stating that a positive number should be entered. If it is positive, the code initializes a variable called sum to 0 and enters a while loop.

The while loop iterates as long as the value of num is greater than 0. On each iteration, it adds the value of num to the running total in sum and then decrements the value of num by 1. When num becomes 0, the while loop terminates, and the code prints the final value of sum.

Here is an example of the output that might be produced by this code:

In this example, the user entered the number 5. The code calculated the sum of the positive integers up to 5, which is 1 + 2 + 3 + 4 + 5 = 15. It then printed the sum to the screen.

Example 29: Find LCM in Python

This code calculates the least common multiple (LCM) of two integers. The LCM of two integers is the smallest positive integer that is divisible by both integers.

The code defines a function called LCM() that takes two integers as arguments and returns their LCM. The function first determines which of the two integers is greater and stores it in a variable called greater. It then enters an infinite while loop that continues until the LCM is found.

The while loop checks on each iteration whether the value of greater is divisible by both of the input integers. If it is, the value of greater is assigned to the lcm variable and the loop is terminated using the break statement. If greater is not divisible by both integers, the value of greater is incremented by 1 and the loop continues.

After the function definition, the code prompts the user to enter two integers and then calls the LCM() function, passing the user-entered values as arguments. The function returns the LCM of the two integers, which is then printed to the screen.

Here is an example of the output that might be produced by this code:

In this example, the user entered the numbers 6 and 10. The LCM function calculated the least common multiple of these two numbers, which is 30, and printed it to

Example 30: Transpose a Matrix in Python

This code transposes a matrix, which means that it flips the matrix along its diagonal so that its rows become columns and its columns become rows.

The code defines a matrix X with three rows and two columns, and a matrix result with two rows and three columns. The matrix X is initialized with some values, and the matrix result is initialized with all zeros.

The code then uses two for loops to iterate over the elements of the matrix X. The outer loop iterates over the rows of X, and the inner loop iterates over the columns of X. For each element in X, the code assigns the value of the element to the corresponding element in result, but with the row and column indices swapped.

Finally, the code iterates over the rows of the matrix result and prints each row to the screen.

Here is an example of the output that might be produced by this code:

In this example, the matrix X was transposed to produce the matrix result, which has its rows and columns flipped compared to X.

Example : Count the Number of Each Vowel in Python

This code counts the number of vowels in a given string. It does so by first defining a string of vowels and a string to be analyzed. It then makes a dictionary with each vowel as a key and a value of 0.

The code then iterates over the characters in the string to be analyzed. For each character, it checks whether it is a vowel by checking whether it is a key in the dictionary. If the character is a vowel, the code increments the value of the corresponding key in the dictionary by 1.

Finally, the code prints the original string and the dictionary containing the vowel counts.

Here is an example of the output that might be produced by this code:

In this example, the string “Python is an easy to learn, powerful programming language.” was converted to lowercase and then analyzed to count the number of vowels it contains. The code found 4 occurrences of the vowel ‘a’, 5 occurrences of the vowel ‘e’, 3 occurrences of the vowel ‘i’, 3 occurrences of the vowel ‘o’, and 0 occurrences of the vowel ‘u’.

Example : Sort Words in Alphabetic Order in Python

This code sorts the words in a given string in alphabetical order. It does so by first prompting the user to enter a string and then splitting the string into a list of words using the split() method. It then sorts the list of words using the sort() method. Finally, it iterates over the sorted list of words and prints each word to the screen.

Here is an example of the output that might be produced by this code:

In this example, the user entered the string “this is a test string”. The code split this string into a list of words, sorted the list, and printed the sorted list of words to the screen.

Example : Find GCD in Python

This code calculates the highest common factor (H.C.F.) of two integers. The highest common factor of two numbers is the largest positive integer that is a factor of both numbers.

The code defines a function called HCF that takes two integers as input and returns their highest common factor. The function first determines which of the two input numbers is smaller, and assigns this value to the variable smaller. It then iterates over the integers from 1 to smaller, inclusive, using a for loop.

For each integer in the range, the function checks whether it is a factor of both of the input numbers by using the modulo operator (%). If it is, the function assigns the value of the integer to the variable hcf and breaks out of the loop.

The code then prompts the user to enter two numbers, and passes these numbers as arguments to the HCF function. The function calculates the highest common factor of the two numbers and returns it, and the code prints this value to the screen.

Here is an example of the output that might be produced by this code:

In this example, the user entered the numbers 24 and 36. The HCF function calculated the highest common factor of these two numbers, which is 12, and printed it to the screen.

Example: Take in the Marks of Subjects and Display the Grade in Python

This code calculates the average of a set of five numbers and assigns a letter grade based on the average. It does so by prompting the user to enter the five numbers and storing them in the variable res. It then calculates the average of these numbers by dividing the sum by 5, and assigns the result to the variable avg.

The code then uses an if-elif-else statement to check the value of avg and assign a letter grade based on the following criteria:

  • If avg is greater than or equal to 90, the grade is ‘A’
  • If avg is greater than or equal to 80 but less than 90, the grade is ‘B’
  • If avg is greater than or equal to 70 but less than 80, the grade is ‘C’
  • If avg is greater than or equal to 60 but less than 70, the grade is ‘D’
  • If avg is less than 60, the grade is ‘F’

Finally, the code prints the average and the letter grade to the screen.

Here is an example of the output that might be produced by this code:

In this example, the user entered five marks, which had an average of 75.0. Based on this average, the code assigned the letter grade ‘C’ to the marks.

Example: Print the Pascal’s triangle for n number of rows given by the user in Python

This code generates a triangular pattern of numbers known as a Pascal’s Triangle. Pascal’s Triangle is a triangular array of numbers in which each number is the sum of the two numbers directly above it.

The code first prompts the user to enter the number of rows in the triangle, and then uses a for loop to create a two-dimensional list with the desired number of rows. It initializes the first element of each row to 1, and then uses another for loop to calculate the remaining elements of the row as the sum of the elements above it. Finally, if the number of rows is not 0, it adds a 1 to the end of the row.

The code then uses two more for loops to print the triangle to the screen. The outer loop iterates over the rows of the triangle, and the inner loop iterates over the elements of each row. The code uses the format() method to pad each element with spaces so that they are aligned in a triangular pattern.

Here is an example of the output that might be produced by this code:

In this example, the user entered the number 5, which specifies the number of rows in the triangle. The code generated a Pascal’s Triangle with 5 rows, as shown above.

I hope these will help you when you are coding.

Leave a Comment