0% found this document useful (0 votes)
27 views3 pages

Python Coding Questions Guide

The document outlines a series of Python coding questions to be completed by July 17, 2024, covering topics such as data types, control flow, lists, functions, dictionaries, strings, input/output, and modules. Each section includes specific programming tasks that require writing code, documenting results, and formatting the final submission as a PDF. The completed PDF must be submitted to the avionics group on Discord.
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)
27 views3 pages

Python Coding Questions Guide

The document outlines a series of Python coding questions to be completed by July 17, 2024, covering topics such as data types, control flow, lists, functions, dictionaries, strings, input/output, and modules. Each section includes specific programming tasks that require writing code, documenting results, and formatting the final submission as a PDF. The completed PDF must be submitted to the avionics group on Discord.
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

Python Coding Questions

Deadline: 17th July, 2024

Instructions:
● Prepare: Understand and plan solutions for each question.
● Code: Write Python code for each question.
● Document: Copy code and capture results in a document.
● Format: Efficiently use pages, add title page, and label solutions.
● Convert: Save as PDF with your name.
● Submit: Send PDF to avionics group on Discord.

Data Types and Variables


1. Integers and Floats: Write a program that takes two numbers from
the user, adds them, and prints the result.
2. Strings: Write a program that takes a user's full name and prints the
initials.
3. Booleans: Write a program that checks if a given number is
divisible by both 3 and 5.
4. Type Conversion: Write a program that converts a given float to an
integer and a string, and prints all three.
5. String Formatting: Write a program that takes a name and age and
prints "Hello, [name]. You are [age] years old."

Control Flow
6. If Statements: Write a program that checks if a given number is
positive, negative, or zero.
7. For Loops: Write a program that prints the first 10 multiples of a
given number.
8. While Loops: Write a program that keeps asking for a number until
the user types in a negative number.
9. Nested If Statements: Write a program that checks if a given year is
a leap year.
10. Range Function: Write a program that prints all prime numbers
between 1 and 50 using a f̀or̀ loop and the r̀angè function.
Lists
11. Basic Operations: Write a program that creates a list of the first
five odd numbers.
12. Indexing and Slicing: Write a program that takes a list of numbers
and prints every second element.
13. List Methods: Write a program that sorts a list of numbers in
ascending order.
14. Appending and Extending: Write a program that takes a list of
names and adds another name to the end, then extends the list with
another list of names.
15. List Comprehensions: Write a program that creates a list of
squares of even numbers between 1 and 20 using a list
comprehension.

Functions
16. Defining Functions: Write a function that takes two numbers and
returns their greatest common divisor (GCD).
17. Function Arguments: Write a function that takes a string and an
optional integer (default value 1), and prints the string repeated that
many times.
18. Default Arguments: Write a function that calculates the area of a
rectangle, where the default length and width are 1 unit each.
19. Returning Values: Write a function that takes a list of numbers
and returns a new list containing only the even numbers.
20. Recursive Functions: Write a recursive function to calculate the
nth Fibonacci number.

Dictionaries
21. Basic Operations: Write a program that creates a dictionary with
keys as student names and values as their scores.
22. Accessing and Modifying: Write a program that updates the score
of a specific student in a dictionary.
23. Dictionary Methods: Write a program that merges two
dictionaries and prints the result.
24. Iterating Through a Dictionary: Write a program that prints each
key-value pair in a dictionary of country-capital pairs.
25. Dictionary Comprehensions: Write a program that creates a
dictionary where the keys are numbers from 1 to 5 and the values are
their factorials.
Strings
26. Concatenation: Write a program that concatenates two strings
with a space in between.
27. String Methods: Write a program that takes a string and prints it
in lowercase, uppercase, and title case.
28. String Slicing: Write a program that takes a string and prints its
first half.
29. String Replacement: Write a program that replaces all vowels in a
string with the letter 'x'.
30. Checking Substrings: Write a program that checks if a given word
is a palindrome.

Input/Output
31. Basic Input: Write a program that takes a user's age and calculates
the year they were born.
32. Reading from a File: Write a program that reads the first 10 lines
of a text file.
33. Writing to a File: Write a program that takes a string from the user
and writes it to a text file, appending it if the file already exists.
34. Appending to a File: Write a program that appends a given list of
strings to a text file, each string on a new line.
35. File Line Count: Write a program that reads a text file and prints
the number of words.

Modules
36. Random Module: Write a program that generates a random
password with 8 characters.
37. Math Module: Write a program that calculates the area of a circle
given its radius using the m̀ath̀ module.
38. Datetime Module: Write a program that calculates the number of
days until a user's next birthday.
39. OS Module: Write a program that lists all files and directories in
the current directory.
40. CSV Module: Write a program that reads a CSV file of student
names and scores, and prints the names and scores of students who
scored above 80.

Common questions

Powered by AI

A recursive function for calculating the nth Fibonacci number involves defining a base case and a recursive step: if `n` is 0 or 1, return `n`; otherwise, return `fib(n-1) + fib(n-2)`. The benefit of recursion is conceptual simplicity; it directly maps the mathematical definition of the Fibonacci sequence into code and simplifies logic for self-referential problems. However, this approach has significant limitations in computational efficiency and risk of stack overflow in Python, especially for large values of `n`. Recursive functions greatly benefit from techniques like memoization to enhance performance by storing results of previous calculations, thus reducing redundant computations .

Converting a float to both an integer and a string can be achieved using type conversion functions in Python: `int()` and `str()`. You might want to convert a float to an integer to perform operations that require whole numbers, avoiding decimal precision. Converting to a string allows for the float to be included in textual outputs or logs, ensuring consistent presentation in user interfaces or reports. This can be useful in cases where formatting and display are separated from numerical computations .

String methods in Python offer optimized and concise ways to transform and format text, such as converting to uppercase or replacing substrings. These methods are built-in and leverage Python's underlying C-optimized string processing capabilities, which results in better performance compared to manual iteration techniques that require explicit loops and condition checks. String methods promote maintainability and readability, encapsulating complex operations with descriptive function names, reducing potential errors associated with loop control and mutable string behaviors in manual methods .

When using a while loop to repeatedly request input until a negative number is entered, consider loop control, input validation, and termination criteria. Ensure correct implementation of the loop condition to prevent infinite loops and handle potential input errors using try-except blocks or input validation to manage non-numeric inputs gracefully. Consider user experience, providing clear instructions and error messages for invalid inputs to guide users appropriately. Additionally, design the loop to handle edge cases, such as when zero or negative numbers are immediately entered, requiring clear expectations on stopping conditions .

Iterating over key-value pairs in dictionary data structures has a time complexity of O(n), where n is the number of key-value pairs in the dictionary. This is efficient for typical use cases such as data aggregation, transformation, and extraction tasks in applications where relationships between items are critical. Effective key-value pair iteration supports operations like lookups, modifications, and dynamic data representation. However, poorly optimized iteration can affect performance in large-scale applications if used alongside high-complexity operations without concurrent optimizations or efficient data access strategies .

Default arguments in Python functions provide flexibility and reduce the need for specifying every argument every time a function is called, which simplifies the interface for common use cases. However, this can lead to less documentation or understanding among developers about intended or potential use cases, as well as potential logical errors if default values do not suit all contexts. Requiring all arguments increases clarity and forces the caller to provide necessary information for each call, ensuring that the function operates as intended without assumptions about default behavior .

Merging dictionaries in Python can be done using the `{**dict1, **dict2}` syntax or the `update()` method. This approach helps manage data from different sources in a unified structure, allowing for efficient data retrieval, storage, and processing in applications. It supports consolidation of configurations, aggregated datasets, or representation of complex relationships, which simplifies tasks like data synchronization or integration of varied data inputs. Adopting this method is crucial in larger applications where modular design and scalability are prioritized .

List comprehension is beneficial for generating a list of squares of even numbers because it provides a concise and readable syntax that efficiently handles iteration and conditionals in a single line. This contrasts with traditional looping methods that require multiple lines for loop setup, condition checking, and list appending, which can introduce boilerplate code and potential for errors. List comprehensions also enhance performance slightly by utilizing Python's internal optimizations, offering a clear and declarative expression of the problem .

To determine if a year is a leap year, evaluate conditions based on the rules defined by the Gregorian calendar: A year is a leap year if it is divisible by 4; it is not a leap year if it is divisible by 100 unless it is also divisible by 400. Thus, check these conditions in sequence: first check divisibility by 400, then by 100, and finally by 4. This sequence ensures that exceptions for century years are correctly applied before straightforward rules, which avoids incorrect results due to order of conditions .

Importing Python's math module enhances computational tasks by providing access to numerous mathematical functions, such as trigonometric and logarithmic functions, that are essential for geospatial applications. For calculating areas and distances precisely, the `math` module allows functions like `sqrt` for Euclidean distances or `sin` and `cos` for angular conversions in geographic coordinates. These utilities enable the precise computation of areas of irregular shapes on maps or calculating distances between GPS coordinates with minimal error, supporting tasks in navigation, GIS, and spatial data analysis .

You might also like