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!
Answer: 14 (multiplication happens first: 2 + 12 = 14)
Answer: = is assignment (x = 5), == is comparison (x == 5 returns True/False)
Answer: A sequence of numbers from 0 to 4: [0, 1, 2, 3, 4]
Answer: Use len() function: len(my_list)
Answer: Lists are mutable (can be changed), tuples are immutable (cannot be changed)
Answer: Adds an item to the end of the list: my_list.append(item)
Answer: Use index 0: my_list[0]
Answer: To iterate over a sequence (list, string, range, etc.) and execute code for each item
Answer: break exits the loop completely, continue skips to the next iteration
Answer: Use def keyword: def my_function():
Answer: To return a value from a function
Answer: Ensures code only runs when the script is executed directly, not when imported
Answer: Use import: import math or from math import sqrt
Answer: String is text ("hello"), integer is a number (5)
Answer: Use int(): int("5") returns 5
Answer: Converts a value to a string: str(5) returns "5"
Answer: A collection of key-value pairs: {"name": "John", "age": 25}
Answer: Use the key: my_dict["name"] or my_dict.get("name")
Answer: A view of all keys in the dictionary
Answer: A loop that continues as long as a condition is True
Answer: A loop that never ends. Avoid by ensuring the condition eventually becomes False
Answer: The number of characters in the string
Answer: Use 'in' operator: if item in my_list:
Answer: and: both conditions True, or: at least one True, not: reverses True/False
Answer: Modulo - returns the remainder: 10 % 3 returns 1
Answer: A concise way to create lists: [x*2 for x in range(5)]
Answer: Splits a string into a list: "hello world".split() returns ["hello", "world"]
Answer: Use .join(): " ".join(["hello", "world"]) returns "hello world"
Answer: append adds one item, extend adds all items from another list
Answer: Removes and returns the last item (or item at specified index)
Answer: To handle errors gracefully and prevent program crashes
Answer: A method is a function that belongs to an object: my_list.append()
Answer: Does nothing - used as a placeholder for empty code blocks
Answer: my_list = [] or my_list = list()
Answer: Removes whitespace from the beginning and end: " hello ".strip() returns "hello"
Answer: == compares values, is compares object identity (memory location)
Answer: Converts all characters to uppercase: "hello".upper() returns "HELLO"
Answer: Use input(): name = input("Enter your name: ")
Answer: Converts all characters to lowercase: "HELLO".lower() returns "hello"
Answer: A way to get a portion of a sequence: my_list[1:4] gets items at indices 1, 2, 3
Answer: Reverses the list: [1,2,3][::-1] returns [3,2,1]
Answer: Global: accessible everywhere, Local: only in the function where defined
Answer: Returns the number of times an item appears: my_list.count(5)
Answer: Use .sort() method (modifies list) or sorted() function (returns new list)
Answer: A parameter with a default value: def greet(name="Guest"):
Answer: Allows a function to accept any number of positional arguments
Answer: Allows a function to accept any number of keyword arguments
Answer: A small anonymous function: lambda x: x * 2
Answer: A view of key-value pairs: dict.items() returns [(key1, value1), ...]
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.
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
- Always call
close() at the end of your program
- Include
hover() delays between takeoff() and land()
- Use appropriate power levels (start low, increase gradually)
- Test in safe environments with sufficient clearance
- Organize code with constants and functions
- Handle errors gracefully with try-except blocks
- Verify sensor ranges before using them
- Have an emergency stop plan
← Back to Documentation |
Version: 2.6 | Last Updated: 2024