Python Code Examples
Python Code Examples
Practising coding with Python program exercise with examples is always an excellent approach to improve your programming and logical comprehension, and this post will give you access to the best Python code examples.
There are numerous Python programming examples in the section below. Among the many fundamental ideas covered by these Python code examples such as lists, strings, dictionaries, tuples, sets, and many more. There are several methods for resolving the issue in each example.
Python Code Examples- Add two number program in Python
This program takes two numbers from the user using input() function. The numbers are converted into float to handle both integers and decimals. The result or sum of two numbers is calculated and stored in the variable sum_result. Finally, the result is displayer using an f-string for formated output. You can edit the program to handle integers or other data type as required.
Python Code
# Program to add two numbers
a = float(input("Enter the first number: ")) # Take first number as input
b = float(input("Enter the second number: ")) # Take second number as input
# Calculate the sum
sum_result = a + b
# Display the result
print(f"The sum of {a} and {b} is: {sum_result}")
Code Output
Enter the first number: 5
Enter the second number: 3
The sum of 5.0 and 3.0 is: 8.0
Python Code Examples-Check if a number is even or odd
Step - Identify the problem
An even integer can be divided by two, meaning that the remainder is zero. An odd number cannot be divided by two; that is, the remainder is 1.To find the remainder, we'll utilise the modulus operator %.
Step 2: Request User Input
To get a number from the user, utilise the input() function.
Use int() to convert the input to an integer.
Step 3: Determine whether the number is odd or even.
To find the remaining after dividing a number by two, use the modulus operator %.
The number is even if the remainder is zero.
The number is odd if the remainder is 1.
Step 4: Present the Outcome
Utilise print() to show whether the number is even or odd.
Python Code
# Step 1: Take input from the user
num = int(input("Enter a number: "))
# Step 2: Check if the number is even or odd
if num % 2 == 0:
# Step 3: Display the result for even
print(f"{num} is an even number.")
else:
# Step 4: Display the result for odd
print(f"{num} is an odd number.")
Code Output
Enter a number: 10
10 is an even number.
Enter a number: 15
15 is an odd number.
Python Code Examples-Find the factorial of a number:
Step 1: Determine the Issue
The product of all positive numbers that are less than or equal to a non-negative integer n is its factorial.
n! is used to represent it.
for instance 5! = 5 × 4 × 3 × 2 × 1 = 120,
0! equals 1 by definition.
Step 2: Request User Input
To get a number from the user, utilise the input() function.
Use int() to convert the input to an integer.
Step 3: Deal with Edge Situations
The factorial is 1 if the input integer is either 0 or 1.
Step 4: Determine the Factorial
Multiply all integers from 1 to n using a loop (such as while or for).
Set a variable factorial to 1 at the beginning of the loop and update it at each iteration.
Step 5: Display the result
Use print() to show the factorial of the number.
Python Code
# Step 1: Take input from the user
n = int(input("Enter a non-negative integer: "))
# Step 2: Handle edge cases
if n < 0:
print("Factorial is not defined for negative numbers.")
else:
# Step 3: Initialize factorial to 1
factorial = 1
# Step 4: Calculate factorial using a loop
for i in range(1, n + 1): # Loop from 1 to n (inclusive)
factorial *= i # Multiply factorial by i
# Step 5: Display the result
print(f"The factorial of {n} is: {factorial}")
Code Output
Enter a non-negative integer: 5
The factorial of 5 is: 120
Enter a non-negative integer: 0
The factorial of 0 is: 1
Enter a non-negative integer: -3
Factorial is not defined for negative numbers.
Python Code Examples- Fibonacci sequence in Python
Step 1: Understand the Problem
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones.It starts with 0 and 1.Example: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Step 2: Take Input from the User
Use the input() function to take the number of terms (n) as input from the user.Convert the input to an integer using int().
Step 3: Handle Edge Cases
If the user enters 0, print nothing.If the user enters 1, print only the first term (0).If the user enters 2, print the first two terms (0, 1).
Step 4: Generate the Fibonacci Sequence
Initialise the first two terms of the sequence: a = 0 and b = 1.Use a loop (e.g., for or while) to generate the sequence:Print the current term.Update a and b such that a takes the value of b, and b takes the value of a + b.
Step 5: Display the Result
Print the Fibonacci sequence up to n terms.
Python Code
# Step 1: Take input from the user
n = int(input("Enter the number of terms: "))
# Step 2: Handle edge cases
if n <= 0:
print("Please enter a positive integer.")
elif n == 1:
print("Fibonacci sequence up to 1 term:")
print(0)
else:
# Step 3: Initialize the first two terms
a, b = 0, 1
# Step 4: Print the first two terms
print("Fibonacci sequence up to", n, "terms:")
print(a, end=", ")
print(b, end=", ")
# Step 5: Generate the remaining terms
for _ in range(2, n): # Loop from 2 to n-1 (since first two terms are already printed)
c = a + b # Calculate the next term
print(c, end=", ") # Print the next term
a, b = b, c # Update a and b for the next iteration
Step-by-Step Execution:
The program prompts the user to enter the number of terms.Example: If the user enters 5, the value of n becomes 5.
Edge Case Handling:
If the user enters 0 or a negative number, the program prints: Please enter a positive integer.If the user enters 1, the program prints: 0.If the user enters 2, the program prints: 0, 1.
Fibonacci Sequence Generation:
Initialize a = 0 and b = 1.Print the first two terms: 0, 1.Loop from 2 to n-1:Iteration 1: c = 0 + 1 = 1, print 1, update a = 1, b = 1.Iteration 2: c = 1 + 1 = 2, print 2, update a = 1, b = 2.Iteration 3: c = 1 + 2 = 3, print 3, update a = 2, b = 3.
Code Output
Enter the number of terms: 5
Fibonacci sequence up to 5 terms:
0, 1, 1, 2, 3,
Enter the number of terms: 1
Fibonacci sequence up to 1 term: 0
Enter the number of terms: -3
Please enter a positive integer.