Contact

Python Code Examples for Beginners

Unlock the Power of Python with Easy-to-Follow Code Examples! Explore Python code examples with clear outputs and detailed descriptions, making learning a breeze.

Python Code Example No. 1: Print "Hello World!"

Python Code
p = "Hello World!"
print(p)
Output
Hello World!

In this example, the following statement:

p = "Hello World!"

declares a variable named p and assigns the string "Hello World!" to it. In Python, variables are used to store data values. In this case, the data value being stored is the string "Hello World!". The equal sign (=) is the assignment operator, which assigns the value on the right side of the equal sign to the variable on the left side. After this line executes, the variable p holds the value "Hello World!".

And then the following statement:

print(p)

uses the print() function to display the value stored in the variable p. The print() function is a built-in function in Python that outputs text or other data to the console. In this case, it outputs the contents of the variable p, which is the string "Hello World!".

Python Code Example No. 2: Addition of Two Numbers

Python Code
# Input two numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Perform addition
sum_result = num1 + num2

# Display the result
print("The sum of", num1, "and", num2, "is:", sum_result)
Output
Enter the first number: 56
Enter the second number: 76
The sum of 56.0 and 76.0 is: 132.0

Explanation

This Python code snippet demonstrates the addition of two numbers. Let's break it down step by step:

  1. num1 = float(input("Enter the first number: "))
    • The input() function is used to receive user input from the console. The prompt message inside the parentheses informs the user to enter the first number.
    • float() is used to convert the user input (which is initially a string) to a floating-point number. This ensures accurate decimal point calculations.
  2. num2 = float(input("Enter the second number: "))
    • Similar to the previous step, this line prompts the user to input the second number and then converts it to a floating-point number using float().
  3. sum_result = num1 + num2
    • The variables num1 and num2 hold the input numbers.
    • The + operator is used to perform addition. The result is stored in the variable sum_result.
  4. print("The sum of", num1, "and", num2, "is:", sum_result)
    • The print() function is employed to display the result.
    • The output message includes the values of num1 and num2 along with the calculated sum (sum_result).
    • The variables and text are concatenated using commas within the print() function, automatically adding spaces for readability.

By executing this code, users are prompted to input two numbers. The code then adds these numbers and displays the result in a structured and professional manner. This example demonstrates how to receive input, perform calculations, and present the output, showcasing the core functionality of addition in Python.

Python Code Example No. 3: Check Even or Odd Number

Python Code
# Input a number from the user
num = int(input("Enter a number: "))

# Check if the number is even or odd
if num % 2 == 0:
    result = "even"
else:
    result = "odd"

# Display the result
print("The number", num, "is", result)
Output
Enter a number: 79
The number 79 is odd

Explanation

Skipping the explanation of the similar code used in the previous example, here is the step-by-step explanation of this code example.

  1. num = int(input("Enter a number: "))
    • The user input is initially a string, so int() is used to convert it to an integer for numerical operations.
  2. if num % 2 == 0:
    • The % operator calculates the remainder of the division of num by 2.
    • If the remainder is 0, it means the number is even. The if statement checks this condition.
  3. result = "even" and result = "odd"
    • If the number is even, the result variable is assigned the string "even".
    • If the number is odd, the result variable is assigned the string "odd".
  4. print("The number", num, "is", result)
    • The output message includes the entered number (num) and whether it's even or odd (result).

Python Code Example No. 4: Check Prime Number

Python Code
# Input a number from the user
num = int(input("Enter a number: "))

# Check if the number is prime
if num > 1:
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            result = "not a prime"
            break
    else:
        result = "prime"
else:
    result = "not a prime"

# Display the result
print("The number", num, "is", result)
Output
Enter a number: 17
The number 17 is prime

Explanation

  1. if num > 1:
    • Prime numbers are greater than 1, so we exclude numbers less than or equal to 1.
  2. for i in range(2, int(num ** 0.5) + 1):
    • A for loop iterates through numbers from 2 to the square root of num.
    • Checking up to the square root reduces the number of iterations required to determine primality.

Python Code Example No. 5: Check Vowel or Consonant

Python Code
# Input a character from the user
char = input("Enter a character: ").lower()

# Check if the character is a vowel or a consonant
if len(char) == 1:
    if char in "aeiou":
        result = "a vowel"
    elif char.isalpha():
        result = "a consonant"
    else:
        result = "neither a vowel nor a consonant"
else:
    result = "invalid input"

# Display the result
print("The character", char, "is", result)
Output
Enter a character: U
The character u is a vowel

Explanation

  1. char = input("Enter a character: ").lower()
    • .lower() is used to convert the input character to lowercase. This ensures that uppercase input is also considered correctly.
  2. if len(char) == 1:
    • This line checks if the input is a single character.
  3. if char in "aeiou":
    • The in keyword checks if the input character is present in the string "aeiou", which represents the vowels.
    • If the character is in the set of vowels, result is set to "a vowel".
  4. elif char.isalpha():
    • This elif (short for "else if") block checks if the input character is an alphabetic character using the .isalpha() method.
    • If the character is an alphabetic letter and not a vowel, it's considered a consonant. result is set to "a consonant".
  5. else:
    • If the character is not a vowel, not an alphabetic letter, or the input is not a single character, it falls into this else block.
    • In this case, result is set to "neither a vowel nor a consonant".
  6. else: (outside the condition)
    • If the input is not a single character, it's invalid.

Python Code Example No. 6: Check Leap Year

Python Code
# Input a year from the user
year = int(input("Enter a year: "))

# Check if the year is a leap year
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    result = "a leap year"
else:
    result = "not a leap year"

# Display the result
print("The year", year, "is", result)
Output
Enter a year: 2024
The year 2024 is a leap year

Explanation

  1. (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
    • This condition checks whether the year is divisible by 4 and not divisible by 100, or if the year is divisible by 400.

Python Code Example No. 7: Swap Two Numbers

Python Code
# Input two numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Swap the values using a temporary variable
temp = num1
num1 = num2
num2 = temp

# Display the swapped values
print("After swapping:")
print("First number:", num1)
print("Second number:", num2)
Output
Enter the first number: 12
Enter the second number: 67
After swapping:
First number: 67.0
Second number: 12.0

Explanation

  1. temp = num1
    • A temporary variable temp is used to store the value of num1.
  2. num1 = num2
    • The value of num2 is assigned to num1, effectively swapping the value of num1 with the value of num2.
  3. num2 = temp
    • The original value of num1 (stored in temp) is assigned to num2, completing the swap.

Python Code Example No. 8: Find the Largest of Three Numbers

Python Code
# Input three numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Find the largest of the three numbers
largest = max(num1, num2, num3)

# Display the largest number
print("The largest of the three numbers is:", largest)
Output
Enter the first number: 10
Enter the second number: 23
Enter the third number: 54
The largest of the three numbers is: 54.0

Explanation

  1. largest = max(num1, num2, num3)
    • The max() function is used to find the largest among the three numbers (num1, num2, and num3).
    • It returns the maximum value among the arguments.

Python Code Example No. 9: Find Average of n Numbers

Python Code
# Input the value of n from the user
n = int(input("Enter the number of values: "))

# Initialize the sum to calculate the average
total_sum = 0

# Input the values and calculate the sum
for _ in range(n):
    value = float(input("Enter a value: "))
    total_sum += value

# Calculate the average
average = total_sum / n

# Display the average
print("The average of the", n, "values is:", average)
Output
Enter the number of values: 5
Enter a value: 10
Enter a value: 20
Enter a value: 30
Enter a value: 34
Enter a value: 65
The average of the 5 values is: 31.8

Explanation

  1. total_sum = 0
    • The variable total_sum is initialized to store the sum of the input values.
  2. for _ in range(n):
    • A for loop iterates n times, as specified by the user input.
  3. value = float(input("Enter a value: "))
    • Inside the loop, the user is prompted to input a value for each iteration.
    • The input value is converted to a floating-point number using float() for accurate summation.
  4. total_sum += value
    • The input value is added to the total_sum variable.
  5. average = total_sum / n
    • The average is calculated by dividing the total sum by the number of values (n).

Python Code Example No. 10: Find Grade of a Student

Python Code
# Input the score from the user
score = float(input("Enter the score: "))

# Define the grading scale
grade_scale = {
    (90, 100): "A",
    (80, 89): "B",
    (70, 79): "C",
    (60, 69): "D",
    (0, 59): "F"
}

# Determine the grade based on the score
grade = "N/A"
for range_min, range_max in grade_scale:
    if range_min <= score <= range_max:
        grade = grade_scale[(range_min, range_max)]
        break

# Display the grade
print("The grade for the score", score, "is:", grade)
Output
Enter the score: 78
The grade for the score 78.0 is: C

Explanation

  1. grade_scale dictionary
    • A dictionary is defined to map score ranges to corresponding grades.
    • Each key is a tuple representing the minimum and maximum score for a grade range, and the value is the corresponding grade.
  2. for range_min, range_max in grade_scale:
    • A for loop iterates through the keys (score ranges) in the grade_scale dictionary.
  3. if range_min <= score <= range_max:
    • Inside the loop, the code checks if the entered score falls within the current score range.
  4. grade = grade_scale[(range_min, range_max)], break
    • If the score falls within a score range, the corresponding grade is assigned to the grade variable.
    • The loop is then exited using the break statement.

Python Code Example No. 11: Find Factors of a Number

Python Code
# Input the number from the user
number = int(input("Enter a number: "))

# Initialize an empty list to store factors
factors = []

# Find factors of the number
for i in range(1, number + 1):
    if number % i == 0:
        factors.append(i)

# Display the factors
print("Factors of", number, "are:", factors)
Output
Enter a number: 45
Factors of 45 are: [1, 3, 5, 9, 15, 45]

Explanation

  1. factors = []
    • An empty list named factors is initialized to store the factors of the input number.
  2. for i in range(1, number + 1):
    • A for loop iterates through numbers from 1 to the entered number (inclusive).
    • We start from 1 because factors are positive integers.
  3. if number % i == 0:
    • Inside the loop, the code checks if the current i is a factor of the input number.
    • If the remainder of the division of number by i is 0, i is a factor.
  4. factors.append(i)
    • If i is a factor, it is added to the factors list.

Python Code Example No. 12: Find Factorial of a Number

Python Code
# Input the number from the user
number = int(input("Enter a number: "))

# Initialize the factorial
factorial = 1

# Calculate the factorial
for i in range(1, number + 1):
    factorial *= i

# Display the factorial
print("Factorial of", number, "is:", factorial)
Output
Enter a number: 5
Factorial of 5 is: 120

Explanation

  1. factorial = 1
    • The variable factorial is initialized to store the factorial of the input number.
  2. factorial *= i
    • Inside the loop, the code multiplies the current value of factorial by the current value of i.

Python Code Example No. 13: Print Star Pattern

Python Code
# Input the number of rows from the user
num_rows = int(input("Enter the number of rows: "))

# Print the star pattern with space
for i in range(1, num_rows + 1):
    print("* " * i)
Output
Enter the number of rows: 12
* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * * * 
* * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * * 
* * * * * * * * * * * * 

Python Code Example No. 14: Print Diamond Pattern of Stars

Python Code
# Input the number of rows from the user
num_rows = int(input("Enter the number of rows: "))

# Print the upper half of the diamond pattern
for i in range(1, num_rows + 1):
    print(" " * (num_rows - i) + "* " * i)

# Print the lower half of the diamond pattern
for i in range(num_rows - 1, 0, -1):
    print(" " * (num_rows - i) + "* " * i)
Output
Enter the number of rows: 10
         * 
        * * 
       * * * 
      * * * * 
     * * * * * 
    * * * * * * 
   * * * * * * * 
  * * * * * * * * 
 * * * * * * * * * 
* * * * * * * * * * 
 * * * * * * * * * 
  * * * * * * * * 
   * * * * * * * 
    * * * * * * 
     * * * * * 
      * * * * 
       * * * 
        * * 
         * 

Explanation

  1. Printing the upper half of the diamond pattern
    • The first for loop iterates through numbers from 1 to the entered number of rows (inclusive).
  2. Printing the lower half of the diamond pattern
    • The second for loop iterates through numbers from num_rows - 1 down to 1.
  3. print(" " * (num_rows - i) + "* " * i)
    • Inside both loops, the print() function is used to print spaces followed by asterisks.
    • The number of spaces before the asterisks is determined by the difference between the total number of rows (num_rows) and the current row number (i).
    • The number of asterisks in each row is equal to the row number i.

Python Code Example No. 15: Search for an Element in a List

Python Code
mylist = []

print("Enter the size of list:", end=" ")
tot = int(input())

print("Enter", tot, "elements for the list:")
mylist = [input() for _ in range(tot)]

print("\nEnter an element to be searched:", end=" ")
elem = input()

found_positions = []
for i, value in enumerate(mylist):
    if value == elem:
        found_positions.append(i + 1)

if found_positions:
    print("\nElement found at Position:", ", ".join(map(str, found_positions)))
else:
    print("\nElement not found in the list.")
Output
Enter the size of list: 5
Enter 5 elements for the list:
12
23
34
45
56
Enter an element to be searched: 45
Element found at Position: 4

Explanation

  1. mylist = [input() for _ in range(tot)]
    • This uses a list comprehension to read input from the user for tot number of times. Each input element is appended to the mylist using the list comprehension. The _ is used as a placeholder variable since we don't need the loop variable's value (it's not used in the comprehension).
  2. found_positions = []
    • This initializes an empty list called found_positions where the positions of the searched element will be stored.
  3. for i, value in enumerate(mylist):
    • This loop iterates through each element in the mylist along with its index. The enumerate() function provides both the index (i) and value (value) of each element in the list.
  4. if value == elem:
    • This condition checks if the current element (value) is equal to the element to be searched (elem).
  5. found_positions.append(i + 1)
    • If the condition is true, the index (i) plus 1 (to make it human-readable by using 1-based indexing) is appended to the found_positions list.
  6. if found_positions:
    • This checks if any positions were found during the search.
  7. print("\nElement found at Position:", ", ".join(map(str, found_positions)))
    • If positions were found, this line prints the message "Element found at Position:" followed by the positions joined together with commas. The map(str, found_positions) converts each position to a string before joining.
  8. else:
    • If no positions were found, this part of the code is executed.



Sharing is stylish! Gift your friends this awesome read!