Swap two variables

Swap two variables

EasyBasic Programs · 8 of 40

Write a Python program to interchange (swap) the values of two variables.

Input
a = 10, b = 20
Output
a = 20
b = 10

Approach

  1. Use tuple unpacking a, b = b, a, or a temporary variable.

Solution 1: tuple unpacking

Python
a = 10b = 20 a, b = b, aprint("a =", a)print("b =", b)
Output
a = 20
b = 10

Line by line

Line 4

The right side b, a is evaluated first as the tuple (20, 10) and then unpacked into a and b, so no temporary variable is needed.

Solution 2: temporary variable

Python
a = 10b = 20 temp = aa = bb = tempprint("a =", a, "b =", b)
Output
a = 20 b = 10

Line by line

Lines 4-6

temp keeps the old value of a before it is overwritten. This is how swapping works in most other languages.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Square and cube of a number

Square and cube of a number

EasyBasic Programs · 7 of 40

Write a Python program to print the square and cube of a given number.

Input
num1 = 9
Output
Square = 81
Cube = 729

Approach

  1. Use the power operator : n 2 is the square and n ** 3 is the cube.

Solution

Python
num1 = 9 square = num1 ** 2cube = num1 ** 3print("Square =", square)print("Cube =", cube)
Output
Square = 81
Cube = 729

Line by line

Lines 3-4

** raises a number to a power. num1 * num1 and num1 * num1 * num1 give the same results.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Median of given numbers

Median of given numbers

MediumBasic Programs · 6 of 40

Write a Python program to find the median of given numbers. The median is the middle value after sorting; for an even count it is the average of the two middle values.

Input
[45, 60, 61, 66, 70, 77, 80]
Output
Median: 66

Approach

  1. Sort the numbers.
  2. If the count is odd, take the middle item at index n // 2.
  3. If it is even, average the two middle items.

Solution 1: by hand

Python
numbers = [45, 60, 61, 66, 70, 77, 80]values = sorted(numbers)n = len(values)mid = n // 2 if n % 2 == 1:    median = values[mid]else:    median = (values[mid - 1] + values[mid]) / 2 print("Median:", median)
Output
Median: 66

Line by line

Line 2

sorted() returns a new sorted list, so the original order is kept.

Line 4

For 7 values, 7 // 2 is 3, which is the index of the 4th (middle) item.

Lines 6-9

An odd count has one middle value; an even count averages the two middle values.

Solution 2: statistics module

Python
import statisticsprint(statistics.median([45, 60, 61, 66, 70, 77, 80]))print(statistics.median([3, 1, 4, 2]))
Output
66
2.5

Line by line

Lines 2-3

statistics.median() sorts and handles odd and even counts for you; for [3, 1, 4, 2] it averages 2 and 3.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Average of given numbers

Average of given numbers

EasyBasic Programs · 5 of 40

Write a Python program to find the average of given numbers. Average = sum of the numbers / how many numbers there are.

Input
a = 40, b = 50, c = 30
Output
Average = 40.0

Approach

  1. Add the numbers.
  2. Divide the sum by the count (3).

Solution 1: three variables

Python
a = 40b = 50c = 30 average = (a + b + c) / 3print("Average =", average)
Output
Average = 40.0

Line by line

Line 5

The brackets make Python add first and then divide. Without them, only c would be divided by 3.

Solution 2: any number of values

Python
numbers = [40, 50, 30]average = sum(numbers) / len(numbers)print("Average =", average)
Output
Average = 40.0

Line by line

Line 2

sum() adds every value and len() counts them, so this works for a list of any size.

Note

/ always returns a float, which is why the answer prints as 40.0.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Repeat a string 5 times

Repeat a string 5 times

EasyBasic Programs · 4 of 40

Write a Python program to repeat a given string 5 times.

Input
str1 = "SQATools"
Output
SQAToolsSQAToolsSQAToolsSQAToolsSQATools

Approach

  1. Multiply the string by 5. In Python, string * n repeats the string n times.

Solution 1: the * operator

Python
str1 = "SQATools"result = str1 * 5print(result)
Output
SQAToolsSQAToolsSQAToolsSQAToolsSQATools

Line by line

Line 2

* between a string and an integer repeats the string; no loop is needed.

Solution 2: a loop

Python
str1 = "SQATools"result = ""for _ in range(5):    result += str1print(result)
Output
SQAToolsSQAToolsSQAToolsSQAToolsSQATools

Line by line

Line 2

Start with an empty string.

Lines 3-4

The loop runs 5 times and appends the text each time. _ is used as the loop variable because its value is not needed.

Line 5

Prints the same result as Solution 1.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Multiply two numbers

Multiply two numbers

EasyBasic Programs · 3 of 40

Write a Python program to multiply two numbers.

Input
a = 12, b = 7.5
Output
Product: 90.0

Approach

  1. Multiply the numbers with *.
  2. Print the product.

Solution

Python
a = 12b = 7.5 product = a * bprint("Product:", product)
Output
Product: 90.0

Line by line

Lines 1-2

One value is an int and the other a float.

Line 4

Multiplying an int by a float gives a float, so the result prints as 90.0.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Subtract two integers

Subtract two integers

EasyBasic Programs · 2 of 40

Write a Python program to subtract one integer from another and print the result.

Input
num1 = 75, num2 = 28
Output
75 - 28 = 47

Approach

  1. Store both numbers.
  2. Subtract the second from the first with -.
  3. Print the difference.

Solution

Python
num1 = 75num2 = 28 difference = num1 - num2print(f"{num1} - {num2} = {difference}")
Output
75 - 28 = 47

Line by line

Line 4

- subtracts num2 from num1. The order matters: num2 - num1 would give -47.

Line 5

The f-string fills each {} with the variable’s value, which makes the output read like the calculation.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Add two integers

Add two integers

EasyBasic Programs · 1 of 40

Write a Python program to add two integer values and print the result.

Input
num1 = 30, num2 = 40
Output
Sum of 30 and 40 is 70

Approach

  1. Store the two numbers in variables.
  2. Add them with the + operator.
  3. Print the result with a label.

Solution

Python
num1 = 30num2 = 40 total = num1 + num2print("Sum of", num1, "and", num2, "is", total)
Output
Sum of 30 and 40 is 70

Line by line

Lines 1-2

Two integer variables hold the input values.

Line 4

+ adds the numbers and the result is stored in total, so it has a meaningful name.

Line 5

print() with several values separated by commas puts a space between each one.

Tip

To add numbers typed by the user, convert the text first: num1 = int(input("First: ")).

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Allot a stream from marks

Allot a stream from marks

EasyIf-Else Programs · 64 of 64

Write a Python program that allots a stream: marks above 85 Science, above 70 Commerce, 35 to 70 Arts, below 35 Fail.

Input
88, 72, 50, 20
Output
88 -> Science
72 -> Commerce
50 -> Arts
20 -> Fail
70 -> Arts
35 -> Arts

Approach

  1. Test from the highest band down so every mark lands in exactly one stream.

Solution

Python
def stream(marks):    if marks > 85:        return "Science"    elif marks > 70:        return "Commerce"    elif marks >= 35:        return "Arts"    else:        return "Fail" for m in [88, 72, 50, 20, 70, 35]:    print(m, "->", stream(m))
Output
88 -> Science
72 -> Commerce
50 -> Arts
20 -> Fail
70 -> Arts
35 -> Arts

Line by line

Lines 2-9

Using >= for 35 and falling through from the band above means boundary values such as 70 and 35 are covered. The original ranges (35 < marks < 70) left 35 and 70 with no stream.

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs

Calculator with an operator

Calculator with an operator

MediumIf-Else Programs · 63 of 64

Write a Python program that accepts two numbers and an operator (+, -, *, /) and prints the result.

Input
30, 45, +
Output
30 + 45 = 75
30 * 45 = 1350
9 / 0 = cannot divide by zero
2 % 3 = unknown operator

Approach

  1. Choose the operation with if-elif.
  2. Guard against division by zero.

Solution

Python
def calculate(a, b, op):    if op == "+":        return a + b    elif op == "-":        return a - b    elif op == "*":        return a * b    elif op == "/":        if b == 0:            return "cannot divide by zero"        return a / b    else:        return "unknown operator" for a, b, op in [(30, 45, "+"), (30, 45, "*"), (9, 0, "/"), (2, 3, "%")]:    print(a, op, b, "=", calculate(a, b, op))
Output
30 + 45 = 75
30 * 45 = 1350
9 / 0 = cannot divide by zero
2 % 3 = unknown operator

Line by line

Lines 8-11

A nested if checks for zero before dividing.

Lines 12-13

Any other symbol gets a clear message.

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs