Python Unit-1 || Questions

Admin
By -
17 minute read
0

 1. What is an Algorithm?

    An algorithm is a sequence of instructions that a computer must perform to solve a well-defined problem. It essentially defines what the computer needs to do and how to do it. Algorithms can instruct a computer how to perform a calculation, process data, or make a decision.

  • It must be correct.
  • It must consist of clear, practical steps that can be completed in a limited time.
  • There should be no confusion about which step comes next.
  • It must have a set number of steps (not an infinite number).
  • It must eventually reach an endpoint.






2. Write an algorithm to Calculate sum of 2 numbers and print it.

  1. Start
  2. Input the first number (num1)
  3. Input the second number (num2)
  4. Calculate the sum: sum = num1 + num2
  5. Print the sum
  6. End
num1=5
num2=7
sum=num1+num2
print(sum)


3. What is a Tuple?

   A tuple is a data structure in programming that is similar to a list or array but with some key differences. It is an ordered collection of elements, and each element can be of a different data type. Tuples are typically immutable, meaning their elements cannot be changede they are defined. They are often used to group related pieces of data together. In many programming languages, tuples are enclosed in parentheses, and elements are separated by commas. For example, in Python, a tuple might look like (1, "apple", 3.14).

   Eg: person = ("John Smith", 30, "New York")

4. Explain Types of Tuple with examples.

   In Python, there are a few types of tuples or tuple-related concepts:

1. Regular Tuples:
    These are the standard tuples in Python. They are immutable, ordered collections of elements enclosed in parentheses and separated by commas.

Example:

my_tuple = (1, "apple", 3.14)

2. Named Tuples: 

   Named tuples are a type of tuple provided by the collections module. They are essentially regular tuples with named fields, which makes code more readable.

Example:

from collections import namedtuple
Person = namedtuple("Person", ["name", "age"])
person = Person(name="Alice", age=25)

3. Immutable Tuples: 
   All tuples in Python are immutable, which means their elements cannot be changed after creation. You can't add, remove, or modify elements in a tuple once it's defined.

4. Heterogeneous Tuples: 
   Tuples can hold elements of different data types. For example, a tuple can contain a mix of integers, strings, floats, etc.

Example:

mixed_tuple = (1, "apple", 3.14)

5. Nested Tuples: 

   You can create nested tuples in Python, where one or more elements of a tuple are themselves tuples.

   Example:

nested_tuple = ((1, 2), ("a", "b"))

6. Empty Tuples: 

   An empty tuple is a tuple with no elements, represented as ().

   Example:

empty_tuple = ()


5. Write a python program to accept two numbers , multiply them and print the result.

# Accepting input for two numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Multiplying the numbers
result = num1 * num2
# Displaying the result
print("The result of multiplying", num1, "and", num2, "is:", result)


6. Write a python program to accept 2 numbers , find the greatest among them.


# Accepting input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Comparing the numbers to find the greatest
if num1 > num2:
    greatest = num1
elif num2 > num1:
    greatest = num2
else:
    greatest = "Both numbers are equal"

# Displaying the result
print(f"The greatest number is: {greatest}")


7. What is a List, How List is differ from Tuple?

        In Python, a list and a tuple are both used to store collections of items, but they have some fundamental differences:

List:

  • Mutable: Lists are mutable, meaning their elements can be changed after the list is created. You can add, remove, or modify elements.
  • Syntax: Lists are defined using square brackets [].
  • Example: my_list = [1, 2, 3, 'apple', 'banana']

Tuple:

  • Immutable: Tuples are immutable, meaning once a tuple is created, you cannot change its elements. The elements within a tuple cannot be altered.
  • Syntax: Tuples are defined using parentheses ().
  • Example: my_tuple = (1, 2, 3, 'apple', 'banana')

Differences:

  1. Mutability: Lists are mutable, while tuples are immutable. Once a tuple is created, it cannot be altered. Elements can't be added, removed, or changed.

  2. Syntax: Lists are defined with square brackets [], while tuples use parentheses ().

  3. Performance: Generally, due to the mutability of lists, they might consume more memory and be slightly slower than tuples. Tuples are more memory-efficient and provide better performance in scenarios where the data is not meant to be changed.

  4. Use cases: Lists are often used when the collection of items might change or needs to be altered, while tuples are preferred for immutable collections or situations where the data should remain constant.



8. Difference between algorithm and program.


Algorithm:

  • Abstract Concept: In Python, an algorithm represents a logical, step-by-step procedure or a plan to solve a particular problem. It's an abstract concept that focuses on the logic of solving a problem without concern for the specific syntax or implementation in Python code.
  • Language-Independent: Algorithms in Python, like in any other language, are language-independent. You can describe an algorithm in pseudocode or a plain language description without using Python's syntax. For instance, you can describe how to sort a list without writing actual Python code.
  • Example: A description of the steps to perform a bubble sort or a binary search without writing Python code is an algorithm in the context of Python.

Program:
  • Concrete Implementation: A Python program is a specific implementation of an algorithm in the Python programming language. It's the translation of an algorithm into actual Python code, written using Python's syntax and constructs.
  • Language-Specific: Python programs are specifically written in the syntax and rules of the Python language. These programs can be executed on a Python interpreter to perform specific tasks.
  • Example: A Python script or function that implements the steps described in an algorithm (e.g., a Python function that sorts a list using the bubble sort algorithm) is an example of a program in Python.


9. Write a Algorithm to find minimum number in a given list of 10 numbers, (without using pre-defined function)

  1. Start
  2.  Initializing a variable, let's say min_number, with a very large value or set it as the first number in the list.
  3. Iterate through the list of 10 numbers.
  4. For each number in the list:
  •   Compare the current number with the min_number
  •   If the current number is smaller than the min_number, update min_number to be the current number.
       5. Once the iteration through the entire list is complete, the min_number will hold the smallest number in the list.
       6. Stop.

# Sample list of 10 numbers
numbers = [23, 12, 56, 7, 34, 78, 9, 41, 60, 18]

# Initialize min_number with a very large value or set it as the first number in the list
min_number = float('inf')  # Initialize with a very large value

# Iterate through the list to find the minimum number
for num in numbers:
    if num < min_number:
        min_number = num

# Display the minimum number found
print("The minimum number in the list is:", min_number)

10. What is Keyword and give Examples.

        Keywords in Python are reserved words that have specific meanings and purposes within the language. They are fundamental building blocks and are used to define the syntax and structure of Python code. Keywords cannot be used as identifiers (variable names or function names) because they hold special meanings within the language.

List of Keywords: (35)
  • False
  • None
  • True
  • and
  • as
  • assert
  • async
  • await
  • break
  • class
  • continue
  • def
  • del
  • elif
  • else
  • except
  • finally
  • for
  • from
  • global
  • if
  • import
  • in
  • is
  • lambda
  • nonlocal
  • not
  • or
  • pass
  • raise
  • return
  • try
  • while
  • with
  • yield


11. Relate String and List.

Similarities:

  1. Sequence Types: Both strings and lists are sequence data types. They can contain elements in a specific order and can be indexed and sliced.

  2. Indexing and Slicing: Both strings and lists support indexing to access individual elements and slicing to obtain subsets of elements.

  3. Iteration: They can be iterated using loops like for loops to access each element.

Differences:

  1. Mutability: Strings are immutable, meaning once a string is created, you cannot change its elements. Lists, on the other hand, are mutable; you can change, add, or remove elements after the list is created.

  2. Character Types: Strings hold a sequence of characters, while lists can contain any data type as elements, allowing for heterogeneity (e.g., numbers, strings, other lists, etc.).

  3. Specific Methods: Strings have specific methods such as split(), join(), and replace() designed for string manipulation. Lists have methods like append(), pop(), extend(), and more, tailored for list operations.


12. List the symbols used in drawing the Flowchart.




13. Outline the logic to swap the content of two Identifiers, without using 3rd Variable.

        In Python, you can swap the contents of two variables without using a third variable using multiple assignment or Tuple unpacking. Here's an outline of the program to achieve this:


# Input values for two variables
var1 = 5
var2 = 10

# Display the original values
print("Before swapping:")
print("var1 =", var1)
print("var2 =", var2)

# Swapping without using a third variable
var1, var2 = var2, var1

# Display the swapped values
print("\nAfter swapping:")
print("var1 =", var1)
print("var2 =", var2)

        This program demonstrates swapping the contents of var1 and var2 without using a third variable. It utilizes the concept of multiple assignment or "Tuple unpacking" in Python to accomplish the swap. The values are exchanged in a single line without the need for an additional temporary variable.


14. State about Logical operator available in python language with examples.

        In Python, logical operators are used to perform logical operations on boolean values. There are three main logical operators: and, or, and not. Here are their descriptions and examples:

1. "and" Operator:

  •    The and operator returns True if both operands are True. Otherwise, it returns False.
x = True
y = False

result = x and y
print(result)  # Output will be False

2. "or" Operator:

  • The or operator returns True if at least one of the operands is True. It returns False only if both operands are False.
a = True
b = False

result = a or b
print(result)  # Output will be True

3. not Operator:

  • The not operator is a unary operator that returns the opposite boolean value of the operand. If the operand is True, not returns False, and if the operand is False, not returns True.
c = True

result = not c
print(result)  # Output will be False

# Combining Logical Operators:

Logical operators can be combined to create more complex conditions:

Example:

p = True
q = False
r = True

result = p and q or r
print(result)  # Output will be True
        Understanding these logical operators allows you to create conditions and perform logical operations based on boolean values, making it integral to control program flow and decision-making in Python.


15. Distinguish about building blocks of algorithm.

        The building blocks of an algorithm are fundamental components or elements used to design, analyze, and create algorithms. These elements are the essential ingredients that form the structure of an algorithm to solve a specific problem or execute a particular task. Here are the primary building blocks of an algorithm:
  1. Input: This is the data or information provided to the algorithm. It's the starting point for the algorithm's operations. Inputs can be varied and can include numbers, strings, arrays, files, or any other form of data required for the algorithm to process.

  2. Output: The result or solution produced by the algorithm after it has performed the necessary computations on the provided inputs. The output could be a single value, a set of values, a modified data structure, a message, or any form of information related to the problem the algorithm is solving.

  3. Sequence: Algorithms often consist of a sequence of steps or actions to be performed in a specific order. Each step details a specific operation that the algorithm should carry out. The sequence defines the flow of the algorithm, outlining the order in which different operations should be executed.

  4. Iteration (Looping): Iteration allows the algorithm to execute a set of instructions repeatedly. This repetition can continue until a specific condition is met, enabling the algorithm to handle tasks that involve repetitive actions, such as processing each element in a list or performing a calculation multiple times.

  5. Selection (Conditional Statements): Conditional statements allow the algorithm to make decisions based on certain conditions. These conditions determine which part of the algorithm should be executed. Common conditional structures include 'if-else' statements, 'switch' statements, and other branching mechanisms.

  6. Modularity (Subroutines/Functions/Procedures): This building block involves breaking down the algorithm into smaller, manageable parts called subroutines, functions, or procedures. These modular components help in organizing the code, making it more readable, maintainable, and reusable.

  7. Variables and Data Structures: Algorithms rely on variables to store and manipulate data during computation. Data structures like arrays, linked lists, trees, stacks, queues, and more are used to organize and manage data efficiently during the algorithm's execution.

  8. Comments and Documentation: While not directly involved in the execution of the algorithm, comments and documentation serve as crucial building blocks for understanding and maintaining the algorithm. Clear, descriptive comments and documentation help explain the purpose, logic, and functionality of the algorithm to developers and maintainers.

        By employing these building blocks effectively, programmers can design algorithms that are efficient, easy to understand, maintain, and modify. The combination and proper utilization of these building blocks play a significant role in creating robust and functional algorithms.



16. Alogorithm to solve Tower of Hanoi with diagram.

Algorithm:
  1. Start.
  2. Hanoi(disk,source,target,aux)
  3. Move disk from source to target.
  4. Recursively all Hanoi (disk-1,source,aux,target)
  5. Recursively all Hanoi (disk-1,aux,target,source)
  6. Stop.

def tower_of_hanoi(n, source, target, auxiliary):
    if n == 1:
        print(f"Move disk 1 from {source} to {target}")
        return
    tower_of_hanoi(n-1, source, auxiliary, target)
    print(f"Move disk {n} from {source} to {target}")
    tower_of_hanoi(n-1, auxiliary, target, source)

# Example Usage:
n = 3  # Number of disks
tower_of_hanoi(n, 'A', 'C', 'B')  # A, B, and C are the names of the towers






17. Algorithm to insert card in a list.


18. Explain how python works in interactive mode and script mode.


        Python can be used in two primary modes: interactive mode and script mode. Both serve different purposes and have distinct ways of interacting with the Python interpreter.

Interactive Mode:

1. Immediate Execution: In interactive mode, the Python interpreter reads and executes commands entered by the user one by one. It provides immediate feedback and results for each command.

2. Interpreter as a Calculator: Users can type simple commands, mathematical calculations, variable assignments, or function calls directly into the interpreter and immediately see the results.

3. Quick Testing and Experimentation: Interactive mode is great for quick testing, trying out small code snippets, and exploring Python's features in an ad-hoc manner.

How to Access Interactive Mode:

  • You can start the Python interactive mode by opening a terminal or command prompt and typing python or python3, depending on your system configuration.

Script Mode:

1. Script Execution: Script mode involves writing code in a separate file (Python script) that contains multiple lines of Python code. This script is then executed by the Python interpreter from start to finish.

2. Reusability and Maintenance: Script mode is useful for writing larger programs, multiple functions, and complex algorithms. It allows you to organize code into separate files for better reusability and maintainability.

3. File Execution: Python scripts are written in text files with the .py extension. They can be executed by invoking the Python interpreter followed by the script filename.

How to Run Python Scripts:

  • Save your Python code in a file with a .py extension (e.g., my_script.py).
  • To execute the script, use the command python my_script.py in the terminal or command prompt.

Key Differences:

  • Execution: Interactive mode executes commands line by line immediately, while script mode reads and executes the entire script in a file.
  • Ease of Experimentation: Interactive mode allows immediate experimentation and testing, whereas script mode involves a more structured and organized approach.
  • Code Reusability: Scripts can be saved and reused, making it easier to share and collaborate on larger projects.

        In practice, both modes are complementary. Interactive mode is great for quick tests and exploring features, while script mode is essential for developing and running complete programs and applications.



19. Difference b/w inperpreter and compiler.






20. Summarize mathematical operator in python.


        In Python, a mathematical operator is a symbol used to perform arithmetic or mathematical operations on values or variables. Python supports various types of mathematical operators:
  1. Addition (+): Used to add two numbers or concatenate two strings.

  2. Subtraction (-): Used to subtract one number from another.

  3. Multiplication (*): Used to multiply two numbers.

  4. Division (/): Used to divide one number by another. In Python 3.x, this returns a floating-point number.

  5. Floor Division (//): Divides one number by another and returns the floor value (rounding down to the nearest whole number).

  6. Exponentiation (**): Raises a number to the power of another number.

  7. Modulo (%): Returns the remainder of the division of two numbers.




21. Draw a flowchart to find greatest among 3 numbers...>



22. Flowchart to find sum of series of 'n' series.

  1. Start
  2. Input the value of n (the total number of terms in the series)
  3. Set sum = 0
  4. Set i = 1
  5. While i <= n do
  6. sum = sum + i
  7. Increment i by 1
  8. End of While loop
  9. Display the sum of the series
  10. Stop
def sum_of_series(n):
    sum = 0
    for i in range(1, n + 1):
        sum += i
    return sum

# Taking input for the value of n
n = int(input("Enter the value of n: "))

# Calculating the sum of the series and displaying the result
result = sum_of_series(n)
print(f"The sum of the series of {n} numbers is: {result}")


23. What is numerical data type with Examples.


        Numerical data types in programming are used to represent numerical values. These data types allow you to perform arithmetic operations and manipulations on numbers. In most programming languages, numerical data types are categorized into various subtypes based on the size and precision of the numbers they can represent.

Common numerical data types include:

  1. Integer (int): Integers represent whole numbers without any decimal points. They can be positive, negative, or zero. In Python, this data type is int. Example: -5, 0, 42

  2. Floating-Point (float): Floating-point numbers represent real numbers with decimal points. They include both integer and fractional parts. In Python, this data type is float. Example: 3.14, -0.001, 10.0

  3. Double (double precision): In many programming languages, double represents double-precision floating-point numbers, which can store larger decimal numbers with higher precision compared to float. Example: 3.141592653589793, -1234567890.123456789

  4. Long (long int): In certain languages like Python 2 or C/C++, long represents integers of a larger size than regular int types. Python 3 handles arbitrary precision integers, so long isn't a distinct data type.

  5. Complex: This data type represents complex numbers in some programming languages. Complex numbers consist of a real part and an imaginary part. Example: 3 + 4j, -2 - 6j

  6. Decimal: A specialized data type that allows precise floating-point arithmetic, useful in cases where accuracy is critical.




24. To explain detail about arithmetic program in python.

        An arithmetic program in Python is a code that performs basic mathematical operations such as addition, subtraction, multiplication, division, and more. Here's an example program that demonstrates various arithmetic operations:

# Arithmetic operations in Python

# Variables to hold numeric values
a = 10
b = 5

# Addition
addition = a + b
print(f"Addition: {a} + {b} = {addition}")

# Subtraction
subtraction = a - b
print(f"Subtraction: {a} - {b} = {subtraction}")

# Multiplication
multiplication = a * b
print(f"Multiplication: {a} * {b} = {multiplication}")

# Division
division = a / b  # By default, this will result in a float
print(f"Division: {a} / {b} = {division}")

# Floor Division
floor_division = a // b
print(f"Floor Division: {a} // {b} = {floor_division}")

# Modulus (remainder)
modulus = a % b
print(f"Modulus: {a} % {b} = {modulus}")

# Exponentiation
exponentiation = a ** b
print(f"Exponentiation: {a} ** {b} = {exponentiation}")

        This program demonstrates different arithmetic operations in Python using variables 'a' and 'b'. It showcases addition, subtraction, multiplication, division, floor division, modulus (remainder), and exponentiation.

  • Addition (a + b): Adds two numbers.
  • Subtraction (a - b): Subtracts the second number from the first.
  • Multiplication (a * b): Multiplies two numbers.
  • Division (a / b): Divides the first number by the second, resulting in a floating-point number.
  • Floor Division (a // b): Divides and rounds down to the nearest whole number.
  • Modulus (a % b): Gives the remainder of the division.
  • Exponentiation (a ** b): Raises 'a' to the power of 'b'.

Each operation's result is computed and printed with a description.



25. To exchange the value of two variables.



27. Python program to generate fibonaci sequence of series of numbers.

def generate_fibonacci_sequence(n):
    sequence = []
    a, b = 0, 1  # Initializing the first two terms of the sequence

    for i in range(n):
        sequence.append(a)  # Append the current value to the sequence
        a, b = b, a + b  # Update the values for the next iteration

    return sequence

# Take user input for the number of terms in the sequence
terms = int(input("Enter the number of terms for the Fibonacci sequence: "))

# Generate and display the Fibonacci sequence
fib_sequence = generate_fibonacci_sequence(terms)
print(f"The Fibonacci sequence with {terms} terms is: {fib_sequence}")



Post a Comment

0Comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn more
Ok, Go it!