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:
- 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.
- 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.
- 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.
- 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
1 2 3 |
print('Hello, WORLD!') |
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:
Example 2: Find the Square Root in Python
1 2 3 4 5 6 |
num = int(input('Enter a Number : ')) numSqrt = num ** 0.5 print('The square root of %0.3f is %0.3f'%(num ,numSqrt)) |
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 3: Add 2 numbers in Python
1 2 3 4 5 6 7 8 9 10 |
num1 = 10 num2 = 8.5 # Add two numbers sum = int(num1) + float(num2) # Result Sum print('{0} + {1} = {2}'.format(num1, num2, sum)) |
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 4: Calculate the Average of Numbers in a Given List in Python
1 2 3 4 5 6 7 8 9 |
num=int(input("Enter the count of elements: ")) arr=[] for i in range(0,num): elem=int(input("Enter element: ")) arr.append(elem) avg=sum(arr)/num print("Average of elements in the list",round(avg,2)) |
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 5: Reverse a Given Number in Python
1 2 3 4 5 6 7 8 9 |
num=int(input("Enter number: ")) rev=0 while(num>0): dig=num%10 rev=rev*10+dig num=num//10 print("Reverse of the number:",rev) |
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 6: Exchange the Values of Two Numbers Without Using a Temporary Variable in Python
1 2 3 4 5 6 7 8 |
a=int(input("Enter value of first variable: ")) b=int(input("Enter value of second variable: ")) a=a+b b=a-b a=a-b print("a is:",a," b is:",b) |
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 7: Add two numbers entered by user in Python
1 2 3 4 5 6 |
num1 = input('Enter #1 : ') num2= input('Enter #2 ') sum=float(num1)+float(num2) print("SUM:{0} ".format(sum)) |
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 8: Check if a Number is a Palindrome in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 |
num=int(input("Enter number:")) temp=num rev=0 while(num>0): dig=num%10 rev=rev*10+dig num=num//10 if(temp==rev): print("The number is a palindrome!") else: print("The number isn't a palindrome!") |
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 9: Print an Inverted Star Pattern in Python
1 2 3 4 5 |
num=int(input("Enter number of rows: ")) for i in range (num,0,-1): print((num-i) * ' ' + i * '*') |
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 10: Calculate Area and Perimeter of Rectangle in Python
1 2 3 4 5 6 7 8 |
l=int(input("Length : ")) w=int(input("Width : ")) area=l*w perimeter=2*(l+w) print("Area of Rectangle : ",area) print("Perimeter of Rectangle : ",perimeter) |
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:
1 2 3 4 |
Area of Rectangle : 50 Perimeter of Rectangle : 30 |
Example 11: Calculate Area and Perimeter of Square in Python
1 2 3 4 5 6 7 |
s=int(input("Side : ")) area=s*s perimeter=4*s print("Area of Rectangle : ",area) print("Perimeter of Rectangle : ",perimeter) |
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:
1 2 3 4 |
Area of Rectangle : 25 Perimeter of Rectangle : 20 |
Example 12: Calculate Area and Perimeter of Circle in Python
1 2 3 4 5 6 7 |
r=float(input("Input Radius : ")) area=3.14*r*r perimeter=2*3.14*r print("Area of Circle: ",area) print("Perimeter of Circle: ",perimeter) |
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:
1 2 3 4 |
Area of Circle: 78.5 Perimeter of Circle: 31.4 |
Example 13: Compare Two Numbers in Python
1 2 3 4 5 6 7 8 9 10 |
num1=int(input("Number 1 : ")) num2=int(input("Number 1 : ")) if num1>num2: print("Number1 is greater than Number2") elif num1<num2: print("Number1 is less than Number2") else: print("Number1 is equal to Number2") |
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:
1 2 3 |
Number1 is less than Number2 |
Example 14: Count the Number of Digits in a Number in Python
1 2 3 4 5 6 7 8 |
num=int(input("Enter number:")) count=0 while(num>0): count=count+1 num=num//10 print("The number of digits in the number are:",count) |
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:
1 2 3 |
The number of digits in the number are: 5 |
Example 15: Find the Sum of Digits in a Number
1 2 3 4 5 6 7 |
num=input("Enter a number:") sum=0 for n in num: sum = sum + int(n) print(sum) |
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:
1 2 3 |
15 |
Example 16: Reverse a String in Python
1 2 3 4 5 6 7 8 9 10 11 12 |
# Python Program - Reverse String print("Enter 'x' for exit.") string = input("Enter any string to reverse it: ") if string == 'x': exit() else: revstring = string[::-1] print("\nOriginal String =",string) print("Reversed String =",revstring) |
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:
1 2 3 4 |
Original String = hello Reversed String = olleh |
Example 17: Make a Simple Calculator in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
print("1. Addition") print("2. Subtraction") print("3. Multiplication") print("4. Division") print("5. Exit") choice = int(input("Enter your choice: ")) if (choice>=1 and choice<=4): print("Enter two numbers: ") num1 = int(input()) num2 = int(input()) if choice == 1: res = num1 + num2 print("Result = ", res) elif choice == 2: res = num1 - num2 print("Result = ", res) elif choice == 3: res = num1 * num2 print("Result = ", res) else: res = num1 / num2 print("Result = ", res) elif choice == 5: exit() else: print("Wrong input..!!") |
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:
1 2 3 |
Result = 15 |
Example 18: Check whether a number is prime or not in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
num = int(input('Enter a Number : ')) if num > 1: for i in range(2,num): if (num % i) == 0: print(num,"is NOT a PRIME number") print(i,"times",num//i,"is",num) break else: print(num,"is a PRIME number") else: print(num,"is NOT a PRIME number") |
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 19: Find the Factorial of a Number in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
num = int(input('Enter a Number : ')) factorial = 1 if num < 0: print("Factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) |
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 20: Calculate the Area of a Triangle in Python
1 2 3 4 5 6 7 8 9 10 11 12 |
a = float(input('Enter #1 side: ')) b = float(input('Enter #2 side: ')) c = float(input('Enter #3 side: ')) # calculate s = (a + b + c) / 2 # calculate the area area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The area of the triangle is %0.2f' %area) |
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:
1 2 3 |
The area of the triangle is 6.00 |
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
1 2 3 4 5 6 7 |
# Generate a Random Number in Python # import the random module import random print(random.randint(0,9)) |
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:
1 2 3 |
4 |
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
1 2 3 4 5 6 7 8 9 10 |
kilometers = float(input("Enter value in kilometers : ")) # conversion factor conv_fac = 0.62137 # calculate miles miles = kilometers * conv_fac print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles)) |
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:
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
1 2 3 4 5 6 7 |
celsius = float(input("Enter value in celsius : ")) # calculate fahrenheit fahrenheit = (celsius * 1.8) + 32 print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) |
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:
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
1 2 3 4 5 6 7 8 9 |
num = float(input("Enter a number: ")) if num > 0: print("Positive") elif num == 0: print("Zero") else: print("Negative") |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
Enter a number: 5 Positive Enter a number: 0 Zero Enter a number: -3 Negative |
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
1 2 3 4 5 6 7 |
num = int(input("Enter a number: ")) if (num % 2) == 0: print("{0} is Even".format(num)) else: print("{0} is Odd".format(num)) |
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:
1 2 3 4 5 6 7 8 |
Enter a number: 4 4 is Even Enter a number: 7 7 is Odd |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) |
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
Enter a year: 2000 2000 is a leap year Enter a year: 1900 1900 is not a leap year Enter a year: 2012 2012 is a leap year |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) num3 = float(input("Enter third number: ")) if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print("The largest number between",num1,",",num2,"and",num3,"is",largest) |
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:
1 2 3 4 5 6 |
Enter first number: 5 Enter second number: 2 Enter third number: 7 The largest number between 5 , 2 and 7 is 7 |
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
1 2 3 4 5 6 7 8 9 10 11 12 |
num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: sum = 0 while(num > 0): sum += num num -= 1 print("The sum is",sum) |
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:
1 2 3 4 |
Enter a number: 5 The sum is 15 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# define a function def LCM(x, y): """This function takes two integers and returns the L.C.M.""" # choose the greater number if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print("The L.C.M. of", num1,"and", num2,"is", LCM(num1, num2)) |
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:
1 2 3 4 5 |
Enter first number: 6 Enter second number: 10 The L.C.M. of 6 and 10 is 30 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
X = [[8,7], [10 ,52], [41 ,3]] result = [[0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[j][i] = X[i][j] for r in result: print(r) |
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:
1 2 3 4 |
[8, 10, 41] [7, 52, 3] |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# string of vowels vowels = 'aeiou' # change this value for a different result ip_str = 'Python is an easy to learn, powerful programming language.' # make it suitable for caseless comparisions ip_str = ip_str.casefold() # make a dictionary with each vowel a key and value 0 count = {}.fromkeys(vowels,0) # count the vowels for char in ip_str: if char in count: count[char] += 1 print(ip_str) print(count) |
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:
1 2 3 4 |
python is an easy to learn, powerful programming language. {'a': 4, 'e': 5, 'i': 3, 'o': 3, 'u': 0} |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
my_str = input("Enter a string: ") # breakdown the string into a list of words words = my_str.split() # sort the list words.sort() # display the sorted words print("The sorted words are:") for word in words: print(word) |
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:
1 2 3 4 5 6 7 8 9 |
Enter a string: this is a test string The sorted words are: a is string test this |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# define a function def HCF(x, y): # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print("The H.C.F. of", num1,"and", num2,"is", HCF(num1, num2)) |
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:
1 2 3 4 5 |
Enter first number: 24 Enter second number: 36 The H.C.F. of 24 and 36 is 12 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
res=0.0 for i in range(1, 6): lec=float(input("Enter marks of the #{0} lecture: ".format(i))) res=res+lec avg=res/5 print (avg) if(avg>=90): print("Grade: A") elif(avg>=80 and avg<90): print("Grade: B") elif(avg>=70 and avg<80): print("Grade: C") elif(avg>=60 and avg<70): print("Grade: D") else: print("Grade: F") |
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:
1 2 3 4 5 6 7 8 9 |
Enter marks of the #1 lecture: 95 Enter marks of the #2 lecture: 85 Enter marks of the #3 lecture: 75 Enter marks of the #4 lecture: 65 Enter marks of the #5 lecture: 55 75.0 Grade: C |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
n=int(input("Enter number of rows: ")) a=[] for i in range(n): a.append([]) a[i].append(1) for j in range(1,i): a[i].append(a[i-1][j-1]+a[i-1][j]) if(n!=0): a[i].append(1) for i in range(n): print(" "*(n-i),end=" ",sep=" ") for j in range(0,i+1): print('{0:6}'.format(a[i][j]),end=" ",sep=" ") print() |
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:
1 2 3 4 5 6 7 8 |
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 |
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.