0% found this document useful (0 votes)
56 views5 pages

Python Basics: 20 Questions & Answers

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

Python Basics: 20 Questions & Answers

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

20 Python Basic Questions with Answers

1. Print Hello World

Q: Write a Python program to print "Hello, World!".


A:

print("Hello, World!")

2. Add Two Numbers

Q: Write a program to add two numbers: 5 + 10.


A:

a=5

b = 10

print(a + b)

3. Find the Square of a Number

Q: Write a program to find the square of 7.


A:

num = 7

print(num * num)

4. Find the Cube of a Number

Q: Write a program to find the cube of 4.


A:

num = 4

print(num ** 3)

5. Swap Two Numbers

Q: Swap the values of x = 3 and y = 7.


A:

x=3

y=7

x, y = y, x

print(x, y)
6. Check Even or Odd

Q: Write a program to check if 12 is even or odd.


A:

num = 12

if num % 2 == 0:

print("Even")

else:

print("Odd")

7. Largest of Two Numbers

Q: Find the largest number between 8 and 15.


A:

a=8

b = 15

print(max(a, b))

8. Convert Celsius to Fahrenheit

Q: Convert 25°C to Fahrenheit.


A:

c = 25

f = (c * 9/5) + 32

print(f)

9. Simple Interest

Q: Write a program to calculate Simple Interest where P=1000, R=5, T=2.


A:

P = 1000

R=5

T=2

SI = (P * R * T) / 100

print(SI)
10. Reverse a String

Q: Reverse the string "Python".


A:

s = "Python"

print(s[::-1])

11. Count Characters in String

Q: Find the length of "Hello".


A:

s = "Hello"

print(len(s))

12. Sum of First 10 Natural Numbers

Q: Find the sum of numbers from 1 to 10.


A:

total = 0

for i in range(1, 11):

total += i

print(total)

13. Factorial of a Number

Q: Find factorial of 5.
A:

num = 5

fact = 1

for i in range(1, num + 1):

fact *= i

print(fact)

14. Multiplication Table

Q: Print the multiplication table of 6.


A:

for i in range(1, 11):


print(6, "x", i, "=", 6*i)

15. Fibonacci Series

Q: Print first 5 terms of Fibonacci series.


A:

a, b = 0, 1

for i in range(5):

print(a, end=" ")

a, b = b, a + b

16. Check Prime Number

Q: Check if 7 is prime or not.


A:

num = 7

is_prime = True

for i in range(2, num):

if num % i == 0:

is_prime = False

break

print("Prime" if is_prime else "Not Prime")

17. Find Maximum in List

Q: Find the largest number in [4, 9, 1, 7].


A:

numbers = [4, 9, 1, 7]

print(max(numbers))

18. Sum of List Elements

Q: Find the sum of [3, 5, 2, 8].


A:

numbers = [3, 5, 2, 8]

print(sum(numbers))
19. Find Vowels in String

Q: Count vowels in "education".


A:

s = "education"

vowels = "aeiou"

count = 0

for ch in s:

if ch in vowels:

count += 1

print(count)

20. Simple Calculator

Q: Write a simple calculator for a=8, b=2.


A:

a=8

b=2

print("Sum:", a+b)

print("Difference:", a-b)

print("Product:", a*b)

print("Division:", a/b)

Common questions

Powered by AI

Loops in Python, such as the 'for' loop, provide an iterative and straightforward approach to generating sequences like the Fibonacci series, allowing easy tracking and generation of terms by simple arithmetic: iterating with two variables tracking the last terms. This approach avoids the memory overhead and potential stack overflow issues of recursion, which can repetitively call functions, leading to increased depth and resource consumption. Loops thus offer a controlled structure for sequence generation, achieving the desired results with improved space efficiency and simplicity.

Python handles division using the operator '/', which results in a float, even if dividing integers. For integer division, Python uses '//' which truncates the decimal part. Care should be taken to handle division by zero, which will raise a ZeroDivisionError, and to consider whether integer or float division is required depending on the application context. Type conversion might be necessary to avoid type errors and ensure numerical precision in more complex arithmetic operations, like those used in a calculator.

Swapping two numbers with a temporary variable in most programming languages involves three steps: assigning one of the numbers to a temporary variable, overwriting the original number with the other, and finally, assigning the value of the temporary variable to the other number. In Python, this can be done more efficiently without an additional variable by using tuple unpacking: x, y = y, x. This method utilizes Python's ability to handle multiple assignments in a single line, making it more elegant and concise compared to languages that require a temporary variable for swaps.

Looping through lists allows for custom logic and control over the operation, useful for complex transformations or conditional logic. However, Python's built-in functions like max() offer optimized performance and readability for common operations such as finding the maximum element. These functions are implemented in C, making them faster than equivalent Python loops. Using built-in functions is generally preferred for simplicity and efficiency unless custom behavior necessitates a manual loop.

Calculating simple interest is straightforward and involves multiplying the principal amount (P) by the rate (R) and time (T), then dividing by 100 to adjust for percentage: (P * R * T) / 100. Simple interest is preferred when dealing with straightforward, short-term loans or investments where interest is calculated only on the principal, as opposed to compound interest which considers accumulated interest. Python's direct arithmetic operations make implementing simple interest calculation easy and concise.

When checking if a number is prime, key considerations include minimizing the number of operations to improve efficiency. Instead of checking all numbers up to n-1, it's more efficient to check divisibility up to the square root of n, as any factor larger would necessarily pair with a smaller factor. Moreover, exceptions for small primes and even numbers should be included to avoid unnecessary computations, utilizing algorithms like the Sieve of Eratosthenes for larger ranges or implementing trial division with optimizations.

In Python, strings are immutable, meaning they cannot be changed in place. This immutability requires creating a new string when performing operations like reversal. The slicing technique s[::-1] creates a new string with the characters in reverse order, rather than altering the original string. This approach effectively bypasses immutability limitations, leveraging Python's efficient slicing capabilities, but also means increased memory usage due to the creation of a new string object.

Using a loop to calculate the sum of the first N natural numbers, like with a for-loop, provides iterative insight and understanding into the process of summation, offering step-by-step addition. Alternatively, using the formula N*(N+1)/2 instantly provides the sum, optimizing for performance by reducing time complexity from O(N) to O(1). However, beginners may prefer loops for educational purposes or when implementing sum manually in applications that require iterative computation.

Using exponentiation (num ** 3) in Python to find a cube is computationally efficient and concise, leveraging Python's optimized arithmetic operations. This operation can internally optimize the series of multiplications needed to arrive at the result, potentially reducing instruction complexity compared to manual loops. It simplifies code readability and maintains numerical precision across large or small bases. These factors contribute to its preferred usage for such mathematical operations.

List comprehensions provide a concise way to iterate over sequences like strings, filtering and transforming data efficiently. Compared to a loop, which explicitly iterates and appends each vowel to a list one at a time, a comprehension like [ch for ch in s if ch in 'aeiou'] directly constructs the list in a single line. Comprehensions are not only more readable and Pythonic but can also offer performance benefits by optimizing the loop at a lower level within Python's execution model.

You might also like