6.11 - Programming in Python
Setting up and using IDLE
IDLE is an integrated development environment (IDE) provided with Python, which means it's a software tool that helps you write, edit, and run code in one place.
Getting started with IDLE
- Download Python from the official website (python.org), which includes IDLE.
- Launch IDLE to open the Python Shell, a window where you can type and execute single lines of code by pressing enter.
- For multi-line programmes, select 'New File' from the 'File' menu to open a code editor window.
- Save your code with a '.py' extension, as this is the standard file format for Python scripts.
- To execute the entire script, use 'Run Module' from the 'Run' menu or press F5.
Key features of Python code
Python code shares similarities with pseudocode but has specific rules to follow:
Python syntax rules:
- Functions and commands, such as
inputandprint, must be in lowercase. - Control statements like
if,for, andwhilerequire a colon (:) at the end of the first line. - Code blocks within these statements must be indented (using spaces or tabs) to indicate they belong to the structure.
- Unlike some pseudocode, Python does not use end statements like 'endif' or 'endwhile' – indentation defines the block's end.
Here is an example of a simple Python code block demonstrating these features:
Defining and using variables
Variables are named storage locations in a programme that hold data values, which can change during execution.
Creating variables in Python
Define a variable by assigning a value to a name using the equals sign (=), for example, quiz_score = 0. The data type is automatically determined by the assigned value – no explicit declaration is needed.
Common data types:
- Integer - Whole numbers, e.g.,
quiz_score = 0creates an integer variable to track points. - String - Text data, e.g.,
player_name = "Alice". - List - A collection of items, similar to an array, which can hold mixed data types and grow dynamically, e.g.,
results = []starts an empty list.
Working with lists
- Lists are flexible data structures that store multiple values in sequence.
- Add items using the
append()method, e.g.,results.append("Correct!"). - Access items by index, starting from 0, e.g.,
results[0]retrieves the first item. - Lists do not have a fixed length, making them ideal for storing varying amounts of data like quiz results.
Handling inputs and outputs
Inputs allow a programme to receive data from the user, while outputs display information on the screen.
Using input() and print()
- The
input()function prompts the user for text entry and returns it as a string, e.g.,player_name = input("Please enter your name: "). - The
print()function displays messages or variable values, e.g.,print("Hi, " + player_name + "!"). - Combine strings using concatenation with the + operator, as shown in the example above.
Pausing and formatting output
- Use empty
print("")statements to add blank lines for better readability. - For pauses without storing input, use
input("Press enter to continue")– it waits for the user to press enter.
Here is an example code snippet for a quiz introduction:
Implementing selection for decisions
Selection structures allow a programme to make decisions based on conditions, executing different code paths accordingly.
Using if statements
- Start with
iffollowed by a condition and a colon, then indent the code block. - Use
eliffor additional conditions andelsefor the default case. - Conditions often compare variables, e.g.,
if user_ans <mark> "C":.
Example code for checking a quiz answer:
Using iteration for input validation
Iteration repeats code until a condition is met, which is useful for ensuring valid user inputs.
While loops for validation
- A
whileloop runs as long as its condition is true, e.g.,while user_ans not in ["A", "B", "C", "D"]: - Combine with
input()to repeatedly prompt until valid. - Use
.upper()to convert input to uppercase for case-insensitive checks.
Example code for validating quiz answers:
Creating and using subroutines
Subroutines are reusable blocks of code that perform specific tasks, helping to avoid repetition.
Defining subroutines
- Use
deffollowed by the name and parentheses, then a colon, e.g.,def input_answer():. - Indent the code block.
- If it returns a value (making it a function), use
return, e.g.,return user_ans. - Define subroutines early in the code, before calling them.
Example subroutine for input validation:
Displaying results with loops
Loops can iterate over data structures to process or display information systematically.
For loops with range
- A
forloop repeats for a set number of times, e.g.,for i in range(5):loops 5 times, withifrom 0 to 4. - Use to access list items by index, e.g.,
print(results[i]).
Casting data types
Convert types for operations like concatenation, e.g., str(quiz_score) turns an integer to a string.
Example code for showing quiz results (assuming 5 questions):
Importing and using modules
Modules are pre-written code libraries that extend Python's functionality, saving development time.
Working with modules
- Import at the programme's start using
import, e.g.,import time. - Call functions with the module name, e.g.,
time.sleep(2)pauses for 2 seconds. - Use modules to add features like timed delays in a quiz for a more interactive feel.