0% found this document useful (0 votes)
22 views12 pages

Viva Questions

The document contains a series of questions and answers related to Python programming and MySQL database management. Key topics include Python features, data types, functions, error handling, and database operations such as connecting to a database, managing tables, and performing queries. It serves as a comprehensive guide for understanding fundamental concepts in Python and SQL.

Uploaded by

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

Viva Questions

The document contains a series of questions and answers related to Python programming and MySQL database management. Key topics include Python features, data types, functions, error handling, and database operations such as connecting to a database, managing tables, and performing queries. It serves as a comprehensive guide for understanding fundamental concepts in Python and SQL.

Uploaded by

Mannu Barthwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

VIVA QUESTIONS

1. What is Python? What are the benefits of using Python?

o Python is a high-level, interpreted programming language known for its simplicity


and readability. Benefits include easy syntax, extensive libraries, cross-platform
compatibility, and versatility for tasks like web development, data analysis, and
automation.

2. What is pickling and unpickling?

o Pickling is the process of converting a Python object into a byte stream for storage
or transfer. Unpickling is the reverse process, converting the byte stream back into
a Python object.

3. What is the difference between list and tuple?

o Lists are mutable (modifiable), while tuples are immutable (read-only). Lists use
square brackets [], and tuples use parentheses ().

4. What are the built-in types that Python provides?

o Python provides types like integers, floats, complex numbers, strings, lists, tuples,
dictionaries, sets, and boolean.

5. What is namespace in Python?

o A namespace is a container where names are mapped to objects, ensuring no


name conflicts.

6. What is pass in Python?

o The pass statement is a placeholder that does nothing. It's used where a statement
is syntactically required but no code is needed.

7. What is slicing in Python?

o Slicing extracts parts of sequences like lists, strings, or tuples using the syntax
start:stop:step.

8. What is docstring in Python?

o A docstring is a string used to document a function, class, or module. It's enclosed


in triple quotes.

9. What is negative index in Python?

o Negative indices access elements from the end of a sequence. For example, -1
refers to the last element.

10. How can you convert a number into a string?

o Use the str() function: str(123) returns '123'.

11. What do you understand by module and package in Python?

o A module is a single Python file with reusable code. A package is a collection of


modules grouped together.

12. What are the rules for local and global variables in Python?

o Local variables are defined inside a function and have limited scope. Global
variables are defined outside any function and can be accessed throughout the
program.

13. How can you generate random numbers in Python?


o Use the random module, e.g., random.randint(1, 10) generates a random integer
between 1 and 10.

14. What is the use of // operator in Python?

o The // operator performs floor division, returning the largest integer less than or
equal to the division result.

15. Mention five benefits of using Python.

o Easy to learn, versatile, vast library support, cross-platform compatibility, and


active community.

16. Mention the use of the split function in Python.

o The split() function splits a string into a list based on a delimiter.

17. What are literals in Python?

o Literals are fixed values in a program, such as numeric, string, boolean, and special
literals like None.

18. Explain Python functions.

o Functions are blocks of reusable code that perform a specific task. They are defined
using the def keyword.

19. Name the different file processing modes supported by Python.

o Modes include r (read), w (write), a (append), b (binary), and + (read/write).

20. What is an operator in Python?

o An operator is a symbol that performs operations on variables or values, such as +,


-, or *.

21. What are the different types of operators in Python?

o Arithmetic, comparison, logical, assignment, bitwise, membership, and identity


operators.

22. What is a Dictionary in Python?

o A dictionary is a collection of key-value pairs, defined using {}.

23. Explain the use of TRY: EXCEPT:

o Used for error handling. Code in try is executed, and errors are caught in except.

24. What is the purpose of PYTHONPATH environment variable?

o It specifies directories where Python looks for modules.

25. What are the supported data types in Python?

o Numeric, sequence, mapping, set, boolean, and none.

26. What is the difference between lists and tuples?

o Lists are mutable; tuples are immutable.

27. How will you reverse a list?

o Use list.reverse() or list[::-1].

28. What is a string in Python?

o A sequence of characters enclosed in quotes.


29. Why is the Return keyword used in Python?

o To return a value from a function.

30. When should you use the “Break” in Python?

o To exit a loop prematurely.

31. What is a tuple in Python?

o An immutable sequence of items.

32. Explain the use of “with” statement.

o Simplifies file handling by automatically closing the file.

33. Differentiate between append() and extend() methods.

o append() adds an item; extend() adds elements from another iterable.

34. What are the advantages of Python recursion?

o Simplifies complex problems, but can lead to high memory usage.

35. How can we get current directory using Python?

o Use os.getcwd() from the os module.

36. What is the difference between del keyword and drop()?

o del deletes variables or elements; drop() is a pandas method to remove


rows/columns.

37. What is primary key?

o A unique identifier for a database record.

38. What is candidate key?

o A set of attributes that can uniquely identify a record.

39. What is foreign key?

o An attribute linking two tables.

40. What is alternate key?

o A candidate key not chosen as the primary key.

41. What is MYSQL?

o An open-source RDBMS.

42. What is RDBMS?

o Relational Database Management System.

43. What is the use of drop command in SQL?

o Deletes a table or database.

44. What do you understand by NOT NULL constraint?

o Ensures a column cannot have a NULL value.

45. What is the significance of COUNT?

o Counts the number of rows matching a condition.

46. How can we delete a table in MYSQL?


o Use DROP TABLE table_name.

47. How can we delete a record in MYSQL?

o Use DELETE FROM table_name WHERE condition.

48. How can we add a record and add a column in a table?

o Use INSERT INTO for records and ALTER TABLE for columns.

49. What is the difference between del and remove methods of list?

o del removes by index; remove() removes by value.

50. What is the output of for x in [1, 2, 3]: print x?

o Syntax error. Correct syntax: print(x).

51. What is the return keyword used for in Python?

o To return values from a function.

52. What is the purpose of id() in python?

o Returns the unique ID of an object.

53. How would you convert a string into lowercase?

o Use str.lower().

54. print(‘Ayushi’.isupper())

o Output: False.

55. Write output of the following:

56. for i in range(7):

57. if i == 3:

58. continue

59. print(i)

o Output: 0, 1, 2, 4, 5, 6.

60. What are membership operators?

o Operators to check membership in a sequence: in and not in.

61. What are identity operators?

o Operators to check object identity: is and is not.

62. How do you calculate the number of characters of the string ‘Ayushi Sharma’?

o Use len('Ayushi Sharma').

63. How will you print the string ‘Python’ five times?

o Use 'Python' * 5.

64. What is the difference between list and dictionary?

o Lists are ordered and indexed by position; dictionaries are unordered and indexed
by keys.

...

61. What is pickling and unpickling?


 Pickling serializes a Python object into a byte stream, while unpickling deserializes the byte
stream back into a Python object.

62. What are Python Libraries? Name any two.

 Python libraries are reusable code collections. Examples: NumPy (numerical computations),
Pandas (data manipulation).

63. What are the three ways to import modules in Python?

 import module_name

 from module_name import specific_function

 from module_name import *

64. What is the difference between char and varchar in MYSQL?

 CHAR is a fixed-length data type; VARCHAR is variable-length.

65. What is the difference between primary key and candidate key?

 A primary key is the chosen unique identifier for a table. Candidate keys are potential
primary keys.

66. What is the difference between NOW() and CURRENT_DATE()?

 NOW() returns the current date and time; CURRENT_DATE() returns the date only.

67. What is the difference between SQL and MYSQL?

 SQL is a query language; MySQL is an RDBMS that uses SQL.

68. What is the difference between database and table in MYSQL?

 A database is a collection of related tables; a table is a structured collection of data.

69. How to add columns in MYSQL?

 Use ALTER TABLE table_name ADD column_name column_type;

70. How to delete a table in MYSQL?

 Use DROP TABLE table_name;

71. How to create a table in MYSQL?

 Use CREATE TABLE table_name (column_name column_type, ...);

72. How to delete columns in a table in MYSQL?

 Use ALTER TABLE table_name DROP COLUMN column_name;

73. How to insert data in MYSQL?

 Use INSERT INTO table_name (columns) VALUES (values);

74. How to delete a row in MYSQL?

 Use DELETE FROM table_name WHERE condition;

75. How to join two tables in MYSQL?

 Use SQL JOINs like INNER JOIN, LEFT JOIN, or RIGHT JOIN:

SELECT columns FROM table1 JOIN table2 ON table1.column = table2.column;


PROJECT QUESTIONS
1. What does the function connect_to_database do?

The connect_to_database function is used to establish a connection to a MySQL database. It can


connect to the MySQL server without a database (db_name=None), or it can connect to a specific
database if one is provided. It uses mysql.connector.connect to connect to the database and
returns the connection object.

2. What is the purpose of the user_login function?

The user_login function prompts the user to input a username and password. It checks the entered
credentials against predefined values (username="admin" and password="bps@2024"). If the
credentials match, it returns True, indicating a successful login. Otherwise, it returns False and
prints an "Invalid credentials" message.

3. What does the main_menu function do?

The main_menu function presents the main menu options to the user, allowing them to select
different actions such as showing databases, creating a database, adding students, updating
records, sorting records, etc. The function runs in a loop, offering the user a chance to select
options until the user chooses to quit the program (option 16).

4. What is the function of the choose_database method?

The choose_database function allows the user to select a database from the available databases on
the MySQL server. It first lists all the databases, then prompts the user to choose one by entering
the corresponding number. It sets the selected database as the global variable DATABASE.

5. What does the add_student function do?

The add_student function allows the user to add a student to the database. The user is prompted to
input the student's roll number, name, stream, total marks, grade, class, and batch. The function
inserts this data into the selected table and adds the student to a specific batch (using the
add_student_to_batch function).

6. What does the display_students_by_batch function do?

The display_students_by_batch function displays student details (like roll number, name, stream,
total marks, grade, and class) for each batch stored in the BATCHES dictionary. It retrieves the
student information from the database for each roll number in the batch.

7. How does the add_student_to_batch function work?

The add_student_to_batch function adds the student (identified by their roll number) to a specific
batch. The batches are stored in the BATCHES dictionary, where the key is the batch name, and the
value is a list of student roll numbers. If the batch does not exist, it creates a new entry.

8. What is the role of the get_grade_conditions function?

The get_grade_conditions function gathers grade conditions from the user. It allows the user to
input grade thresholds (minimum marks required for each grade), and these conditions are
returned as a list of tuples containing the grade and the minimum marks. The user can input
multiple grades or enter "done" to finish.

9. How does the calculate_grade function work?

The calculate_grade function calculates the grade of a student based on their marks and the grade
conditions. It iterates through the list of grade conditions (as returned by get_grade_conditions)
and assigns the highest grade that meets the condition of the student's marks.
10. How does the sort_records function work?

The sort_records function allows the user to sort records in the selected table based on a column
and the specified order (ascending or descending). The user is prompted for the column name and
the order (ASC for ascending or DESC for descending). The function then constructs a SELECT
query to retrieve the sorted records and displays them.

11. What is the show_databases function doing?

The show_databases function lists all the databases available in the MySQL server. It executes the
SQL query SHOW DATABASES and prints the names of the databases.

12. How does the choose_table function work?

The choose_table function allows the user to choose a table from the available tables in the
selected database. It first lists all the tables and prompts the user to input the name of the table
they want to work with.

13. What happens when the create_table function is called?

The create_table function creates a new table in the selected database if both DATABASE and
TABLE are set. The table has columns for roll number, name, stream, total marks, grade, and class.
If the table creation is successful, a confirmation message is printed.

14. What is the function show_tables used for?

The show_tables function lists all the tables present in the selected database. It executes the SQL
query SHOW TABLES to retrieve the table names.

15. What does the display_structure function do?

The display_structure function shows the structure (schema) of the current table. It executes the
DESC {TABLE} SQL query to display the column names, data types, and other properties of the
table.

Let me know if you need additional details or further clarification on any of the questions!

4o mini

You said:

answer all quesions

ChatGPT said:

ChatGPT

It seems like you are asking for answers to a comprehensive set of questions that might arise from
the code you shared, or perhaps you are referring to questions related to the code's logic and
functionality. I’ll assume you meant a breakdown of what the code does in a general sense, and I’ll
go through the questions systematically.

Here are answers to the questions that might arise from this code:

1. What does the connect_to_database function do?

The connect_to_database function is used to establish a connection to the MySQL database. It does
this by calling mysql.connector.connect() with parameters like host, user, password, and database
name. It returns a connection object that can be used to interact with the MySQL database. The
function is designed to return the connection for use in other parts of the program.

2. What is the purpose of the user_login function?

The user_login function is a simple login function that prompts the user for a username and
password. It checks whether the entered credentials match predefined ones (username="admin",
password="bps@2024"). If the credentials match, it returns True, indicating a successful login;
otherwise, it returns False, showing "Invalid credentials."
3. What does the main_menu function do?

The main_menu function presents a list of options to the user, allowing them to interact with the
database. It provides actions such as viewing databases, creating a database, adding students,
sorting records, updating student information, and quitting the application. The user chooses
options by entering corresponding numbers, and the menu loops until the user selects the option to
quit.

4. What is the function of the choose_database method?

The choose_database method allows the user to select a database from the list of databases
present on the MySQL server. It queries the list of databases and then prompts the user to choose
one. Once the database is chosen, it sets the DATABASE variable to the selected database, which is
used for subsequent operations like creating tables or adding records.

5. What does the add_student function do?

The add_student function enables the user to add a new student to the database. It asks for details
like roll number, name, stream, total marks, grade, class, and batch. The student’s information is
then inserted into the selected database using an INSERT INTO SQL statement. The function also
calls add_student_to_batch to associate the student with a specific batch.

6. What does the display_students_by_batch function do?

The display_students_by_batch function displays student records by batch. It fetches the list of
students from each batch (stored in the BATCHES dictionary) and retrieves the details of each
student from the database. The student details include roll number, name, stream, total marks,
grade, and class.

7. How does the add_student_to_batch function work?

The add_student_to_batch function adds a student (identified by their roll number) to a batch. It
uses a dictionary called BATCHES, where the key is the batch name, and the value is a list of
student roll numbers. If the batch does not already exist, the function creates a new entry in the
dictionary for that batch. The student is then added to the corresponding list of students.

8. What is the role of the get_grade_conditions function?

The get_grade_conditions function collects grade conditions from the user. It asks the user to input
grade thresholds (minimum marks for each grade). For example, it may ask for the number of
marks required for each grade like A, B, C, etc. The user can input these thresholds for multiple
grades and finish the input by typing "done". The function returns these conditions as a list of
tuples.

9. How does the calculate_grade function work?

The calculate_grade function determines the grade of a student based on their marks and the
grade conditions (which are retrieved by the get_grade_conditions function). It compares the
student's marks to the grade conditions, and the highest grade that meets the condition is
assigned to the student.

10. How does the sort_records function work?

The sort_records function allows the user to sort records in a database table. The user is prompted
to select a column by which to sort, as well as the sorting order (ASC for ascending or DESC for
descending). The function constructs an SQL SELECT query with the ORDER BY clause and executes
it to display the sorted results.

11. What is the show_databases function doing?

The show_databases function retrieves and lists all the databases present on the MySQL server. It
executes the SQL query SHOW DATABASES and prints each database name, allowing the user to
view all available databases.
12. How does the choose_table function work?

The choose_table function lets the user select a table from the available tables in the chosen
database. The user is first shown a list of tables in the database and then prompted to enter the
name of the table they want to work with. The function stores this choice for later operations, such
as querying or modifying records in that table.

13. What happens when the create_table function is called?

When the create_table function is called, it creates a table in the current database. The table
consists of columns for the student’s roll number, name, stream, total marks, grade, and class. If
the table is successfully created, a success message is printed. The function relies on the selected
database being active and available.

14. What is the show_tables function used for?

The show_tables function lists all the tables in the selected database. It executes the SHOW TABLES
SQL query, which retrieves the names of all tables in the current database, and prints them for the
user.

15. What does the display_structure function do?

The display_structure function shows the structure (schema) of the current table. It executes the
DESC {TABLE} SQL command, which retrieves information about the columns in the table, such as
the column names, data types, and other attributes. This allows the user to view the layout of the
table.

NOTES

1. Menu-Driven Program (Experiment No. 1)

 Functions: input() to get user choice, print() to display the menu and results.

 Math: math.pi for calculating the area of a circle.

 Modules: math for mathematical functions (if needed).

 Commands: if-else for decision making.

2. Convert While Loop to For Loop (Experiment No. 2)

 Commands: while, for, range()

 Purpose: This experiment involves converting a while loop to a for loop, likely using
range() to iterate a specific number of times.

3. Quadratic Equation Roots (Experiment No. 3)

 Functions: input() for user input, math.sqrt() for square root calculation.

 Commands: Conditional checks (if-else) to check for real and complex roots.

 Math: Quadratic formula: (-b ± sqrt(b² - 4ac)) / 2a

4. Oldest and Youngest Person (Experiment No. 4)

 Functions: input() for user input, min() and max() to find the youngest and oldest.

 Commands: Conditional statements and comparisons.

5. Prime or Composite Number (Experiment No. 5)

 Functions: input() for user input, for loop for checking divisibility.

 Commands: if-else for prime/composite check.

6. Search Number in List (Experiment No. 6)

 Functions: input() for user input, in operator for list search.


 Commands: for loop for searching through the list.

7. Phone Number Validation (Experiment No. 7)

 Functions: input() for user input.

 Modules: re (regular expressions) for pattern matching to validate the phone number
format.

 Commands: if-else for checking the validity.

8. Swap List Halves (Experiment No. 8)

 Functions: Slicing (list[:len(list)//2], list[len(list)//2:]).

 Commands: List slicing and swapping.

9. Nth Fibonacci Number (Experiment No. 9)

 Functions: Recursive or iterative function to generate the Fibonacci sequence.

 Commands: for loop or recursion.

10. Count Lines Starting with Digit in File (Experiment No. 10)

 Modules: open() to read the file.

 Commands: startswith() to check if a line starts with a digit.

11. Case Invert in File (Experiment No. 11)

 Modules: open() to read and write files.

 Functions: str.swapcase() to invert case.

12. Count Blank Spaces in File (Experiment No. 12)

 Modules: open() to read the file.

 Functions: str.count(' ') to count spaces.

13. Search Character in File (Experiment No. 13)

 Modules: open() to read the file.

 Commands: str.count() to find occurrences of a character.

14. Pickle Module for Binary Files (Experiment No. 14)

 Modules: pickle to serialize and deserialize Python objects.

 Commands: pickle.dump() and pickle.load() for writing and reading from binary files.

15. Reverse String (Experiment No. 15)

 Functions: Slicing (str[::-1]) to reverse the string.

 Commands: print() to display the reversed string.

16. Stack Implementation with Lists (Experiment No. 16)

 Commands: List methods like append() for pushing and pop() for popping elements.

 Functions: Define functions for stack operations (push, pop, peek).

17-20. MySQL Integration (Experiments No. 17-20)

 Modules: mysql.connector for interacting with MySQL.

 Functions: connect() to establish a connection, cursor.execute() to run queries, fetchall()


to get results.
 Commands: SQL commands like CREATE TABLE, INSERT, SELECT, UPDATE.

21. Insert Records into MySQL (Experiment No. 21)

 Modules: mysql.connector for MySQL integration.

 Commands: INSERT INTO SQL command.

22-25. SQL Queries (Experiments No. 22-25)

 Commands: SQL queries like SELECT, JOIN, GROUP BY, ORDER BY, WHERE, and COUNT.

Python Programs

Concepts:

 Docstrings: Lines starting with triple quotes (""") are used to document the code's purpose
and functionality.

 Comments: Lines starting with # are comments and are ignored by the Python interpreter.

 Input/Output: The input() function is used to get user input, and the print() function is used
to display output.

 Loops: for and while loops are used to iterate over sequences of data.

 Conditional Statements: if, elif, and else statements are used to control the flow of the
program based on conditions.

 Functions: Python functions are defined using the def keyword and can be used to
encapsulate reusable blocks of code.

Explanation:

The document outlines various Python programs but doesn't provide the complete code for each.
However, it mentions the concepts used in these programs.

2. SQL Queries

Concepts:

 SQL (Structured Query Language): A language used to interact with relational databases.

 SELECT: Clause used to retrieve data from tables.

 FROM: Clause specifies the table(s) from which data is retrieved.

 WHERE: Clause used to filter data based on conditions.

 GROUP BY: Clause used to group data by one or more columns.

 HAVING: Clause used to filter grouped data.

 ORDER BY: Clause used to sort the results of a query.

 JOIN: Clauses used to combine data from multiple tables.

 CREATE TABLE: Statement used to create a new table in a database.

 INSERT INTO: Statement used to insert new rows of data into a table.

 UPDATE: Statement used to modify existing data in a table.

 DELETE FROM: Statement used to delete rows from a table.

Explanation:
The document presents various SQL queries but doesn't provide the complete code for each query.
However, it mentions the concepts used in these queries.

3. Specific Code Examples

While the document doesn't provide complete code examples, here are explanations for some
concepts mentioned:

Example 1: Swapping elements in a list (Explanation without code)

This concept likely involves a function that takes a list as input and swaps the elements in the first
half with the elements in the second half. The function might achieve this by:

1. Finding the middle index of the list.

2. Slicing the list into two halves (first half and second half).

3. Creating a temporary variable to store the second half.

4. Assigning the second half to the first half of the list.

5. Assigning the temporary variable (originally containing the second half) to the second half
of the list (now containing the first half elements).

Example 2: Counting lines starting with a digit in a text file (Explanation without code)

This concept likely involves a function that takes the filename as input and returns the number of
lines starting with a digit. The function might achieve this by:

1. Opening the file in read mode.

2. Iterating over each line in the file.

3. Using a regular expression to check if the line starts with a digit.

4. If the line starts with a digit, increment a counter.

5. After iterating over all lines, return the counter value.

You might also like