Hi everyone, welcome back to Week 3 of our 3 Month Beginner Friendly Secure Coding Series in Python. If you have followed Week 1 and Week 2, you now know how to use input, output, if/else statements, loops, dictionaries and lists to make interactive programs like a calculator and To-Do list. This week, we are going to take a step toward writing cleaner, more professional code by learning python functions.
So far, we’ve been writing everything in one long block of code, but as programs get bigger, this becomes messy and hard to manage long code. Imagine having a program with hundreds of lines where everything is mixed together. If you want to fix a bug or change one part, you have to scroll up and down and be very careful not to break something else. So as a programmer we have to write clean and secure code which is our main focus overall but for now python functions helps us. So take it easy, be relaxed we are going to dive in.
What Are Functions in Python?
In Python, a function is a block of code that is written once and can be used whenever needed in a program. It allows us to group related instructions together and run them by simply calling the function name. Functions can take input values, called parameters, and can also return an output value after processing. They make programs easier to read, reduce repetition, and help in organizing code into smaller, logical parts. In Python, we create a function using the def keyword, give it a name myFunction, and write the code inside it. Functions are important because they improve re-usability, structure, and clarity of programs.
There are two types of functions in Python:
- Built-in functions » These functions are prebuilt and come with Python. We’ll talk about them later in this blog.
- User-defined functions » These functions are created and defined by users. Below is an example of a user-defined function.
A very simple function example to greet a user:
def greet(name):
print("Hello,", name)
We wrote above function with the name greet(). But if you run the above code it will not give you any answer or print result. It is because whenever we define any function then we must have to call that function and the syntax to call defined function is function_name(Argument) like this:
greet("Aziz")
greet("Ahmad")
greet("Ali")
greet("Javed")
Now to make it together it looks like this:
def greet(name):
print("Hello,", name)
greet("Aziz")
greet("Ahmad")
greet("Ali")
greet("Javed")
greet("AnyThing")
Write and save this code in a python file greet-user.py in VS-Code. and then run it.
Output:
Hello, Aziz
Hello, Ahmad
Hello, Ali
Hello, Javed
Hello, AnyThing
See what happened? We wrote the logic of saying hello once, but we can call it as many times as we want with different names. This is why functions are so powerful. To define more in depth, when we defined the function greet(name), we created a block of code that takes one input (a name) and prints a message. Inside the function, the code print("Hello,", name) tells Python to show the text Hello, followed by the value stored in name. When we call greet("Aziz"), the function runs with "Aziz" as the input, so it prints Hello, Aziz. Then, when we call greet("Ahmad"), the same function runs again, but this time with "Ahmad" as the input, so it prints Hello, Ahmad. The important thing here is that we only wrote the logic once, but we can reuse it multiple times with different inputs, which makes our code shorter, cleaner, and more useful. Additionally, we can create an empty function without arguments, and we can define functions with multiple arguments and multiple parameter names. This would get long, so I suggest you study this in more detail, here I am just giving the concept.
Functions with Return Values
Functions with return values are useful when we don’t just want to display something, but actually want to keep the result and use it in our program later. The return keyword tells Python to give back a value from the function. For example:
def add(x, y):
return x + y
result = add(10, 5)
print("The sum is:", result)
the function add(x, y) calculates the sum and returns it instead of just printing it. Then we stored that returned value in the variable result and printed it outside the function.
Organizing Our Code with Functions
Let’s take what we learned last week with the To-do list project and make it cleaner by using functions. But to make the code more clean then Instead of writing everything inside while loop, we can break it down into smaller parts with the help of functions like below, and by the way we have written this code in previous post and I want that you compare the following code with previous one and this time we are just improving it:
#----TO-DO-List-program---
#------functions----------
def show_tasks(tasks):
print("Your Tasks:")
for t in tasks:
print(">>>", t)
def add_task(tasks):
task = input("Enter a new task: ")
tasks.append(task)
print("Task added.")
def remove_task(tasks):
task = input("Enter the task to remove: ")
if task in tasks:
tasks.remove(task)
print("Task removed.")
else:
print("Task not found.")
#------store-data-in-list----------
tasks = []
#-----condition------
while True:
command = input("Enter a command (add/show/remove/exit): ")
#----calling-above-functions-----
if command == "add":
add_task(tasks)
elif command == "show":
show_tasks(tasks)
elif command == "remove":
remove_task(tasks)
elif command == "exit":
print("Exit Program!")
break
else:
print("Unknown command, try again.")
Write and save this code in a python file todov2.py in VS-Code. and then run it.
Above we wrote functions for each one like for adding task, removing and showing tasks. Now the main loop looks clean, and if later you want to improve how tasks are shown, you only have to edit just the function like the show_tasks() function, not your whole program. I have added comments in the code above to understand it easily.
Question: Did you notice that our previous program was 25 line of code including the free spaces. But now as we said that we are going to write short code but this isn’t short its 42 lines of code including free spaces. As compare to previous one this is lengthy? why
Yes, if we just count the number of lines, this new program looks longer than the previous one. But the point of using functions is not always about reducing the number of lines, it’s about making the code cleaner, organized, and easier to read and manage. In our old program, all the code was inside one big loop, so if we wanted to change how tasks are shown, we have to dig inside and edit that part carefully. But now, with functions, each task (add, show, remove) has its own separate block. This means the main loop is simple and clear, and if later we want to improve one part, we just edit that one function without touching the rest. I hope it is clear.
Lambda - a.k.a - anonymous function!!
Another neat feature in Python which is lambda function also known as anonymous function. A lambda is a way to create small, anonymous functions in one line and we don’t need using def . They are especially useful when you need a function “just for now,” like when sorting, filtering, or doing quick calculations. I am going to give you some examples codes and their outputs to help you get the idea.
Look at some examples to understand it better
square = lambda x: x * x
print(square(5))
# Output: 25
we can use lambda with multiple arguments
add = lambda a, b: a + b
print(add(3, 7))
# Output: 10
Or if you have a list of words and want to sort them by length not by alphabetically:
words = ["python", "java", "C#", "pascal"]
sorted_words = sorted(words, key=lambda w: len(w))
print(sorted_words)
Output:
['python', 'java', 'C#', 'pascal']
to filter even number using filter() function.
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
# Output: [2, 4, 6]
listing items in a list easily with map() for example to double every numbers:
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, nums))
print(doubled)
# Output: [2, 4, 6, 8]
So in short that def is recommended for big logics, and lambda is used for now, like when sorting, filtering, or doing quick calculations.
We already wrote simple functions like greet(name) or add(x, y) But I also want to add more on parameters and arguments with functions so we can understand more deeply how functions work and how we can structure them.
What Are Parameters, Arguments and How Do They Work in Python?
In Python, parameters are variables that you define inside the parentheses of a function. The actual definition of parameters is that they are like inputs you give to a function so it can work with different values. They allow you to pass different values (called arguments) into the function when you call it. And a function can take one or more parameters, use them inside the function, and then return a value that you can store in a variable. This way, the same function can work with different data without rewriting the code. When the function runs, the values you pass in are assigned to the parameters, and then the function uses them to perform its task.
For example if we make a function greet(name) then name is a parameter, when we call the function we give it an argument like greet("Aziz") and then inside the function it uses that value to print Hello Aziz, so basically parameters make our functions reusable because we don’t have to hard code values, we just pass them in and the function will use them however we want.
Below is an example of a function that checks whether a number is even or odd:
def check_even_odd(num):
if num % 2 == 0:
return "even"
else:
return "odd"
number = int(input("Enter a number: "))
result = check_even_odd(number)
print("The number is:", result)
write and save this code in a python file check-even-odd.py in VS-Code. and then run it.
In this program, num is the parameter of the function check_even_odd. Whatever number the user enters gets passed as an argument, and that value is assigned to num. The function then uses num to decide if the number is even or odd.
Now I hope you have an understanding of functions, parameters, and arguments in Python. If it looks confusing, then no worries, just try your best, explore more resources, and learn more by doing it practically. Then you will feel confident.
Now I just want to add one more point about the above code, that how we filtered characters or symbols and only accepted numbers to protect the program from crashing. As you can see In the above code, we wanted “Even” and “Odd” values, but imagine if a user tries to break the program by entering a non number value. So to prevent this, we used the int datatype with input like this: number = int(input("Enter a number: ")). This means the program will only accept integer values as input, and with this idea, our secure coding foundation will be built.
Python Built-in Functions and String Methods
Python gives us a lot of power through its built-in functions and methods. Built-in functions are part of the Python core, meaning you can use them anytime without installing anything extra. Methods, on the other hand is also very useful and string methods belong to the string data type and help you modify or work with text directly. Let’s first understand some important built-in functions, and then we’ll move to string methods that are most useful for text operations.
Python Built-in Functions
In Python, built-in functions are special functions already included in the language. You don’t need to import or install anything. They’re made to perform common tasks like handling input, counting items, converting types, or applying logic to collections.
We already discussed two built-in Python functions in the previous week: input() and print(). Now, there are many built-in functions, but I just want to explain the most commonly used. After learning these, you will get a better understanding and then you can easily explore the others as well.
len() in Python
In Python, the len() function is used to count the number of items in a sequence such as a string, list, tuple, or dictionary. It is very useful when checking the size of data like counting users, checking password length, or validating inputs.
Example of checking password length during signup:
password = input("Enter your password: ")
if len(password) < 8:
print("Short! Password must be at least 8 characters.")
else:
print("All Good.")
Write and save this code in a Python file len-demo.py in VS Code, and then run it.
Output:

map() in Python
The map() function applies a specific function to every item in a sequence like a list or tuple. This is useful when you want to modify or transform many items at once without using loops.
Example:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)
Here, map() applies the lambda function (which squares each number) to every element of the list.
Output:
[1, 4, 9, 16, 25]
filter() in Python
The filter() function is used to filter out elements from a sequence based on a condition. It keeps only the items that meet the condition you define.
Example:
numbers = [10, 25, 30, 45, 50, 65]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Output:
[10, 30, 50]
Here, filter() returns only those numbers that are divisible by 2.
Python String Methods
String methods are functions that belong specifically to strings, just like we have list and dictionaries methods (in previous post we discussed it already) The same we have string methods. You call them using dot notation like text.upper() or email.strip(). They’re very handy for formatting, cleaning, and processing user input.
split() in Python
The split() method is used to break a string into parts and return them as a list. This is useful for processing logs, parsing CSV data, or splitting user input like full names or emails.
Example
student = "Ahmad,53,China"
student_detail = student.split(",")
print(student_detail)
Write and save this code in a Python file split-demo.py in VS Code, and then run it.
Output:
We can also count the words using len() together with split():
sentence = input("Please enter a sentence: ")
words = sentence.split()
word_count = len(words)
print("Number of words are: ", word_count)
write and save this code in a Python file word-counter.py in VS Code, and then run it.
Output:

upper() and lower() in Python
The upper() function converts all the input text to uppercase. For example, if the user enters abc, then upper() will convert it to ABC. On the other hand, the lower() function converts text to lowercase. This is useful when you want to standardize data. For example, we want to accept the email address in lowercase. During registration users sometimes type emails in caps so we need to handle this before saving in database like this:
email = input("Enter your email: ")
email = email.lower().strip()
print("Email saved as:", email)
write and save this code in a Python file upper-to-lower.py in VS Code, and then run it.
Output:
These functions are very useful in Python. Sometimes, for example in a quiz program or a Capture The Flag (CTF) challenge, the answer is stored in a specific format. Let’s say the correct flag is alliswell0123. If a user types All iS WELL 0123, it has spaces and uppercase letters. Even though the answer is logically correct, but it won’t match the format. So as a programmer, we can handle this situation using lower(), upper(), and replace(" ", "").
Imagine the CTF challenge where Correct flag = alliswell0123 and User input = All is Well 0123
flag = "alliswell0123"
user_input = input("Submit Flag: ")
user_input = user_input.lower().replace(" ", "")
if user_input == flag:
print("nice, your flag is:", flag)
else:
print("Wrong, Try again!")
Now, no matter how the user types the flag (with spaces or uppercase), the backend will normalize it before comparison and saving in DB. you can see the output below:

strip() in Python
The strip() method removes extra spaces from the beginning and end of a string. In backend systems, this is very useful because user inputs often contain unwanted spaces that can break authentication or data storage.
Example:
username = input("Please enter your username: ")
print("User Name:", ">>>", username.strip(), "<<<")
Write and save this code in a Python file strip-demo.py in VS Code, and then run it.
Output:
As you can see I added many free spaces before and after the actual username but still it filters out and just print out the result which we want. Don’t be confused by the >>> and <<< in above code I just added to show where the username will appear.
join() in Python
The join() method combines items from a list or tuple into a single string, using a defined separator between them. It’s often used when you need to turn a list of words into a sentence or format data for output.
Example:
words = ["Python", "is", "easy"]
sentence = " ".join(words)
print(sentence)
Output:
Python is easy
Unit Converter - Our Mini Project
Now let’s write a small project to practice Python functions. As you know, we try to build a mini project every week, so for this week I have planned a Unit Converter , where the user can convert between kilometers to miles, and Celsius to Fahrenheit, and vice versa. For now, look at the code, copy it, or write it yourself (recommended), I will explain below how I did this:
def km_to_miles(km):
return km * 0.6
def miles_to_km(miles):
return miles / 0.6
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
def fahrenheit_to_celsius(f):
return (f - 32) * 5/9
while True:
print("\nOur Mini Project unit Converter")
print("1. Km to Miles")
print("2. Miles to Km")
print("3. Celsius to Fahrenheit")
print("4. Fahrenheit to Celsius")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == "1":
km = float(input("Enter distance in km: "))
print("In miles:", km_to_miles(km))
elif choice == "2":
miles = float(input("Enter distance in miles: "))
print("In km:", miles_to_km(miles))
elif choice == "3":
c = float(input("Enter temperature in °C: "))
print("In °F:", celsius_to_fahrenheit(c))
elif choice == "4":
f = float(input("Enter temperature in °F: "))
print("In °C:", fahrenheit_to_celsius(f))
elif choice == "5":
print("Exit Progrma!")
break
else:
print("Invalid choice, try again.")
Write and save this code in a python file unit-converter.py in VS-Code. and then run it.
Now let me explain the big picture in very easy words.
We have 3 main parts of our program
Start of code
- Functions
- looping (in our case
while loop) - Lastly if/else statements
End of code
In part (1) of the program we wrote 4 functions which means our project contain 4 main functionality (kilometer to miles, miles to kilometer, celsius to fahrenheit, fahrenheit to celsius) right.
Next In part (2) of our program, we can see the while True. Well we are using while True because we want our program to keep running until the user decides to exit. As you know we have discussed the while loop previously in detail so in Python it creates a loop that repeats as long as the condition is true (True / False = these are Booleans). Since we wrote “True”, which is always true, the loop will never stop by itself. It will only stop when we tell it to, in our case when the user types "exit" and we use break statement to end the loop.
Next in part (3) If/else statements, at the end of our program, we are using if, elif, and else statements to decide what to do based on the user’s choice.
For example, if the user types "1", then the program calls km_to_miles() and converts kilometers into miles.
If the user types "2", then it runs miles_to_km() to convert miles into kilometers.
If the user types "3", then the program calls celsius_to_fahrenheit() to convert Celsius into Fahrenheit.
If the user types "4", then it runs fahrenheit_to_celsius() to convert Fahrenheit into Celsius.
If the user types "5", then it prints Exit Program! and breaks the loop to stop the program.
Last, the else part is just a safety check. If the user enters something we don’t understand, like "0", "abc", or any random input or empty spaces, the program prints "Invalid choice, try again." so it won’t break our program.
Now run this program and test it with different inputs, use character, empty spaces, symbols instead of numbers, try to remove float (the datatype) from the code like this one float(input("Enter distance in km: ")) to this input("Enter distance in km: ")) and rerun the program, and same concept try to break it and compare the result with the previous one. This is a good reminder that input validation is important, and we will learn better ways to handle it in the coming weeks.
Book Reading –> Chapter 2 (Threats)
This week I also started reading Chapter 2 “Threats” from Designing Secure Software A Guide for Developers by Kohnfelder. I recommend you read it too, and then we’ll cover and summarize it next week.
Alright, that’s it for this week. Please revise previous learning materials, concepts and try to practice. I hope it helps you and you have gained some knowledge, Next week our new topic will be Modular Programming and Error Handling. We will end up this chapter (Threats) from the book if possible, so please stay tuned. If you have any questions, recommendations and improvement please feel free to reach out to me on LinkedIn: https://www.linkedin.com/in/aziz-u000/