×

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

  1. Simple Outputs
  2. Variables
  3. Inputs
  4. Selection
  5. Iteration
  6. String Handling
  7. Error Handling
  8. Functions with Parameter Passing
  9. 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 or False)

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

  1. Hello, World!
    Write a program that prints "Hello, World!" to the console.

  2. Input and Output
    Write a program that asks the user for their name and greets them.

  3. Simple Addition
    Write a program that adds two numbers provided by the user.

  4. Odd or Even
    Write a program that determines if a number is odd or even.

  5. Generate Multiplication Table
    Generate the multiplication table for a given number.

  6. Find ASCII Value of a Character
    Write a program that prints the ASCII value of a character.

  7. Simple Interest Calculator
    Calculate simple interest given principal, rate, and time.

  8. Area of a Circle
    Write a program to calculate the area of a circle given its radius.

  9. Area of a Triangle
    Calculate the area of a triangle given its base and height.

  10. Swap Two Variables
    Write a program to swap two variables without using a temporary variable.

  11. Random Number Generator
    Write a program that generates a random number between 1 and 100.

  12. Calculate the Sum of a List
    Write a program to calculate the sum of all numbers in a list.

  13. Generate a List of Even Numbers
    Write a program to generate a list of even numbers from 1 to 100.

  14. Calculate the Average of Numbers in a List
    Write a program to calculate the average of numbers in a list.

  15. Convert Celsius to Fahrenheit
    Write a program to convert temperature from Celsius to Fahrenheit.

  16. Simulate a Dice Roll
    Write a program to simulate rolling a dice.

  17. Leap Year Checker
    Write a program to check if a year is a leap year.

  18. Simple Calculator
    Create a calculator that can add, subtract, multiply, and divide two numbers.

  19. Factorial Calculator
    Write a program to calculate the factorial of a number.

  20. Fibonacci Sequence
    Generate the Fibonacci sequence up to a certain number of terms.

  21. ⭐⭐ Prime Number Checker
    Write a program to check if a number is prime.

  22. ⭐⭐ Largest of Three Numbers
    Write a program to find the largest among three numbers input by the user.

  23. ⭐⭐ Reverse a String
    Write a program that reverses a string input by the user.

  24. ⭐⭐ Palindrome Checker
    Write a program to check if a string is a palindrome.

  25. ⭐⭐ Count Vowels in a String
    Write a program that counts the number of vowels in a string.

  26. ⭐⭐ Sum of Digits
    Write a program to calculate the sum of digits of a number.

  27. ⭐⭐ Compound Interest Calculator
    Calculate compound interest given principal, rate, and time.

  28. ⭐⭐ Calculate the Length of a String
    Write a program to find the length of a string without using len().

  29. ⭐⭐ Count Words in a String
    Write a program that counts the number of words in a string.

  30. ⭐⭐ Sort a List
    Write a program to sort a list of numbers in ascending order.

  31. ⭐⭐ Remove Duplicates from a List
    Write a program to remove duplicates from a list.

  32. ⭐⭐ Count the Number of Uppercase and Lowercase Letters
    Write a program that counts uppercase and lowercase letters in a string.

  33. ⭐⭐ Calculate the Power of a Number
    Write a program to calculate the power of a number without using the ** operator.

  34. ⭐⭐ Check if a String is a Substring of Another String
    Write a program to check if one string is a substring of another.

  35. ⭐⭐ 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.

  36. ⭐⭐ Count the Occurrences of an Element in a List
    Write a program to count how many times an element occurs in a list.

  37. ⭐⭐ Merge Two Dictionaries
    Write a program to merge two dictionaries into one.

  38. ⭐⭐ Generate a Random OTP (One-Time Password)
    Write a program to generate a random 6-digit OTP.

  39. ⭐⭐ Convert a List into a Comma-Separated String
    Write a program to convert a list of numbers into a comma-separated string.

  40. ⭐⭐ Find the Longest Word in a Sentence
    Write a program to find the longest word in a given sentence.

  41. ⭐⭐ 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.

  42. ⭐⭐ 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.

  43. ⭐⭐ Reverse the Words in a Sentence
    Write a program that takes a sentence as input and reverses the order of words in the sentence.

  44. ⭐⭐ Check if Two Lists are Equal
    Write a program to check if two lists have the same elements in the same order.

  45. ⭐⭐ Calculate the Distance Between Two Points
    Write a program to calculate the Euclidean distance between two points in 2D space.

  46. ⭐⭐ Find the Intersection of Two Lists
    Write a program to find the elements common to two lists.

  47. ⭐⭐ Find the Union of Two Lists
    Write a program to find all unique elements from two lists.

  48. ⭐⭐ Find the Difference Between Two Lists
    Write a program to find elements present in one list but not the other.

  49. ⭐⭐ Calculate the Sum of Squares of First n Natural Numbers
    Write a program to calculate the sum of squares of first n natural numbers.

  50. ⭐⭐ Create a Mad Libs Game
    Write a program that asks the user for inputs and generates a funny story (Mad Libs).

  51. ⭐⭐⭐ Armstrong Number Checker
    Write a program to check if a number is an Armstrong number.

  52. ⭐⭐⭐ Quadratic Equation Solver
    Write a program to solve quadratic equations.

  53. ⭐⭐⭐ Rock, Paper, Scissors Game
    Create a simple rock, paper, scissors game against the computer.

  54. ⭐⭐⭐ Guess the Number Game
    Write a program where the computer chooses a number, and the user tries to guess it.

  55. ⭐⭐⭐ Remove Punctuation from a String
    Write a program that removes punctuation from a given string.

  56. ⭐⭐⭐ Merge Two Lists
    Write a program to merge two lists into a dictionary.

  57. ⭐⭐⭐ Find the Second Largest Number in a List
    Write a program to find the second largest number in a list.

  58. ⭐⭐⭐ Check for Anagrams
    Write a program to check if two strings are anagrams.

  59. ⭐⭐⭐ Find Common Elements in Two Lists
    Write a program to find common elements between two lists.

  60. ⭐⭐⭐ Fibonacci Series Using Recursion
    Write a recursive function to generate the Fibonacci series.

  61. ⭐⭐⭐ Factorial Using Recursion
    Write a recursive function to calculate the factorial of a number.

  62. ⭐⭐⭐ Calculate GCD of Two Numbers
    Write a program to find the greatest common divisor (GCD) of two numbers.

  63. ⭐⭐⭐ Calculate LCM of Two Numbers
    Write a program to find the least common multiple (LCM) of two numbers.

  64. ⭐⭐⭐ Check for Armstrong Numbers in an Interval
    Find all Armstrong numbers between two given numbers.

  65. ⭐⭐⭐ Check for Prime Numbers in an Interval
    Find all prime numbers between two given numbers.

  66. ⭐⭐⭐ Check if a String is a Pangram
    Write a program to check if a string contains all letters of the alphabet.

  67. ⭐⭐⭐ Count the Frequency of Words in a String
    Write a program to count the frequency of each word in a string.

  68. ⭐⭐⭐ Print the Following Pattern
    *
    **
    ***
    ****
    *****
            

  69. ⭐⭐⭐ Print the Reverse of the Above Pattern
    *****
    ****
    ***
    **
    *
            

  70. ⭐⭐⭐ Print a Pyramid Pattern
       *
      ***
     *****
    *******
            

  71. ⭐⭐⭐ Simple Number Guessing Game
    Create a game where the user has limited attempts to guess a number.

  72. ⭐⭐⭐ Convert Decimal to Binary
    Write a program to convert a decimal number to binary.

  73. ⭐⭐⭐ Convert Binary to Decimal
    Write a program to convert an integer binary number to decimal.

  74. ⭐⭐⭐ 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).

  75. ⭐⭐⭐ 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).

  76. ⭐⭐⭐ Check if a Number is a Happy Number
    Write a program to check if a number is a happy number.

  77. ⭐⭐⭐ Find the HCF and LCM of Multiple Numbers
    Write a program to find the HCF and LCM of a list of numbers.

  78. ⭐⭐⭐ Generate a Random Password
    Write a program to generate a random password containing letters and numbers.

  79. ⭐⭐⭐ Implement Binary Search
    Write a program to perform binary search on a sorted list.

  80. ⭐⭐⭐ Implement Bubble Sort
    Write a program to sort a list using bubble sort algorithm.

  81. ⭐⭐⭐ Implement Selection Sort
    Write a program to sort a list using selection sort algorithm.

  82. ⭐⭐⭐ Implement Insertion Sort
    Write a program to sort a list using insertion sort algorithm.

  83. ⭐⭐⭐ Transpose a Matrix
    Write a program to transpose a 2D matrix.

  84. ⭐⭐⭐ 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.

  85. ⭐⭐⭐ Check if a String is a Palindrome Using Recursion
    Write a recursive function to check if a string is a palindrome.

  86. ⭐⭐⭐ 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.

  87. ⭐⭐⭐ Check if a String is a Valid Email Address
    Write a program to validate an email address.

  88. ⭐⭐⭐ Find the Most Frequent Element in a List
    Write a program to find the most frequent element in a list.

  89. ⭐⭐⭐ Implement a Stack Using a List
    Write a program to implement a stack using a list.

  90. ⭐⭐⭐ Implement a Queue Using a List
    Write a program to implement a queue using a list.

  91. ⭐⭐⭐ Flatten a Nested List
    Write a program to flatten a list that contains nested lists.

  92. ⭐⭐⭐ Generate a Deck of Cards
    Write a program to generate a standard deck of 52 cards.

  93. ⭐⭐⭐ Implement Caesar Cipher Encryption
    Write a program to encrypt a message using Caesar cipher.

  94. ⭐⭐⭐ Implement Caesar Cipher Decryption
    Write a program to decrypt a message encrypted with Caesar cipher.

  95. ⭐⭐⭐ 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.

  96. ⭐⭐⭐ Check if All Characters in a String are Unique
    Write a program to determine if a string has all unique characters.

  97. ⭐⭐⭐ Implement a Simple Calculator Using Functions
    Write a program to create a simple calculator using functions for each operation.

  98. ⭐⭐⭐ Check if a Number is a Fibonacci Number
    Write a program to check if a given number is in the Fibonacci sequence.

  99. ⭐⭐⭐ Print the First n Prime Numbers
    Write a program to print the first n prime numbers.

  100. ⭐⭐⭐ Find the Smallest Missing Positive Integer
    Write a program to find the smallest positive integer missing from a list.

  101. ⭐⭐⭐ Generate All Permutations of a String
    Write a program to generate all permutations of a given string.
Scroll to Top