0% found this document useful (0 votes)
10 views34 pages

Akhila Py

The document outlines key features of Python, including its readability, interpreted nature, dynamic typing, object-oriented support, and extensive libraries. It also covers type conversion functions, formal languages, recursion, function definition, mutable lists, variable-length argument tuples, class definitions, and inheritance in OOP. Additionally, it provides examples of string operations such as searching, looping, and counting occurrences.
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)
10 views34 pages

Akhila Py

The document outlines key features of Python, including its readability, interpreted nature, dynamic typing, object-oriented support, and extensive libraries. It also covers type conversion functions, formal languages, recursion, function definition, mutable lists, variable-length argument tuples, class definitions, and inheritance in OOP. Additionally, it provides examples of string operations such as searching, looping, and counting occurrences.
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/ 34

SHOTS

Q1: Key Features of Python


1. Readability and Simplicity:
o Python's syntax is clear and easy to read, which helps developers write
clean and maintainable code.
o The language emphasizes readability, often using English keywords
where other languages use punctuation.
2. Interpreted Language:
o Python is an interpreted language, meaning code is executed line-by
line. This feature makes debugging easier and allows for rapid
prototyping.
3. Dynamically Typed:
o In Python, you don’t need to declare the type of a variable. The
interpreter assigns the type dynamically at runtime.
4. Object-Oriented:
o Python supports object-oriented programming (OOP), enabling
developers to create classes and objects to model real-world entities and
relationships.
5. Extensive Standard Library:
o Python comes with a rich standard library that provides modules and
functions for various tasks, such as file handling, Internet protocols, and
system operations.
6. Extensive Ecosystem:
o There are numerous third-party libraries and frameworks available for
Python, extending its capabilities in areas such as web development
(Django, Flask), data science (NumPy, pandas), machine learning
(TensorFlow, scikit-learn), and more.
7. Cross-Platform Compatibility:
o Python is cross-platform, which means Python programs can run on
different operating systems like Windows, macOS, and Linux without
modification.
8. Community Support:
o Python has a large and active community that contributes to its
development and provides support through forums, online courses, and
documentation.

2Q: Type conversion functions: In Python, type conversion


functions are used to
convert data from one type to another. This is often necessary when you need
to
manipulate or process data in a specific.
1. int()
Converts a value to an integer. It can handle strings and floating-point numbers.
String to Integer:
num_str = "42"
num_int = int(num_str)
print(num_int) # Output: 42
Float to Integer:
num_float = 3.14
num_int = int(num_float)
print(num_int) # Output: 3
2. float()
Converts a value to a floating-point number. • String to Float:
num_str = "3.14"
num_float = float(num_str)
print(num_float) # Output: 3.14
Integer to Float:
num_int = 5
num_float = float(num_int)
print(num_float) # Output: 5.0
3. str()
Converts a value to a string.
• Integer to String:
num_int = 42
num_str = str(num_int)
print(num_str) # Output: '42'
Float to String:
num_float = 3.14
num_str = str(num_float)
print(num_str) # Output: '3.14'
4. bool()
Converts a value to a boolean (True or False).
• Integer to Boolean:
num = 1
bool_value = bool(num)
print(bool_value) # Output: True
String to Boolean:
text = ""
bool_value = bool(text)
print(bool_value) # Output: False

3Q: Formal Languages


Characteristics:
1. Designed: Formal languages are deliberately created for specific purposes.
2. Precision: They are unambiguous and have strict syntax and semantics.
3. Limited Vocabulary: They have a restricted set of symbols and rules.
4. Lack of Redundancy: Formal languages avoid redundancy to maintain
clarity and precision.
5. Non-contextual: Meaning is independent of context.
Examples:
• Programming languages (Python, Java, C++)
• Mathematical notations
• Formal grammars (used in automata theory and compiler design)
• Markup languages (HTML, XML)
Applications:
• Computer programming
• Mathematical proofs
• Formal verification of systems
• Algorithm design and analysis

2. Formal Language Theory:


o Formal languages are studied in theoretical computer science to
understand computational complexity and automata theory.
o This theory is essential for designing programming languages and
compilers.

Formal Language (Python):


def can_read(person, item):
if person == "I" and item == "book":
return True
return False
print(can_read("I", "book")) # Output: True

4Q: Recursive Tree


Recursion can be visualized as a tree of function calls. Each recursive call creates
a
new branch until it hits the base case.
Key Points
1. Base Case**: This is the condition under which the recursion stops. It
prevents
infinite recursion.
2. **Recursive Case**: This is where the function calls itself with a modified
argument.
Leap of Faith
The "leap of faith" is a term often used to describe the confidence that a
recursive
function will work correctly. It involves trusting that the recursive calls will
eventually lead to a base case and that each step towards the base case will
solve a
smaller instance of the problem correctly.
Example: Leap of Faith
Consider a function that finds the maximum value in a list:
```python
def find_max(lst):
if len(lst) == 1:
return lst[0]
else:
max_of_rest = find_max(lst[1:])
return lst[0] if lst[0] > max_of_rest else max_of_rest
Example usage
print(find_max([3, 1, 4, 1, 5, 9, 2, 6])) # Output: 9
In this function, we assume that `find_max` correctly finds the maximum of the
sublist `lst[1:]`. We use this assumption to determine the maximum of the
entire
list. This "leap of faith" helps simplify the problem and focus on solving it in
steps.
5Q: Adding New Functions
In Python programming, adding new functions to your code is a fundamental
way to
organize and reuse code, making your programs more modular, readable, and
maintainable.
Defining Functions
Functions are defined using the def keyword, followed by the function name
and
parentheses. Here’s a basic syntax:
def function_name(parameters):
"""Optional docstring."""
# Function body
return value
Example:
def greet(name):
"""Return a greeting message."""
return f"Hello, {name}!"
Using Functions
Once a function is defined, you can call it using its name followed by
parentheses.
Pass any required arguments within the parentheses.
Example:
message = greet("Alice")
print(message) # Output: Hello, Alice!
Descriptive Names: Choose meaningful names that clearly indicate what the
function does.
Docstrings: Include a docstring right after the function definition to describe its
purpose and usage.
Keep Functions Small: Each function should perform a single, well-defined task.
This makes your code easier to understand and test.
Use Default Parameters Wisely: Provide default values for parameters that are
optional, but avoid overusing them.
Avoid Side Effects: Functions should ideally have no side effects (e.g., modifying
global variables) to keep them predictable and reusable.
Organize Code: Group related functions together and consider separating them
into different modules if necessary.

6Q: Key Features of Mutable Lists


1. **Change Elements**: You can update individual elements by accessing them
via their index.
```python
my_list = [1, 2, 3]
my_list[1] = 20 # Now my_list is [1, 20, 3]
2. **Add Elements**: You can append new elements using methods like
`append()` and `insert()`.
```python
my_list.append(4)
# Now my_list is [1, 20, 3, 4]
my_list.insert(1, 15) # Now my_list is [1, 15, 20, 3, 4]
3. **Remove Elements**: You can remove elements using methods like
`remove()` and `pop()`.
```python
my_list.remove(20)
# Now my_list is [1, 15, 3, 4]
popped_element = my_list.pop() # Removes and returns the last element (4)
4. **Extend Lists**: You can combine lists using the `extend()` method or the `+`
operator.
```python
another_list = [5, 6]
my_list.extend(another_list) # Now my_list is [1, 15, 3, 5, 6]
5. **Sort and Reverse**: You can modify the order of elements with `sort()` and
`reverse()`.
```python
my_list.sort()
my_list.reverse()
# Sorts in ascending order
# Reverses the order of elements
Example of Mutability
Here's an example showcasing the mutability of lists:
python
# Initial list
my_list = [10, 20, 30]
# Modify an element
my_list[1] = 25
print(my_list) # Output: [10, 25, 30]
# Add an element
my_list.append(40)
print(my_list) # Output: [10, 25, 30, 40]
# Remove an element
my_list.remove(30)
print(my_list) # Output: [10, 25, 40]
# Extend the list
my_list.extend([50, 60])
print(my_list) # Output: [10, 25, 40, 50, 60]

7Q: Variable-length argument tuples


Variable-Length Argument Tuples
In Python, you can use variable-length argument tuples in function definitions
by
using the `*` syntax. This allows you to pass a variable number of arguments to
a
function, which are then accessible as a tuple within the function.
Example of Variable-Length Argument Tuples
```python
def concatenate(*args):
result = ""
for arg in args:
result += str(arg) + " "
return result.strip()
# Calling the function with different numbers of arguments
print(concatenate("Hello", "world!"))
# Output: Hello world!
print(concatenate("Python", "is", "awesome")) # Output: Python is awesome
print(concatenate(1, 2, 3, 4, 5))
# Output: 1 2 3 4 5
In the example above, `*args` captures all positional arguments as a tuple,
allowing
the function to handle an arbitrary number of arguments.

8Q: Class Definition, Creating Objects, Instances as


Arguments
In Python, a class is a blueprint for creating objects (instances). Objects are
instances of classes, and you can define methods and attributes within a class.
Class Definition
To define a class, use the `class` keyword followed by the class name
(conventionally in CamelCase).
Python
class Dog:
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable
def bark(self):
return f"{self.name} says woof!"
Creating Objects
You create an object (instance) of a class by calling the class as if it were a
function.
python
my_dog = Dog("Buddy", 3)
print(my_dog.bark()) # Output: Buddy says woof!
Instances as Arguments
You can pass instances of classes as arguments to methods or functions. Here’s
an
example where one class method takes an instance of another class as an
argument.
python
class Owner:
def __init__(self, name):
self.name = name
def introduce_dog(self, dog):
return f"{self.name} has a dog named {dog.name} who is {dog.age} years
old."
Instances as return

9Q:label,menu,message box

1. **Label** - Displays text or images.


```python
label = Label(root, text="Hello, World!")
2. **Menu** - Creates menus for the application.
```python
menu = Menu(root)
root.config(menu=menu)
3. **tkMessagebox** - Provides functions for displaying message boxes.
```python
from tkinter import messagebox
messagebox.showinfo("Info", "This is an information message.")
Example
python
import tkinter as tk
from tkinter import messagebox
def on_button_click():
messagebox.showinfo("Info", "Button Clicked!")
root = tk.Tk()
root.title("Tkinter Widgets Example")
# Label
label = tk.Label(root, text="Welcome to Tkinter!")
label.pack(pady=10)
# Button
button = tk.Button(root, text="Click Me", command=on_button_click)
button.pack(pady=10)
# Entry
entry = tk.Entry(root)
entry.pack(pady=10)
# Checkbutton
check_var = tk.IntVar()
checkbutton = tk.Checkbutton(root, text="Check me", variable=check_var)
checkbutton.pack(pady=10)
# Listbox
listbox = tk.Listbox(root)
listbox.pack(pady=10)
listbox.insert(1, "Item 1")
listbox.insert(2, "Item 2")
root.mainloop()

10 Q: Creating and Exploring Modules

You can create your own modules by saving Python code in a `.py` file. Here’s a
simple example:
**Creating a Module:**
Create a file named `my_module.py`:
```python
# my_module.py
def greet(name):
return f"Hello, {name}!"
def add(a, b):
return a + b
Using Your Module:
You can then import and use your module in another Python file:
python
import my_module
print(my_module.greet("Alice")) # Output: Hello, Alice!
print(my_module.add(3, 4)) # Output: 7

11Q: Inheritance in Object-Oriented Programming


Inheritance is a fundamental concept in OOP that allows a class to inherit
properties and behaviors (methods) from another class. This promotes code
reusability and establishes a natural hierarchy between classes.
Key Components:
1. Class: A blueprint for creating objects (specific instances of a class). It
defines a set of attributes (data) and methods (functions).
2. Superclass (Parent Class): The class whose properties and methods are
inherited.
3. Subclass (Child Class): The class that inherits from the superclass. It can
have additional properties or methods, or it can override existing ones.
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
return "Some generic sound"

class Dog(Animal):
def speak(self):
return "Bark"
Types of Inheritance:
1. Single Inheritance: A subclass inherits from one superclass.
2. Multiple Inheritance: A subclass inherits from more than one superclass.
3. Multilevel Inheritance: A subclass inherits from another subclass.
4. Hierarchical Inheritance: Multiple subclasses inherit from a single
superclass.
5. Hybrid Inheritance: A combination of two or more types of inheritance.
Benefits of Inheritance:
1. Reusability: Code written in the superclass can be reused in subclasses,
reducing redundancy.
2. Extensibility: New functionality can be added to existing classes without
modifying them.
3. Maintenance: Easier to update and maintain code as changes in the
superclass are reflected in all subclasses.
4. Organization: Provides a clear structure, making the code more
understandable and logical.

LONG

1Q: Searching, Looping and Counting of string


In Python, you can perform various operations on strings, including searching,
looping through, and counting occurrences.
1. Searching for a Substring in a String
To find if a substring exists within a string, you can use the `in` keyword or
methods like `find()` and `index()`.
- **Using `in` keyword**:
```python
main_string = "Hello, welcome to the world of Python."
substring = "welcome"
if substring in main_string:
print(f"'{substring}' is found in the main string.")
else:
print(f"'{substring}' is not found in the main string.") - **Using `find()`
method**:
python
position = main_string.find(substring)
if position != -1:
print(f"'{substring}' found at index {position}.")
else:
print(f"'{substring}' not found.") - **Using `index()` method**:
```python
try:
position = main_string.index(substring)
print(f"'{substring}' found at index {position}.")
except ValueError:
print(f"'{substring}' not found.")
`find()` returns `-1` if the substring is not found, whereas `index()` raises a
`ValueError` if it is not found.
2. Looping Through Characters in a String
You can loop through each character in a string using a `for` loop.
python
for char in main_string:
print(char)
If you need the index of each character as well, you can use the `enumerate()`
function.
python
for index, char in enumerate(main_string):
print(f"Index {index}: {char}")
3. Counting Occurrences of a Substring
To count the number of times a substring appears in a string, you can use the
`count()` method.
python
count = main_string.count(substring)
print(f"'{substring}' appears {count} times in the main string.")
Full Example
Here’s a full example that combines searching, looping, and counting:
python
main_string = "Hello, welcome to the world of Python. Python is great."
substring = "Python"
# Search for the substring
if substring in main_string:
print(f"'{substring}' is found in the main string.")
else:
print(f"'{substring}' is not found in the main string.")
# Loop through the main string
print("Looping through characters:")
for index, char in enumerate(main_string):
print(f"Index {index}: {char}")
# Count occurrences of the substring
count = main_string.count(substring)
print(f"'{substring}' appears {count} times in the main string.")

2Q: Built-in List Operators


Python provides several built-in operators for manipulating lists.
1. Concatenation (`+`)
You can concatenate two lists using the `+` operator.
python
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) # Output: [1, 2, 3, 4, 5, 6]
2. Repetition (`*`)
You can repeat a list multiple times using the `*` operator.
python
my_list = [1, 2, 3]
repeated = my_list * 3
print(repeated) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
3. Membership (`in` and `not in`)
You can check if an element is in a list using the `in` keyword.
python
my_list = [1, 2, 3, 4]
print(2 in my_list) # Output: True
print(5 not in my_list) # Output: True
4. Indexing
You can access elements by their index.
python
my_list = [10, 20, 30, 40]
print(my_list[1]) # Output: 20
5. Slicing
You can retrieve a sublist using slicing.
python
my_list = [10, 20, 30, 40, 50]
sublist = my_list[1:4] # Elements from index 1 to 3
print(sublist) # Output: [20, 30, 40]
6. Length (`len()`)
You can get the number of elements in a list using the `len()` function.
python
my_list = [1, 2, 3, 4]
print(len(my_list)) # Output: 4
7. Iteration
You can iterate through the list using a `for` loop.
python
my_list = [1, 2, 3, 4]
for item in my_list:
print(item)
8. Sorting (`sort()` and `sorted()`)
You can sort a list in place using `sort()`, or create a new sorted list using
`sorted()`.
python
my_list = [3, 1, 4, 2]
my_list.sort() # Sorts in place
print(my_list) # Output: [1, 2, 3, 4]
Using sorted()
new_list = sorted([3, 1, 4, 2])
print(new_list) # Output: [1, 2, 3, 4]
9. Reversing (`reverse()`)
You can reverse the order of elements in a list using `reverse()`.
python
my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # Output: [4, 3, 2, 1]
10. Count (`count()`)
You can count the occurrences of a specific element using `count()`.
python
my_list = [1, 2, 2, 3]
print(my_list.count(2)) # Output: 2
11. Index (`index()`)
You can find the index of the first occurrence of a value using `index()`.
python
my_list = [1, 2, 3, 2]
print(my_list.index(2)) # Output: 1

3Q: Multithreading
Multithreaded programming in Python can be effectively managed using the
`threading` module. Below is a breakdown of key concepts, including creating
threads, synchronizing them, and implementing a multithreaded priority queue.
1. Creating a Thread
You can create threads using either the `Thread` class from the `threading`
module
or by subclassing it. Here’s a simple example of both methods:
Using Thread class directly:
python
import threading
import time
def worker():
print("Thread is starting...")
time.sleep(2)
print("Thread has finished.")
# Creating a thread
thread = threading.Thread(target=worker)
thread.start()
# Wait for the thread to finish
thread.join()
print("Main thread continues...")
Subclassing Thread
python
import threading
import time
class MyThread(threading.Thread):
def run(self):
print("Thread is starting...")
time.sleep(2)
print("Thread has finished.")
# Creating a thread
thread = MyThread()
thread.start()
thread.join()
print("Main thread continues...")
2. Synchronizing Threads
Synchronization is crucial when multiple threads access shared resources. You
can
use locks to ensure that only one thread accesses a resource at a time.
**Using Lock:**
```python
import threading
lock = threading.Lock()
shared_resource = 0
def increment():
global shared_resource
for _ in range(100000):
with lock:
shared_resource += 1
threads = []
for _ in range(2):
thread = threading.Thread(target=increment)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
print(f"Final value of shared resource: {shared_resource}")
3. Multithreaded Priority Queue
For managing tasks that need to be processed based on priority, you can use
`queue.PriorityQueue`. This allows you to assign a priority to each task.
Example of a multithreaded priority queue:
python
import threading
import queue
import time
# Define a worker that processes tasks
def worker(priority_queue):
while True:
try:
priority, task = priority_queue.get(timeout=1) # Timeout to prevent
blocking
print(f"Processing task: {task} with priority: {priority}")
time.sleep(1) # Simulate work
priority_queue.task_done()
except queue.Empty:
break
# Create a priority queue
priority_queue = queue.PriorityQueue()
# Adding tasks to the queue (priority, task)
tasks = [(2, "Task 2"), (1, "Task 1"), (3, "Task 3")]
for task in tasks:
priority_queue.put(task)
# Creating multiple threads to process the queue
threads = []
for _ in range(3):
thread = threading.Thread(target=worker, args=(priority_queue,))
threads.append(thread)
thread.start()
# Wait for all threads to finish
for thread in threads:
thread.join()
print("All tasks completed.")

4Q: Handling Standard attributes and Properties of


Widgets
In Python, particularly when using GUI frameworks like Tkinter, PyQt, or Kivy,
widgets have standard attributes and properties that you can manipulate to
control
their appearance and behavior. Here’s a general overview:
1. Tkinter Widgets
**Common Attributes:** - **`text`**: Displays text in labels, buttons, etc.
- **`bg` / `background`**: Sets the background color. - **`fg` / `foreground`**:
Sets the text color. - **`font`**: Specifies the font type and size. - **`width`**
and **`height`**: Sets the size of the widget. - **`padx` / `pady`**: Adds
padding inside the widget.
**Common Methods:** - **`pack()`**: Arranges the widget in blocks before
placing them in the parent
widget. - **`grid()`**: Places the widget in a grid layout. - **`place()`**: Places
the widget at an exact position. - **`config()`**: Changes the properties of the
widget after it has been created.
Example in Tkinter
python
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Hello, Tkinter!", bg="lightblue", fg="black",
font=("Arial", 14))
label.pack(padx=20, pady=20)
root.mainloop()
2. PyQt Widgets
**Common Properties:** - **`text`**: Similar to Tkinter, for displaying text. -
**`sizePolicy`**: Controls how the widget resizes. - **`styleSheet`**: Allows for
custom styling with CSS-like syntax. - **`icon`**: Sets an icon for buttons and
other widgets.
**Common Methods:** - **`show()`**: Displays the widget. - **`setText()`**:
Changes the text displayed. - **`setEnabled()`**: Enables or disables the widget.
Example in PyQt
python
from PyQt5.QtWidgets import QApplication, QLabel
app = QApplication([])
label = QLabel('Hello, PyQt!')
label.setStyleSheet("background-color: lightblue; color: black; font-size: 14px;")
label.show()
app.exec_()
3. Kivy Widgets
**Common Properties:** - **`text`**: Used in labels and buttons. -
**`size_hint`**: Controls how the widget resizes relative to its parent. -
**`background_color`**: Sets the background color.
**Common Methods:** - **`add_widget()`**: Adds a widget to a layout. -
**`remove_widget()`**: Removes a widget from a layout.
Example in Kivy
python
from kivy.app import App
from kivy.uix.label import Label
class MyApp(App):
def build(self):
return Label(text='Hello, Kivy!', size_hint=(None, None), size=(200, 50),
color=(0, 0, 0, 1))
MyApp().run()

5Q: Looping: for, while, nested loops


Looping is a fundamental concept in programming, allowing you to execute a
block
of code repeatedly based on certain conditions. In Python, you can use for
loops,
while loops, and nested loops to achieve various iteration tasks.
1. for Loop
The for loop in Python is used to iterate over a sequence (such as a list, tuple,
string,
or range) or other iterable objects. It's particularly useful when you know the
number
of iterations beforehand.
Syntax
for variable in iterable:
# code to execute
Examples
Iterating over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Iterating over a String
for char in "hello":
print(char)
Output:
h
e
l
l
o
Using range() Function
The range() function generates a sequence of numbers, which can be used with
for
loops.
for i in range(5):
print(i)
Output:
0
1
2
3
4
You can also specify a start and stop value:
for i in range(2, 6):
print(i)
Output:
2
3
4
5
You can also specify a step value:
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8
2. while Loop
The while loop continues to execute a block of code as long as a given condition
is
True. It's useful when the number of iterations is not known beforehand.
Syntax
while condition:
# code to execute
Examples
Basic While Loop
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4Avoiding Infinite Loops
Ensure that the condition in a while loop will eventually become False to avoid
infinite loops.
Using break and continue
• break: Exits the loop prematurely.
• continue: Skips the rest of the code inside the loop for the current iteration
and proceeds with the next iteration.
count = 0
while count < 10:
if count == 5:
break # Exit loop when count is 5
print(count)
count += 1
0
1
2
3
4
count = 0
while count < 10:
count += 1
if count % 2 == 0:

continue # Skip even numbers


print(count)
1
3
5
7
9
3. Nested Loops
Nested loops are loops inside other loops. Both for and while loops can be
nested.
Syntax
for outer_variable in outer_iterable:
for inner_variable in inner_iterable:
# code to execute
Examples
Nested for Loops
for i in range(3):
for j in range(2):
print(f"i = {i}, j = {j}")
Output:
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
Nested while Loops
i=0
while i < 3:
j=0
while j < 2:
print(f"i = {i}, j = {j}")
j += 1
i += 1
Output:
i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1
Using Nested Loops with Lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for elem in row:
print(elem, end=' ')
print()
Output:
123
456
789
• for Loop: Iterates over a sequence (list, tuple, string, range) or any iterable
object.
• while Loop: Repeats as long as a condition is True.
• Nested Loops: Loops within other loops, used for more complex iteration
scenarios…

You might also like