Python Procedural Programming Reference Guide for Beginners
Welcome to this beginner-friendly guide on procedural programming in Python! This guide will walk you through the fundamental constructs of Python programming, including simple outputs, variables, inputs, selection, iteration, string handling, error handling, and functions with parameter passing. Each section includes explanations and examples to help you grasp the concepts easily.
Table of Contents
- Simple Outputs
- Variables
- Inputs
- Selection
- Iteration
- String Handling
- Error Handling
- Functions with Parameter Passing
- Reading and Writing to Files
1. Simple Outputs
The print()
Function
The print()
function is used to display information to the console.
Syntax:
print(object, ..., sep=' ', end='\n')
object
: The value or expression to display.sep
: Separator between objects (default is a space).end
: What to print at the end (default is a newline).
Example
# Simple output print("Hello, World!") # Outputting multiple objects print("The sum of 2 and 3 is", 2 + 3)
Output:
Hello, World! The sum of 2 and 3 is 5
2. Variables
Variables store data that can be used and manipulated in your program.
Variable Assignment
Assign values to variables using the =
operator.
Example:
# Assigning variables name = "Alice" age = 25 height = 5.6
Data Types
- Integer (
int
): Whole numbers (e.g.,1
,42
) - Floating-point (
float
): Decimal numbers (e.g.,3.14
,0.001
) - String (
str
): Text data (e.g.,"hello"
,'world'
) - Boolean (
bool
): Logical values (True
orFalse
)
Example:
# Different data types is_student = True score = 3.75 # Printing variable values print("Name:", name) print("Age:", age) print("Height:", height) print("Is Student:", is_student) print("Score:", score)
Output:
Name: Alice Age: 25 Height: 5.6 Is Student: True Score: 3.75
3. Inputs
Collect input from the user using the input()
function.
The input()
Function
Syntax:
variable = input(prompt)
prompt
: The message displayed to the user.
Example
# Getting user input name = input("Enter your name: ") print("Hello,", name)
Output:
Enter your name: Bob Hello, Bob
Casting Input
By default, input()
returns a string. To work with other data types, cast the input.
Example:
age = int(input("Enter your age: ")) print("You are", age, "years old.")
Output:
Enter your age: 30 You are 30 years old.
4. Selection
Control the flow of your program using conditional statements.
if
Statements
Execute code only if a condition is true.
Syntax:
if condition: # code block
if-else
Statements
Provide an alternative when the condition is false.
Syntax:
if condition: # code block if condition is true else: # code block if condition is false
if-elif-else
Statements
Check multiple conditions.
Syntax:
if condition1: # code block elif condition2: # code block else: # code block
Example
age = int(input("Enter your age: ")) if age >= 18: print("You are an adult.") elif age >= 13: print("You are a teenager.") else: print("You are a child.")
Output:
Enter your age: 16 You are a teenager.
5. Iteration
Repeat code using loops.
for
Loops
Iterate over a sequence.
Syntax:
for variable in sequence: # code block
Example
# Iterating over a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
Output:
apple banana cherry
while
Loops
Repeat as long as a condition is true.
Syntax:
while condition: # code block
Example
# Counting down from 5 count = 5 while count > 0: print(count) count -= 1 print("Blast off!")
Output:
5 4 3 2 1 Blast off!
6. String Handling
Manipulate and work with text data.
String Literals
Strings can be enclosed in single ('
), double ("
), or triple quotes ('''
or """
).
Concatenation
Combine strings using the +
operator.
Example:
greeting = "Hello" name = "Alice" message = greeting + ", " + name + "!" print(message)
Output:
Hello, Alice!
String Methods
Common methods to manipulate strings:
.upper()
- Converts to uppercase.lower()
- Converts to lowercase.strip()
- Removes leading/trailing whitespace.replace(old, new)
- Replaces substrings.split(separator)
- Splits the string
Example:
text = " Hello World! " print(text.strip()) # Removes whitespace print(text.upper()) # Converts to uppercase print(text.replace("World", "Python"))
Output:
Hello World! HELLO WORLD! Hello Python!
Slicing Strings
Extract substrings using indexing.
Syntax:
substring = string[start:end]
start
: Starting index (inclusive)end
: Ending index (exclusive)
Example:
text = "Hello, World!" print(text[7:12]) # Outputs 'World'
Output:
World
7. Error Handling
Manage errors gracefully using try
and except
blocks.
try
and except
Blocks
Syntax:
try: # code that might raise an exception except ExceptionType: # code to handle the exception
Example
try: numerator = int(input("Enter numerator: ")) denominator = int(input("Enter denominator: ")) result = numerator / denominator print("Result:", result) except ValueError: print("Please enter valid integers.") except ZeroDivisionError: print("Cannot divide by zero.")
Output:
Enter numerator: 10 Enter denominator: 0 Cannot divide by zero.
8. Functions with Parameter Passing
Organize code into reusable blocks using functions.
Defining Functions
Syntax:
def function_name(parameters): # code block return value
Parameters and Arguments
- Parameters: Variables listed in the function definition.
- Arguments: Values passed to the function when called.
Example
# Function with parameters def greet(name): return "Hello, " + name + "!" # Calling the function message = greet("Bob") print(message)
Output:
Hello, Bob!
Return Values
Functions can return values using the return
statement.
Example:
# Function that adds two numbers def add(a, b): return a + b sum = add(5, 7) print("Sum:", sum)
Output:
Sum: 12
9. Reading and Writing to Files
Python allows you to read from and write to text files using built-in functions. This is especially useful for saving data, loading configurations, or processing information from external sources. In your Python editor, any text file you read or write will automatically create a new tab, where you can view and edit the contents of the file.
Opening Files
Syntax:
file = open('filename.txt', mode)
- filename.txt: The name of the file you want to open. Make sure the file name matches the name of the tab in your IDE.
- mode: Specifies the purpose of opening the file. Common modes include:
'r'
: Read (default mode)'w'
: Write (creates a new file or truncates existing file)'a'
: Append (writes to the end of the file)'r+'
: Read and write
Reading from a File
To read the contents of a text file, use the read()
or readlines()
method.
Example:
# Open a file in read mode file = open('example.txt', 'r') # Read the entire content of the file content = file.read() # Close the file after reading file.close() # Output the content print(content)
Output:
# The contents of example.txt will be displayed here.
Writing to a File
To write to a file, open the file in 'w'
(write) or 'a'
(append) mode. When you write to a file, it automatically creates a new tab in your IDE with the same name, and the text you write will be added to that tab.
Example:
# Open a file in write mode file = open('example.txt', 'w') # Write text to the file file.write("This is an example of writing to a file.\n") # Close the file after writing file.close()
Note: If the file already exists, this will overwrite its content. If you want to add text to an existing file, use 'a'
mode (append).
Example of Appending to a File
Example:
# Open a file in append mode file = open('example.txt', 'a') # Append text to the file file.write("Adding a new line of text.\n") # Close the file after appending file.close()
Reading Line by Line
You can read files line by line using a for
loop, which is especially useful for large files.
Example:
# Open a file in read mode file = open('example.txt', 'r') # Read each line one by one for line in file: print(line.strip()) # Print each line without extra newlines # Close the file after reading file.close()
Using with
Statement
It's good practice to use the with
statement when working with files. This ensures that the file is properly closed after its suite finishes, even if an exception is raised.
Example:
# Using 'with' to open and automatically close the file with open('example.txt', 'r') as file: content = file.read() print(content) # Output the content of the file
Example of Writing with with
:
# Using 'with' to write to a file with open('example.txt', 'w') as file: file.write("This is a new line written using the 'with' statement.\n")
Conclusion
Congratulations! You've covered the fundamental constructs of procedural programming in Python. By understanding simple outputs, variables, inputs, selection, iteration, string handling, error handling, functions with parameter passing, and reading/writing to files, you're well on your way to becoming proficient in Python programming. Keep practicing and experimenting with these concepts to strengthen your skills.
Unlock More with CSUK:Teacher!
Teachers, would you like solutions, a student workbook and tracking tool to accompany these challenges? Become a CSUK:Teacher member and get:
- A Student Workbook to track and submit challenge progress.
- A Teacher Tracking and Solutions Spreadsheet with coded solutions and tracking tools.
Join now to take your CS teaching to the next level!
CSUK's 101 Python Coding Challenges for Beginners
- ⭐
Hello, World!
Write a program that prints"Hello, World!"
to the console. - ⭐
Input and Output
Write a program that asks the user for their name and greets them. - ⭐
Simple Addition
Write a program that adds two numbers provided by the user. - ⭐
Odd or Even
Write a program that determines if a number is odd or even. - ⭐
Generate Multiplication Table
Generate the multiplication table for a given number. - ⭐
Find ASCII Value of a Character
Write a program that prints the ASCII value of a character. - ⭐
Simple Interest Calculator
Calculate simple interest given principal, rate, and time. - ⭐
Area of a Circle
Write a program to calculate the area of a circle given its radius. - ⭐
Area of a Triangle
Calculate the area of a triangle given its base and height. - ⭐
Swap Two Variables
Write a program to swap two variables without using a temporary variable. - ⭐
Random Number Generator
Write a program that generates a random number between 1 and 100. - ⭐
Calculate the Sum of a List
Write a program to calculate the sum of all numbers in a list. - ⭐
Generate a List of Even Numbers
Write a program to generate a list of even numbers from 1 to 100. - ⭐
Calculate the Average of Numbers in a List
Write a program to calculate the average of numbers in a list. - ⭐
Convert Celsius to Fahrenheit
Write a program to convert temperature from Celsius to Fahrenheit. - ⭐
Simulate a Dice Roll
Write a program to simulate rolling a dice. - ⭐
Leap Year Checker
Write a program to check if a year is a leap year. - ⭐
Simple Calculator
Create a calculator that can add, subtract, multiply, and divide two numbers. - ⭐
Factorial Calculator
Write a program to calculate the factorial of a number. - ⭐
Fibonacci Sequence
Generate the Fibonacci sequence up to a certain number of terms. - ⭐⭐
Prime Number Checker
Write a program to check if a number is prime. - ⭐⭐
Largest of Three Numbers
Write a program to find the largest among three numbers input by the user. - ⭐⭐
Reverse a String
Write a program that reverses a string input by the user. - ⭐⭐
Palindrome Checker
Write a program to check if a string is a palindrome. - ⭐⭐
Count Vowels in a String
Write a program that counts the number of vowels in a string. - ⭐⭐
Sum of Digits
Write a program to calculate the sum of digits of a number. - ⭐⭐
Compound Interest Calculator
Calculate compound interest given principal, rate, and time. - ⭐⭐
Calculate the Length of a String
Write a program to find the length of a string without using len(). - ⭐⭐
Count Words in a String
Write a program that counts the number of words in a string. - ⭐⭐
Sort a List
Write a program to sort a list of numbers in ascending order. - ⭐⭐
Remove Duplicates from a List
Write a program to remove duplicates from a list. - ⭐⭐
Count the Number of Uppercase and Lowercase Letters
Write a program that counts uppercase and lowercase letters in a string. - ⭐⭐
Calculate the Power of a Number
Write a program to calculate the power of a number without using the ** operator. - ⭐⭐
Check if a String is a Substring of Another String
Write a program to check if one string is a substring of another. - ⭐⭐
Find the Sum of a Series 1 + 1/2 + 1/3 + ... + 1/n
Write a program to calculate the sum of the series up to n terms. - ⭐⭐
Count the Occurrences of an Element in a List
Write a program to count how many times an element occurs in a list. - ⭐⭐
Merge Two Dictionaries
Write a program to merge two dictionaries into one. - ⭐⭐
Generate a Random OTP (One-Time Password)
Write a program to generate a random 6-digit OTP. - ⭐⭐
Convert a List into a Comma-Separated String
Write a program to convert a list of numbers into a comma-separated string. - ⭐⭐
Find the Longest Word in a Sentence
Write a program to find the longest word in a given sentence. - ⭐⭐
Find All Factors of a Number
Write a program to find and display all the factors of a given positive integer. A factor is a number that divides another number completely without leaving any remainder. - ⭐⭐
Check if a Number is a Perfect Square
Write a program to check if a given number is a perfect square. A perfect square is a number that is the square of an integer. - ⭐⭐
Reverse the Words in a Sentence
Write a program that takes a sentence as input and reverses the order of words in the sentence. - ⭐⭐
Check if Two Lists are Equal
Write a program to check if two lists have the same elements in the same order. - ⭐⭐
Calculate the Distance Between Two Points
Write a program to calculate the Euclidean distance between two points in 2D space. - ⭐⭐
Find the Intersection of Two Lists
Write a program to find the elements common to two lists. - ⭐⭐
Find the Union of Two Lists
Write a program to find all unique elements from two lists. - ⭐⭐
Find the Difference Between Two Lists
Write a program to find elements present in one list but not the other. - ⭐⭐
Calculate the Sum of Squares of First n Natural Numbers
Write a program to calculate the sum of squares of first n natural numbers. - ⭐⭐
Create a Mad Libs Game
Write a program that asks the user for inputs and generates a funny story (Mad Libs). - ⭐⭐⭐
Armstrong Number Checker
Write a program to check if a number is an Armstrong number. - ⭐⭐⭐
Quadratic Equation Solver
Write a program to solve quadratic equations. - ⭐⭐⭐
Rock, Paper, Scissors Game
Create a simple rock, paper, scissors game against the computer. - ⭐⭐⭐
Guess the Number Game
Write a program where the computer chooses a number, and the user tries to guess it. - ⭐⭐⭐
Remove Punctuation from a String
Write a program that removes punctuation from a given string. - ⭐⭐⭐
Merge Two Lists
Write a program to merge two lists into a dictionary. - ⭐⭐⭐
Find the Second Largest Number in a List
Write a program to find the second largest number in a list. - ⭐⭐⭐
Check for Anagrams
Write a program to check if two strings are anagrams. - ⭐⭐⭐
Find Common Elements in Two Lists
Write a program to find common elements between two lists. - ⭐⭐⭐
Fibonacci Series Using Recursion
Write a recursive function to generate the Fibonacci series. - ⭐⭐⭐
Factorial Using Recursion
Write a recursive function to calculate the factorial of a number. - ⭐⭐⭐
Calculate GCD of Two Numbers
Write a program to find the greatest common divisor (GCD) of two numbers. - ⭐⭐⭐
Calculate LCM of Two Numbers
Write a program to find the least common multiple (LCM) of two numbers. - ⭐⭐⭐
Check for Armstrong Numbers in an Interval
Find all Armstrong numbers between two given numbers. - ⭐⭐⭐
Check for Prime Numbers in an Interval
Find all prime numbers between two given numbers. - ⭐⭐⭐
Check if a String is a Pangram
Write a program to check if a string contains all letters of the alphabet. - ⭐⭐⭐
Count the Frequency of Words in a String
Write a program to count the frequency of each word in a string. - ⭐⭐⭐
Print the Following Pattern
* ** *** **** *****
- ⭐⭐⭐
Print the Reverse of the Above Pattern
***** **** *** ** *
- ⭐⭐⭐
Print a Pyramid Pattern
* *** ***** *******
- ⭐⭐⭐
Simple Number Guessing Game
Create a game where the user has limited attempts to guess a number. - ⭐⭐⭐
Convert Decimal to Binary
Write a program to convert a decimal number to binary. - ⭐⭐⭐
Convert Binary to Decimal
Write a program to convert an integer binary number to decimal. - ⭐⭐⭐
Check if a Number is a Perfect Number
Write a program to check if a number is perfect (sum of its proper divisors equals the number). - ⭐⭐⭐
Check if a Number is a Strong Number
Write a program to check if a number is a strong number (sum of factorial of its digits equals the number). - ⭐⭐⭐
Check if a Number is a Happy Number
Write a program to check if a number is a happy number. - ⭐⭐⭐
Find the HCF and LCM of Multiple Numbers
Write a program to find the HCF and LCM of a list of numbers. - ⭐⭐⭐
Generate a Random Password
Write a program to generate a random password containing letters and numbers. - ⭐⭐⭐
Implement Binary Search
Write a program to perform binary search on a sorted list. - ⭐⭐⭐
Implement Bubble Sort
Write a program to sort a list using bubble sort algorithm. - ⭐⭐⭐
Implement Selection Sort
Write a program to sort a list using selection sort algorithm. - ⭐⭐⭐
Implement Insertion Sort
Write a program to sort a list using insertion sort algorithm. - ⭐⭐⭐
Transpose a Matrix
Write a program to transpose a 2D matrix. - ⭐⭐⭐
Calculate the Sum of Diagonals in a Matrix
Write a program to calculate the sum of the main and secondary diagonals in a square matrix. - ⭐⭐⭐
Check if a String is a Palindrome Using Recursion
Write a recursive function to check if a string is a palindrome. - ⭐⭐⭐
Find the Max and Min in a List Without Using Built-in Functions
Write a program to find the maximum and minimum numbers in a list without using built-in functions. - ⭐⭐⭐
Check if a String is a Valid Email Address
Write a program to validate an email address. - ⭐⭐⭐
Find the Most Frequent Element in a List
Write a program to find the most frequent element in a list. - ⭐⭐⭐
Implement a Stack Using a List
Write a program to implement a stack using a list. - ⭐⭐⭐
Implement a Queue Using a List
Write a program to implement a queue using a list. - ⭐⭐⭐
Flatten a Nested List
Write a program to flatten a list that contains nested lists. - ⭐⭐⭐
Generate a Deck of Cards
Write a program to generate a standard deck of 52 cards. - ⭐⭐⭐
Implement Caesar Cipher Encryption
Write a program to encrypt a message using Caesar cipher. - ⭐⭐⭐
Implement Caesar Cipher Decryption
Write a program to decrypt a message encrypted with Caesar cipher. - ⭐⭐⭐
Check if a String is a Valid Palindrome Ignoring Spaces
Write a program to check if a string is a palindrome, ignoring spaces and punctuation. - ⭐⭐⭐
Check if All Characters in a String are Unique
Write a program to determine if a string has all unique characters. - ⭐⭐⭐
Implement a Simple Calculator Using Functions
Write a program to create a simple calculator using functions for each operation. - ⭐⭐⭐
Check if a Number is a Fibonacci Number
Write a program to check if a given number is in the Fibonacci sequence. - ⭐⭐⭐
Print the First n Prime Numbers
Write a program to print the first n prime numbers. - ⭐⭐⭐
Find the Smallest Missing Positive Integer
Write a program to find the smallest positive integer missing from a list. - ⭐⭐⭐
Generate All Permutations of a String
Write a program to generate all permutations of a given string.