Control Structures in Python
#Task 1: Check if a Number is Even or Odd Problem Statement: Write a Python program that:
- Takes an integer input from the user.
- Checks whether the number is even or odd using an if-else statement.
- Displays the result accordingly.
This Python script checks whether a given number is even or odd. Here's a detailed explanation of how it works:
-
Take Input from the User:
num = input("Enter a number : ")
- Prompts the user to enter a number.
- The input is initially read as a string.
-
Convert Input to Integer:
num = int(num)
- Converts the string input to an integer so arithmetic operations can be performed.
-
Check Even or Odd:
if(num % 2 == 0): print(f"num is an even number.") else: print(f"num is an odd number.")
-
Uses the modulus operator
%
to check the remainder whennum
is divided by 2:- If
num % 2 == 0
, the number is even. - Otherwise, it is odd.
- If
-
Prints the appropriate message.
-
Enter a number : 10
num is an even number.
Enter a number : 7
num is an odd number.
input()
for taking user inputint()
for type conversion%
modulus operatorif-else
conditional statementsf-string
formatting for clean output
Task 2: Sum of Integers from 1 to 50 Using a Loop
Problem Statement: Write a Python program that:
- Uses a for loop to iterate over numbers from 1 to 50.
- Calculates the sum of all integers in this range.
- Displays the final sum.
This Python script calculates the sum of all integers from 1 to 50 using a for
loop. Here's a detailed explanation of how it works:
-
Initialize a Sum Variable:
sumTotal = 0
- A variable named
sumTotal
is initialized to0
. - It will be used to keep a running total of the sum.
- A variable named
-
Loop Through Numbers 1 to 50:
for num in range(1, 51): sumTotal = sumTotal + int(num)
-
range(1, 51)
generates numbers from 1 to 50 (note: the end is exclusive, so 51 is not included). -
In each iteration of the loop:
- The current number
num
is added tosumTotal
. int(num)
is used, though it's actually unnecessary sincenum
is already an integer fromrange()
.
- The current number
-
-
Print the Final Sum:
print(f"The sum of numbers from 1 to 50 is : {sumTotal}")
- After the loop completes, the total sum is printed using an f-string.
The sum of numbers from 1 to 50 is : 1275
for
looprange()
function- Integer addition and accumulation
f-string
for formatted output