0% found this document useful (0 votes)
5 views

Python_Exercises_and_Explanations_Fixed

Uploaded by

satyaswaroop797
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python_Exercises_and_Explanations_Fixed

Uploaded by

satyaswaroop797
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Python Programming Exercises with Detailed Explanations

### Question 20: Find Maximum Number Until 0 is Entered

Code:
```python
max_num = None
while True:
num = int(input("Enter a number (0 to stop): "))
if num == 0:
break
if max_num is None or num > max_num:
max_num = num

print(f"The maximum number entered is {max_num}.")


```

Explanation:
- Starts with `max_num` as `None`.
- Continuously takes input from the user until they enter `0`.
- If `max_num` is `None` (first number) or `num` is greater than the
current `max_num`, updates `max_num`.
- Exits when `0` is entered.

---
### Question 21: Find the Position of a Character in a String

Code:
```python
text = input("Enter a string: ")
char = input("Enter the character to find: ")

for i in range(len(text)):
if text[i] == char:
print(f"The character '{char}' is found at position {i + 1}.")
break
else:
print(f"The character '{char}' is not found in the string.")
```

Explanation:
- Takes a string and character as input.
- Iterates through the string using its index (`i`).
- When the character is found, prints its position (1-based) and exits
the loop with `break`.
- If the loop completes without finding the character, executes the
`else` block.

---

### Question 22: Simple Text-Based Game


Code:
```python
while True:
action = input("Choose an action (move, turn left, turn right, quit):
").lower()
if action == "quit":
print("Exiting the game.")
break
elif action == "move":
print("You moved forward.")
elif action == "turn left":
print("You turned left.")
elif action == "turn right":
print("You turned right.")
else:
print("Invalid action. Try again.")
```

Explanation:
- Runs an infinite loop to take user commands.
- Valid commands (`move`, `turn left`, `turn right`, `quit`) perform
specific actions.
- Exits when the user enters `"quit"`.

---

### Question 23: Calculate the LCM of Two Numbers


Code:
```python
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

greater = max(num1, num2)


while True:
if greater % num1 == 0 and greater % num2 == 0:
print(f"The LCM of {num1} and {num2} is {greater}.")
break
greater += 1
```

Explanation:
- Starts with the larger of the two numbers (`greater`).
- Checks if both `num1` and `num2` divide `greater` without a
remainder.
- If yes, this is the **LCM**, and the loop breaks.
- Otherwise, increments `greater`.

---

### Question 24: Perfect Square Checker

Code:
```python
num = int(input("Enter a number: "))
if int(num**0.5) ** 2 == num:
print(f"{num} is a perfect square.")
else:
print(f"{num} is not a perfect square.")
```

Explanation:
- Checks if the square root of `num` (calculated using `**0.5`) squared
back results in the original number.
- If true, `num` is a perfect square.

---

### Question 25: Identify Perfect Squares in a List

Code:
```python
numbers = list(map(int, input("Enter a list of integers separated by
spaces: ").split()))
perfect_squares = [num for num in numbers if int(num**0.5) ** 2 ==
num]
print(f"The perfect squares in the list are: {perfect_squares}")
```

Explanation:
- Takes a list of numbers from the user.
- Uses list comprehension to check if each number is a perfect
square.
- Displays all perfect squares in the input list.

---

### Question 26: Print Odd Numbers Using `continue`

Code:
```python
limit = int(input("Enter the upper limit: "))
for i in range(1, limit + 1):
if i % 2 == 0:
continue
print(i, end=" ")
```

Explanation:
- Loops through numbers from 1 to `limit`.
- Skips even numbers (`i % 2 == 0`) using `continue`.
- Prints all odd numbers.

---

### Question 27: Skip Multiples of 7

Code:
```python
for i in range(1, 101):
if i % 7 == 0:
continue
print(i, end=" ")
```

Explanation:
- Loops through numbers from 1 to 100.
- Skips numbers that are multiples of 7 using `continue`.

---

### Question 28: Print a Right-Angled Triangle

Code:
```python
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
print("*" * i)
```

Explanation:
- Loops from 1 to `rows`.
- Prints a line of `i` asterisks (`*`).

---
### Question 29: Print a Diamond Shape

Code:
```python
n = int(input("Enter an odd number for the diamond: "))
for i in range(1, n + 1, 2):
print(" " * ((n - i) // 2) + "*" * i)
for i in range(n - 2, 0, -2):
print(" " * ((n - i) // 2) + "*" * i)
```

Explanation:
- First loop creates the top half of the diamond.
- Second loop creates the bottom half.
- Each line centers `*` by adjusting spaces.

---

### Question 30: Pascal's Triangle

Code:
```python
rows = int(input("Enter the number of rows for Pascal's Triangle: "))
triangle = [[1]]
for i in range(1, rows):
row = [1]
for j in range(1, i):
row.append(triangle[i - 1][j - 1] + triangle[i - 1][j])
row.append(1)
triangle.append(row)

for row in triangle:


print(" ".join(map(str, row)).center(rows * 2))
```

Explanation:
- Generates Pascal's Triangle row by row.
- Each element is the sum of the two elements above it.
- Formats and displays the triangle.

You might also like