0% found this document useful (0 votes)
19 views14 pages

Answer

Uploaded by

Saran Sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views14 pages

Answer

Uploaded by

Saran Sk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 14

Sure!

Below are **Python programming questions and answers** for each of the
following data types:

1. **Integer**
2. **String**
3. **List**
4. **Dictionary**
5. **Boolean**

---

### ✅ 1. Integer

**Question:**
Write a Python program to check whether a given integer is **even or odd**.

**Answer:**

```python
num = int(input("Enter an integer: "))

if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
```

---

### ✅ 2. String

**Question:**
Write a Python program to **count the number of vowels** in a given string.

**Answer:**

```python
string = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0

for char in string:


if char in vowels:
count += 1

print("Number of vowels:", count)


```

---

### ✅ 3. List

**Question:**
Write a Python program to **find the largest number** in a list.

**Answer:**

```python
numbers = [12, 45, 78, 3, 67, 89, 23]
largest = max(numbers)

print("The largest number is:", largest)


```

---

### ✅ 4. Dictionary

**Question:**
Write a Python program to **count the frequency of each character** in a string
using a dictionary.

**Answer:**

```python
string = input("Enter a string: ")
char_count = {}

for char in string:


if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1

print("Character frequency:")
print(char_count)
```

---

### ✅ 5. Boolean

**Question:**
Write a Python program to check if a given number is **both positive and even**.
Use Boolean logic.

**Answer:**

```python
num = int(input("Enter a number: "))

is_positive = num > 0


is_even = num % 2 == 0

if is_positive and is_even:


print("The number is positive and even.")
else:
print("The number is not both positive and even.")
```

---

Would you like more advanced examples or versions for functions, classes, or file
handling too?

Great! Here's a **new set of Python questions and answers** for each data type
(Integer, String, List, Dictionary, Boolean), focusing specifically on using:
* `for` loops
* `while` loops
* `if-else` statements

---

### ✅ **1. Integer**

---

#### **Question 1 (for loop):**

Write a program to print the sum of the first 10 positive integers.

**Answer:**

```python
total = 0
for i in range(1, 21):
total += i

print("Sum of first 20 positive integers:", total)


```

---

#### **Question 2 (while loop):**

Write a program to check if a number is a **prime number**.

**Answer:**

```python
num = int(input("Enter a number: "))
is_prime = True
i = 2

if num <= 1:
is_prime = False
else:
while i < num:
if num % i == 0:
is_prime = False
break
i += 1

if is_prime:
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")
```

---

### ✅ **2. String**

---
#### **Question 3 (for loop + if):**

Write a program to **count uppercase and lowercase letters** in a string.

**Answer:**

```python
string = input("Enter a string: ")
upper = 0
lower = 0

for char in string:


if char.isupper():
upper += 1
elif char.islower():
lower += 1

print("Uppercase letters:", upper)


print("Lowercase letters:", lower)
```

---

#### **Question 4 (while loop + if-else):**

Write a program to reverse a string **using a while loop**.

**Answer:**

```python
string = input("Enter a string: ")
reversed_string = ''
i = len(string) - 1

while i >= 0:
reversed_string += string[i]
i -= 1

print("Reversed string:", reversed_string)


```

---

### ✅ **3. List**

---

#### **Question 5 (for loop + if):**

Write a program to print **all even numbers** from a list.

**Answer:**

```python
numbers = [1, 4, 7, 10, 13, 16, 19]
for num in numbers:
if num % 2 == 0:
print(num)
```
---

#### **Question 6 (while loop + if-else):**

Write a program to calculate the **sum of positive numbers only** in a list.

**Answer:**

```python
numbers = [3, -2, 7, -5, 10, -1]
i = 0
total = 0

while i < len(numbers):


if numbers[i] > 0:
total += numbers[i]
i += 1

print("Sum of positive numbers:", total)


```

---

### ✅ **4. Dictionary**

---

#### **Question 7 (for loop):**

Write a program to print each **key and value** in a dictionary.

**Answer:**

```python
student = {"name": "Alice", "age": 20, "grade": "A"}

for key in student:


print(key, ":", student[key])
```

---

#### **Question 8 (if-else):**

Write a program to check if a key exists in a dictionary.

**Answer:**

```python
person = {"name": "John", "city": "New York", "age": 25}
key = input("Enter a key to check: ")

if key in person:
print(f"The key '{key}' exists. Value: {person[key]}")
else:
print(f"The key '{key}' does not exist.")
```
---

### ✅ **5. Boolean**

---

#### **Question 9 (if-else + Boolean logic):**

Write a program to check if a user is eligible to vote (age >= 18 and citizen ==
True).

**Answer:**

```python
age = int(input("Enter age: "))
citizen = input("Are you a citizen? (yes/no): ").lower() == "yes"

if age >= 18 and citizen:


print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
```

---

#### **Question 10 (while loop + Boolean flag):**

Write a program that keeps asking the user to enter a **positive number** until
they do.

**Answer:**

```python
valid = False

while not valid:


num = int(input("Enter a positive number: "))
if num > 0:
valid = True
print("Thank you! You entered:", num)
else:
print("That's not a positive number. Try again.")
```

---

Would you like similar questions using **functions**, **file handling**, or


**classes** next?

Absolutely! Below are **logical thinking Python problems** (questions only)


organized by data type — focusing on **Integer, String, List, Dictionary, and
Boolean**. These are designed to challenge your **reasoning and problem-solving**
skills a bit more than basic syntax tasks.

Let me know if you'd like the answers as well after trying them out.

---
## 🧠 LOGICAL THINKING PROBLEMS

---

### 🔢 **1. Integer**

#### **Q1. Armstrong Number Checker**

Check whether a number is an **Armstrong number** (e.g., 153 = 1³ + 5³ + 3³).

---

#### **Q2. Reverse Digits Without String Conversion**

Given a positive integer, **reverse its digits** without converting it to a string.

---

#### **Q3. Digital Root**

Keep summing the digits of a number until a **single-digit** number is obtained.

*Example:* 987 → 9+8+7 = 24 → 2+4 = **6**

---

### 🧵 **2. String**

#### **Q4. Anagram Checker**

Write a program to check if two strings are **anagrams** (contain the same
characters in a different order).

---

#### **Q5. Palindrome Ignoring Spaces and Case**

Check if a sentence is a **palindrome** (ignoring spaces, punctuation, and case).

*Example:* "Was it a car or a cat I saw" → Palindrome ✅

---

#### **Q6. Longest Word Finder**

Find the **longest word** in a given sentence.

---

### 📋 **3. List**

#### **Q7. Second Largest Unique Number**

Find the **second largest unique number** in a list without using `sort()`.

---

#### **Q8. Find Missing Number**


A list contains numbers from 1 to 100, but one number is missing. Find it **without
using loops over the full range**.

---

#### **Q9. Remove Duplicates Without Set**

Remove all **duplicate elements** from a list manually (i.e., without using `set()`
or libraries).

---

### 📚 **4. Dictionary**

#### **Q10. Invert a Dictionary**

Given a dictionary, invert it — swap keys and values.

*Example:* `{"a": 1, "b": 2}` → `{1: "a", 2: "b"}`

---

#### **Q11. Most Frequent Value**

Find the **most frequent value** in a dictionary.

---

#### **Q12. Merge Two Dictionaries with Summed Values**

Merge two dictionaries by **adding values of common keys**.

*Example:*

```python
dict1 = {'a': 5, 'b': 2}
dict2 = {'a': 3, 'c': 4}
# Result → {'a': 8, 'b': 2, 'c': 4}
```

---

### ✅ **5. Boolean**

#### **Q13. Truth Table Evaluator**

Ask the user for two boolean values and print the result of:

* AND
* OR
* NOT (on each)
* XOR

---

#### **Q14. Password Strength Checker**

Check if a password is **strong** using Boolean logic:


* At least 8 characters
* Contains a digit
* Contains an uppercase letter
* Contains a symbol

---

#### **Q15. Login System with Limited Attempts**

Simulate a login system that gives the user **3 attempts** to enter the correct
password. After 3 failed tries, it locks them out.

---

Would you like detailed **answers** or solutions for any of these next? You can
also choose a specific problem you'd like to try.

In the meantime, I’ll provide detailed answers for each question **right here**
below.

---

## ✅ DETAILED LOGICAL PROBLEM ANSWERS

---

### 🔢 **1. Integer**

#### **Q1. Armstrong Number Checker**

```python
num = int(input("Enter a number: "))
sum_of_powers = 0
temp = num
num_digits = len(str(num))

while temp > 0:


digit = temp % 10
sum_of_powers += digit ** num_digits
temp //= 10

if sum_of_powers == num:
print("Armstrong number.")
else:
print("Not an Armstrong number.")
```

---

#### **Q2. Reverse Digits Without String Conversion**

```python
num = int(input("Enter a number: "))
reversed_num = 0

while num > 0:


digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10

print("Reversed number:", reversed_num)


```

---

#### **Q3. Digital Root**

```python
num = int(input("Enter a number: "))

def digital_root(n):
while n >= 10:
sum_digits = 0
while n > 0:
sum_digits += n % 10
n //= 10
n = sum_digits
return n

print("Digital Root:", digital_root(num))


```

---

### 🧵 **2. String**

#### **Q4. Anagram Checker**

```python
str1 = input("Enter first string: ").lower().replace(" ", "")
str2 = input("Enter second string: ").lower().replace(" ", "")

if sorted(str1) == sorted(str2):
print("They are anagrams.")
else:
print("They are not anagrams.")
```

---

#### **Q5. Palindrome Ignoring Spaces and Case**

```python
text = input("Enter a sentence: ").lower()
cleaned = ''.join(char for char in text if char.isalnum())

if cleaned == cleaned[::-1]:
print("It's a palindrome.")
else:
print("Not a palindrome.")
```

---

#### **Q6. Longest Word Finder**

```python
sentence = input("Enter a sentence: ")
words = sentence.split()
longest = ""

for word in words:


if len(word) > len(longest):
longest = word

print("Longest word:", longest)


```

---

### 📋 **3. List**

#### **Q7. Second Largest Unique Number**

```python
numbers = [10, 40, 20, 40, 30, 10]
unique = []

for num in numbers:


if num not in unique:
unique.append(num)

first = second = float('-inf')

for num in unique:


if num > first:
second = first
first = num
elif num > second:
second = num

print("Second largest unique number:", second)


```

---

#### **Q8. Find Missing Number (1 to 100)**

```python
numbers = list(range(1, 101))
numbers.remove(57) # simulate missing number

expected_sum = 100 * 101 // 2


actual_sum = sum(numbers)

print("Missing number is:", expected_sum - actual_sum)


```

---

#### **Q9. Remove Duplicates Without Set**

```python
original = [1, 2, 2, 3, 4, 4, 5]
unique = []
for item in original:
if item not in unique:
unique.append(item)

print("List without duplicates:", unique)


```

---

### 📚 **4. Dictionary**

#### **Q10. Invert a Dictionary**

```python
original = {'a': 1, 'b': 2, 'c': 3}
inverted = {}

for key, value in original.items():


inverted[value] = key

print("Inverted dictionary:", inverted)


```

---

#### **Q11. Most Frequent Value**

```python
data = {'a': 1, 'b': 2, 'c': 2, 'd': 3, 'e': 2}
freq = {}

for key in data:


val = data[key]
if val in freq:
freq[val] += 1
else:
freq[val] = 1

most_frequent = max(freq, key=freq.get)


print("Most frequent value:", most_frequent)
```

---

#### **Q12. Merge Two Dictionaries with Summed Values**

```python
dict1 = {'a': 5, 'b': 2}
dict2 = {'a': 3, 'c': 4}
merged = {}

for key in dict1:


merged[key] = dict1[key]

for key in dict2:


if key in merged:
merged[key] += dict2[key]
else:
merged[key] = dict2[key]
print("Merged dictionary:", merged)
```

---

### ✅ **5. Boolean**

#### **Q13. Truth Table Evaluator**

```python
a = input("Enter first boolean (true/false): ").lower() == "true"
b = input("Enter second boolean (true/false): ").lower() == "true"

print("AND:", a and b)
print("OR:", a or b)
print("NOT A:", not a)
print("NOT B:", not b)
print("XOR:", a != b)
```

---

#### **Q14. Password Strength Checker**

```python
import string

password = input("Enter password: ")

has_digit = any(c.isdigit() for c in password)


has_upper = any(c.isupper() for c in password)
has_symbol = any(c in string.punctuation for c in password)
is_long_enough = len(password) >= 8

if all([has_digit, has_upper, has_symbol, is_long_enough]):


print("Strong password.")
else:
print("Weak password.")
```

---

#### **Q15. Login System with Limited Attempts**

```python
correct_password = "letmein"
attempts = 3

while attempts > 0:


entered = input("Enter password: ")
if entered == correct_password:
print("Access granted.")
break
else:
attempts -= 1
print(f"Incorrect. {attempts} attempts left.")

if attempts == 0:
print("Account locked.")
```

---

Would you like a **PDF export**, **quiz version**, or **project-style problems**


based on this too?

You might also like