Python Practice Questions

Version: 2.6 | Last Updated: 2024

Essential guidelines for writing reliable, safe, and efficient CoDrone EDU Python code

Python Practice Questions

Test your Python programming knowledge with these 50 practice questions. Click on each question to expand and see the answer. Try to answer each question before checking the solution!

Q1 What is the output of: print(2 + 3 * 4)?

Answer: 14 (multiplication happens first: 2 + 12 = 14)

Q2 What is the difference between = and == in Python?

Answer: = is assignment (x = 5), == is comparison (x == 5 returns True/False)

Q3 What does the range(5) function return?

Answer: A sequence of numbers from 0 to 4: [0, 1, 2, 3, 4]

Q4 How do you get the length of a list in Python?

Answer: Use len() function: len(my_list)

Q5 What is the difference between a list and a tuple?

Answer: Lists are mutable (can be changed), tuples are immutable (cannot be changed)

Q6 What does the append() method do for lists?

Answer: Adds an item to the end of the list: my_list.append(item)

Q7 How do you access the first element of a list?

Answer: Use index 0: my_list[0]

Q8 What is a for loop used for?

Answer: To iterate over a sequence (list, string, range, etc.) and execute code for each item

Q9 What is the difference between break and continue in loops?

Answer: break exits the loop completely, continue skips to the next iteration

Q10 How do you define a function in Python?

Answer: Use def keyword: def my_function():

Q11 What is a return statement used for?

Answer: To return a value from a function

Q12 What does if __name__ == '__main__': do?

Answer: Ensures code only runs when the script is executed directly, not when imported

Q13 How do you import a module in Python?

Answer: Use import: import math or from math import sqrt

Q14 What is the difference between a string and an integer?

Answer: String is text ("hello"), integer is a number (5)

Q15 How do you convert a string to an integer?

Answer: Use int(): int("5") returns 5

Q16 What does the str() function do?

Answer: Converts a value to a string: str(5) returns "5"

Q17 What is a dictionary in Python?

Answer: A collection of key-value pairs: {"name": "John", "age": 25}

Q18 How do you access a value in a dictionary?

Answer: Use the key: my_dict["name"] or my_dict.get("name")

Q19 What does the .keys() method return for dictionaries?

Answer: A view of all keys in the dictionary

Q20 What is a while loop?

Answer: A loop that continues as long as a condition is True

Q21 What is an infinite loop and how do you avoid it?

Answer: A loop that never ends. Avoid by ensuring the condition eventually becomes False

Q22 What does the len() function return for a string?

Answer: The number of characters in the string

Q23 How do you check if a value is in a list?

Answer: Use 'in' operator: if item in my_list:

Q24 What is the difference between and, or, and not?

Answer: and: both conditions True, or: at least one True, not: reverses True/False

Q25 What does the % operator do?

Answer: Modulo - returns the remainder: 10 % 3 returns 1

Q26 What is a list comprehension?

Answer: A concise way to create lists: [x*2 for x in range(5)]

Q27 What does the .split() method do for strings?

Answer: Splits a string into a list: "hello world".split() returns ["hello", "world"]

Q28 How do you join a list of strings?

Answer: Use .join(): " ".join(["hello", "world"]) returns "hello world"

Q29 What is the difference between .append() and .extend() for lists?

Answer: append adds one item, extend adds all items from another list

Q30 What does the .pop() method do for lists?

Answer: Removes and returns the last item (or item at specified index)

Q31 What is a try-except block used for?

Answer: To handle errors gracefully and prevent program crashes

Q32 What is the difference between a function and a method?

Answer: A method is a function that belongs to an object: my_list.append()

Q33 What does the pass statement do?

Answer: Does nothing - used as a placeholder for empty code blocks

Q34 How do you create an empty list?

Answer: my_list = [] or my_list = list()

Q35 What does the .strip() method do for strings?

Answer: Removes whitespace from the beginning and end: " hello ".strip() returns "hello"

Q36 What is the difference between == and is?

Answer: == compares values, is compares object identity (memory location)

Q37 What does the .upper() method do for strings?

Answer: Converts all characters to uppercase: "hello".upper() returns "HELLO"

Q38 How do you get user input in Python?

Answer: Use input(): name = input("Enter your name: ")

Q39 What does the .lower() method do for strings?

Answer: Converts all characters to lowercase: "HELLO".lower() returns "hello"

Q40 What is a slice in Python?

Answer: A way to get a portion of a sequence: my_list[1:4] gets items at indices 1, 2, 3

Q41 What does [::-1] do to a list?

Answer: Reverses the list: [1,2,3][::-1] returns [3,2,1]

Q42 What is the difference between global and local variables?

Answer: Global: accessible everywhere, Local: only in the function where defined

Q43 What does the .count() method do for lists?

Answer: Returns the number of times an item appears: my_list.count(5)

Q44 How do you sort a list?

Answer: Use .sort() method (modifies list) or sorted() function (returns new list)

Q45 What is a default parameter in a function?

Answer: A parameter with a default value: def greet(name="Guest"):

Q46 What does the *args parameter do?

Answer: Allows a function to accept any number of positional arguments

Q47 What does the **kwargs parameter do?

Answer: Allows a function to accept any number of keyword arguments

Q48 What is a lambda function?

Answer: A small anonymous function: lambda x: x * 2

Q49 What does the .items() method return for dictionaries?

Answer: A view of key-value pairs: dict.items() returns [(key1, value1), ...]

Q50 What is the difference between .remove() and .del for lists?

Answer: .remove() removes by value, del removes by index


← Back to Main Documentation

Connection Management

Always Close Connections

Always call close() at the end of your program to properly disconnect the drone and free resources.

from codrone_edu.drone import *

drone = Drone()
try:
    drone.pair()
    # Your code here
finally:
    drone.close()  # Always executed

💡 Tip: Use Try-Finally

Wrap your code in a try-finally block to ensure close() is always called, even if an error occurs.

Reliable Pairing

For more reliable pairing, specify the USB port name explicitly, especially on Windows systems.

# Windows
drone.pair("COM3")

# Linux/Mac
drone.pair("/dev/ttyUSB0")

Flight Safety

Always Include Hover Delays

Include hover() or time.sleep() between takeoff() and land() to prevent commands from being missed.

drone.takeoff()
drone.hover(1)  # Always include this!
drone.land()

⚠️ Warning

Without a hover delay, the land() command may be missed, causing the drone to continue flying.

Use Appropriate Power Levels

Start with lower power levels (20-40%) for testing, then increase as needed. Higher power levels consume more battery and are harder to control.

# Good: Start with lower power
drone.go("forward", 30, 1)

# Avoid: Too high power for indoor use
# drone.go("forward", 90, 1)  # Too fast!

Test in Safe Environments

Always test your code in a safe, open area with sufficient clearance. Ensure there are no obstacles, people, or pets nearby.

Code Organization

Use Constants for Configuration

Define constants at the top of your file for easy adjustment of power levels, durations, and other parameters.

# Configuration constants
POWER_LEVEL = 30
DURATION = 1.0
HOVER_TIME = 2

drone = Drone()
drone.pair()
drone.takeoff()
drone.go("forward", POWER_LEVEL, DURATION)
drone.hover(HOVER_TIME)
drone.land()
drone.close()

✅ Best Practice

Using constants makes your code more maintainable and easier to adjust for different flight conditions.

Organize Code into Functions

Break your code into logical functions for better readability and reusability.

def fly_square(drone, power=30, duration=1):
    """Fly in a square pattern."""
    for direction in ["forward", "right", "backward", "left"]:
        drone.go(direction, power, duration)
        drone.hover(0.5)

drone = Drone()
drone.pair()
drone.takeoff()
fly_square(drone)
drone.land()
drone.close()

Sensor Usage

Check Sensor Ranges

Always verify sensor ranges before using them. Different sensors have different effective ranges.

# Front range sensor: 0-100cm
front_range = drone.get_front_range()
if front_range < 20:  # Too close!
    drone.go("backward", 30, 1)

Use Sensor Data for Decision Making

Combine sensor readings with conditional logic for intelligent flight behavior.

while True:
    distance = drone.get_front_range()
    if distance < 50:
        drone.go("right", 30, 1)
    else:
        drone.go("forward", 30, 1)
    time.sleep(0.1)

Error Handling

Handle Connection Errors

Always check if pairing was successful before attempting to fly.

try:
    drone.pair()
    # Check if paired successfully
    if drone.get_flight_state() == "connected":
        drone.takeoff()
    else:
        print("Failed to connect")
except Exception as e:
    print(f"Error: {e}")
finally:
    drone.close()

Use Emergency Stop

Always have a way to immediately stop the drone in case of unexpected behavior.

try:
    # Your flight code
    drone.takeoff()
    # ... flight commands ...
except KeyboardInterrupt:
    drone.emergency_stop()  # Stop immediately!
    drone.close()

⚠️ Critical

emergency_stop() immediately stops all motors. Use only in emergency situations. The drone will fall, so ensure you're in a safe environment.

Performance Optimization

Minimize Unnecessary Delays

Use appropriate hover times. Too short may cause missed commands, too long wastes battery.

# Good: Appropriate hover time
drone.go("forward", 30, 1)
drone.hover(0.5)  # Stabilize before next command

# Avoid: Too long hover times
# drone.hover(10)  # Wastes battery!

Batch Similar Operations

Group similar operations together to reduce communication overhead.

# Good: Batch LED operations
drone.set_drone_LED(255, 0, 0, 100)  # Red
time.sleep(1)
drone.set_drone_LED(0, 255, 0, 100)  # Green
time.sleep(1)
drone.set_drone_LED(0, 0, 255, 100)  # Blue

Common Mistakes to Avoid

1. Forgetting to Close

Always call close() at the end of your program.

2. Missing Hover Delays

Never call land() immediately after takeoff() without a hover delay.

3. Using Too High Power

Start with lower power levels (20-40%) and increase gradually as needed.

4. Not Checking Sensor Ranges

Always verify sensor readings are within valid ranges before using them.

5. Ignoring Error Handling

Always include error handling, especially for connection and flight operations.

Summary

✅ Key Takeaways


← Back to Documentation | Version: 2.6 | Last Updated: 2024