0% found this document useful (0 votes)
42 views8 pages

Python Programming Basics and Features

The document provides a comprehensive overview of Python programming, covering its features, key data types, and fundamental concepts such as loops, functions, and file handling. It also discusses advanced topics like decorators, recursion, and memory management, along with practical examples. Additionally, it highlights the differences between various data structures and programming constructs in Python.

Uploaded by

NAVANEETH SAI
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)
42 views8 pages

Python Programming Basics and Features

The document provides a comprehensive overview of Python programming, covering its features, key data types, and fundamental concepts such as loops, functions, and file handling. It also discusses advanced topics like decorators, recursion, and memory management, along with practical examples. Additionally, it highlights the differences between various data structures and programming constructs in Python.

Uploaded by

NAVANEETH SAI
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

1. What is Python? List a few features of Python.

Python is a high-level, interpreted programming language known for its simplicity and readability.

Features:

- Easy to learn

- Interpreted language

- Dynamically typed

- Large standard library

- Community support

- Cross-platform

2. What are the key data types in Python?

int, float, str, bool, list, tuple, dict, set, NoneType

3. How do you write a comment in Python?

Using the # symbol. Example: # This is a comment

4. What is the difference between a list and a tuple?

Lists are mutable, tuples are immutable.

5. What is a dictionary in Python?

A collection of key-value pairs. Example: {'a': 1, 'b': 2}

6. What is the use of the len() function?

Returns the number of items in an object.

7. How do you convert a string to an integer?

Using int(). Example: int('123')

8. How do you take user input in Python?

Using input(). Example: name = input('Enter name: ')

9. How do you print something without a newline?

Use end parameter. Example: print('Hello', end='')

10. What is a variable in Python? How do you declare one?

A variable stores data. Example: x = 10


11. What are if, elif, and else used for?

They are used for conditional branching.

12. How do you write a for loop in Python?

Example: for i in range(5): print(i)

13. What is the use of the range() function?

Generates a sequence of numbers.

14. What is the difference between break and continue?

break exits the loop, continue skips to the next iteration.

15. How do you write a while loop in Python?

Example: while condition: do_something()

16. How do you define a function in Python?

Using def keyword. Example: def func(): pass

17. What is the purpose of the return statement?

To return a value from a function.

18. What is a default parameter in a function?

A parameter with a default value. Example: def func(x=1):

19. How do you call a function in Python?

By writing its name followed by parentheses. Example: func()

20. What is the difference between a function and a method?

Function is independent; method is associated with an object.

21. How do you access the first character of a string?

Using index: s[0]

22. How do you find the length of a string or list?

Using len() function.

23. How can you append an element to a list?

Using append() method. Example: [Link](x)

24. How can you sort a list?


Using sort() or sorted().

25. How do you slice a string?

Using [start:stop:step] syntax.

26. How do you open a file in Python?

Using open() function. Example: open('[Link]')

27. What is the difference between read(), readline(), and readlines()?

read(): entire file, readline(): one line, readlines(): list of lines.

28. How do you write to a file in Python?

Use open with 'w' or 'a' mode and write().

29. What does the with statement do when handling files?

Manages file context and closes file automatically.

30. What happens if you try to open a file that doesn't exist?

Raises a FileNotFoundError.

31. What is the difference between the Python shell and script mode?

Shell runs one line at a time, script runs a file.

32. What does help() do in the Python interpreter?

Displays help documentation.

33. How do you calculate compound interest in Python?

CI = P * (1 + R/100)**T - P

34. How do you find the distance between two points using coordinates?

Use [Link]((x2 - x1)**2 + (y2 - y1)**2)

35. How can you accept multiple user inputs from the keyboard?

Using split(). Example: input().split()

36. How do for and while loops differ in Python?

for is definite iteration, while is indefinite.

37. How do you print a triangle pattern using a nested loop?

Use nested for loops to control rows and columns.


38. How can you check if a character is uppercase or a digit?

Use isupper() or isdigit() methods.

39. How does the Fibonacci sequence work in a while loop?

Loop while condition and update a, b = b, a+b.

40. How can you break out of a loop when a prime is found?

Use break after finding the prime.

41. How do you convert a list or tuple to an array?

Use [Link]()

42. What methods can be used to find common elements in two arrays?

Use set intersection or numpy.intersect1d().

43. Write a recursive function to compute gcd.

def gcd(a, b): return a if b == 0 else gcd(b, a % b)

44. What is a palindrome? How do you check one in Python?

Palindrome reads same backward. Check with s == s[::-1]

45. How do you check if a list is sorted without using sort()?

Compare with sorted version: lst == sorted(lst)

46. How do you detect duplicates in a list without changing it?

Use a set to track seen elements.

47. What does set() do when removing duplicates?

Converts list to a set, automatically removing duplicates.

48. How do you invert a dictionary in Python?

Use dict comprehension: {v: k for k, v in [Link]()}

49. How can you insert a comma between characters of a string?

Use ','.join(string)

50. How do you replace or remove a word in a string?

Use [Link]().

51. Write a function that capitalizes the first letter of each word.
def cap_words(s): return [Link]()

52. How do you generate binary strings of n bits recursively?

Use recursion by appending '0' or '1' at each step.

53. How do you represent a matrix in Python?

Use a list of lists.

54. How do you add two square matrices?

Use nested loops or list comprehensions to add elements.

55. How do you multiply matrices in Python?

Use nested loops or [Link]().

56. What is a Python module? How do you create and use one?

Module is a .py file with functions. Use import module_name.

57. What are exceptions in Python?

Errors detected during execution. Example: ZeroDivisionError

58. How do you catch general exceptions?

Use try-except block.

59. What is a class and an object in Python?

Class is a blueprint. Object is an instance.

60. What are attributes in classes?

Variables bound to an object or class.

61. How do you draw shapes using a Canvas?

Use [Link] and its methods like create_rectangle().

62. What is MRO (Method Resolution Order)?

The order in which methods are searched in multiple inheritance.

63. How is MRO used in multiple inheritance?

Determines the method to be used when classes overlap.

64. How do you validate email and phone number using regex?

Use [Link]() with appropriate regex patterns.


65. How do you merge contents of two files in Python?

Read both, then write to a new file.

66. How do you check if a word exists in a text file?

Read file and use 'word' in content.

67. How do you count the most frequent word in a file?

Use [Link].

68. How can you count words, vowels, spaces, upper/lowercase letters in a file?

Read content and use loops or regex for counting.

69. What is NumPy used for?

Efficient array and matrix operations.

70. What can SciPy do?

Scientific computations including optimization and signal processing.

71. How do you create a simple plot using matplotlib?

Use [Link] with plot() and show().

72. How do you install packages using pip?

Run pip install package_name in terminal.

73. How do you implement an AND gate in Python?

Using logical operator: A and B

74. What is the logic behind a Half Adder?

Uses XOR for sum and AND for carry.

75. How is a Full Adder different from a Half Adder?

Full Adder handles carry-in, Half Adder does not.

76. What is a Parallel Adder?

Adder that adds multi-bit numbers simultaneously.

77. What is tkinter used for?

For building GUI applications in Python.

78. How do you create a GUI with text fields and buttons?
Use tkinter widgets like Entry, Button, and pack/grid.

79. What are the key data types in Python?

int, float, str, bool, list, tuple, dict, set

80. How does Python handle memory management?

Using reference counting and garbage collection.

81. What is the difference between == and is in Python?

== compares values, is compares identities.

82. What is the purpose of __init__() in a class?

It's the constructor method called on object creation.

83. What is recursion? Give a use case.

A function calling itself. Example: factorial calculation.

84. How do you handle multiple exceptions in Python?

Use except (Error1, Error2):

85. What is the difference between break, continue, and pass?

break exits loop, continue skips iteration, pass does nothing.

86. How do you read a file line by line?

Using a for loop: for line in open('[Link]')

87. What is slicing in Python?

Extracting parts of sequences using [start:stop:step]

88. How do you sort a dictionary by its values?

Use sorted([Link](), key=lambda x: x[1])

89. What's the use of enumerate() in loops?

Returns index and value during iteration.

90. What's the difference between list, tuple, set, and dict?

list: ordered, mutable; tuple: ordered, immutable; set: unordered, unique; dict: key-value pairs

91. How is a lambda function different from a normal function?

Anonymous, one-line functions using lambda keyword.


92. What is list comprehension?

A concise way to create lists. Example: [x for x in range(5)]

93. What is the difference between shallow copy and deep copy?

Shallow copies outer object; deep copies everything recursively.

94. What are global and local variables?

Global is outside functions; local is inside functions.

95. What is the use of try-except-finally?

Handle exceptions and ensure final code runs.

96. What are Python decorators?

Functions that modify other functions.

97. What are docstrings in Python?

String literals used to document functions/classes.

98. What are *args and **kwargs?

*args: variable positional args, **kwargs: variable keyword args.

99. How do you import a module in Python?

Using import statement. Example: import math

100. What is the difference between a package and a module?

Module is a .py file, package is a collection of modules with __init__.py

Common questions

Powered by AI

MRO (Method Resolution Order) in Python is the sequence used to determine which method to invoke when a method is called on a class in multiple inheritance scenarios. MRO follows the C3 linearization algorithm, ensuring a consistent order that respects the inheritance hierarchy while avoiding issues like the diamond problem. This is critical for understanding and predicting behavior in complex class hierarchies .

The 'range()' function generates a sequence of numbers, simplifying the writing of for loops by automatically managing loop boundaries and incrementing counters. It enhances readability and reduces potential errors compared to manually updating counters, such as off-by-one errors often encountered in traditional for-loop constructs. Additionally, 'range()' can efficiently handle large sequences as it generates numbers on-the-fly, not storing them in memory .

The 'with' statement in Python simplifies exception handling by automatically managing resources. It ensures that the file is always closed after its block is executed, even if an exception is raised, thereby preventing resource leaks and ensuring that file handles are released properly. This feature provides a clear syntax for managing resources effectively .

'==' checks for value equality, meaning it compares the data content between objects, while 'is' checks for identity equality, verifying if two references point to the same object in memory. In practice, this means two variables can be '==' equal by value but not 'is' equal if they reference different objects with identical content. This is crucial in scenarios dealing with mutable objects, where unexpected behavior might occur if 'is' is used instead of '==' .

Python manages memory using two main techniques: reference counting and a cyclic garbage collector. Reference counting tracks the number of references to an object, deallocating memory once the count reaches zero. However, this alone cannot handle cyclic references, prompting the use of a garbage collector to identify and clean these cycles. This dual approach ensures efficient use of memory, balancing immediate deallocation with the detection and removal of unreferenced cycles .

Creating a GUI application using tkinter involves initializing a Tkinter application, defining widgets like buttons and labels, and managing their placement with geometry managers like pack(), grid(), or place(). Users interact with the GUI through events, and callback functions handle these events. Tkinter simplifies GUI development in Python by providing a straightforward and built-in framework, making it accessible for quick prototyping and deployment of desktop applications .

NumPy provides efficient array computations, including mathematical operations and array manipulations, forming the foundation for other scientific libraries. SciPy builds upon NumPy, offering more advanced numerical algorithms like optimization, differential equations, and signal processing. While NumPy handles basic data structures and operations, SciPy extends its utilities, making them essential together for comprehensive scientific computing .

Lists are mutable, allowing for modifications like additions, deletions, and updates of elements, making them versatile for dynamic data operations. In contrast, tuples are immutable, which implies stability of data and potentially faster access times due to their fixed size, allowing Python to optimize storage. The immutability of tuples also makes them suitable keys for dictionaries, whereas lists cannot serve this purpose .

Decorators in Python modify the behavior of functions or methods without altering their source code. They enable code modularity by isolating concerns; for instance, adding logging, authentication, or timing features. Decorators enhance code reuse by allowing these behaviors to be easily attached and detached across multiple functions, promoting cleaner, more maintainable code through separation of concerns .

Python being an interpreted language allows for cross-platform compatibility, as the same code can run on any system with a Python interpreter without needing modification. It also supports interactive testing, debugging, and prototyping, making development quicker and more flexible. However, interpreted languages tend to be slower than compiled languages because the code is translated on-the-fly rather than beforehand .

You might also like