0% found this document useful (0 votes)
2 views2 pages

Python Qna

The document provides a series of Python programming examples, including printing text, taking user input, checking for even or odd numbers, calculating factorials using recursion, creating list comprehensions, reversing strings, using lambda functions, handling exceptions, and reading/writing files. Each example includes code snippets that demonstrate the functionality. This serves as a quick reference for basic Python programming concepts.
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)
2 views2 pages

Python Qna

The document provides a series of Python programming examples, including printing text, taking user input, checking for even or odd numbers, calculating factorials using recursion, creating list comprehensions, reversing strings, using lambda functions, handling exceptions, and reading/writing files. Each example includes code snippets that demonstrate the functionality. This serves as a quick reference for basic Python programming concepts.
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
You are on page 1/ 2

Q: How do you print 'Hello, World!' in Python?

print("Hello, World!")

Q: How do you take user input and display it?

name = input("Enter your name: ")

print("Hello,", name)

Q: How do you check if a number is even or odd?

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

if num % 2 == 0:

print("Even")

else:

print("Odd")

Q: How do you find the factorial of a number using recursion?

def factorial(n):

if n == 0:

return 1

return n * factorial(n - 1)

print(factorial(5)) # Output: 120

Q: What is a list comprehension? Give an example.

squares = [x**2 for x in range(1, 6)]

print(squares) # Output: [1, 4, 9, 16, 25]

Q: How to reverse a string in Python?

s = "hello"

print(s[::-1]) # Output: "olleh"

Q: What is a lambda function? Give an example.

add = lambda x, y: x + y

print(add(3, 5)) # Output: 8

Q: How do you handle exceptions in Python?

try:
result = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero.")

finally:

print("Done.")

Q: How do you read and write to a file?

# Writing

with open("example.txt", "w") as f:

f.write("Hello file!")

# Reading

with open("example.txt", "r") as f:

content = f.read()

print(content)

You might also like