Algorithms and Programming Python 1
Introduction
Before learning the Python programming language, it’s essential to cover some introductory topics to facilitate the learning process.
Overview
Initially, students are invited to explore small programs that contain the building blocks of programming: expressions, assignments, conditionals, and loops. In practice, a program consists of a mixture of these building elements. Students need to synthesize and integrate their knowledge by “deconstructing” a sample program and extracting its elements to adapt and reconstruct a complete program to solve the problems they face.
This is the essence of Computational Thinking. Decomposing problems involves breaking down a program into smaller syntactical elements to form a cohesive solution. Patterns are expected to emerge from the basic syntactical elements learned through small programs, leading to solution patterns for larger problem-building types.
With this foundational thinking and approach, this course on Basic Programming with Python consists of several modules:
- Introduction: Introduces the history of Python, example applications, and commonly used terms. Recommended IDEs are also discussed.
- Small Programs in Python: Introduces Python through the smallest program, “Hello, World.”
- Initialization and Assignment: Introduces what variables are and the basic types, such as integers, floating-point numbers, and characters/strings. It also explains two ways to assign values to a variable: initialization and assignment.
- Constants: Introduces the concept of constants, which are variables that cannot be changed, and explains the difference between constants and variables.
- Input/Output: Teaches how to input values into variables.
- Basic Operations with Python: Teaches various operations in Python, including arithmetic, boolean, comparison, etc.
- Conditional Statements: Introduces conditional statements so that programs can execute according to a specified flow.
- Looping Statements: Introduces looping statements that allow programs to repeat instructions, such as for, while-do, do-while, and for loops.
- Arrays/Tables: Introduces arrays for storing multiple values in a matrix format.
- Subprograms: Introduces subprograms, functions, and procedures as abstractions of computational processes that can be called by a program.
- Conclusion: Tests understanding of the Python programming language through five exercises to deepen concepts in a simple program, including computational operations, conditional instructions, looping instructions, tables or arrays, and functions and procedures.
Programming algorithm learning will emphasize practical work, with a class composition of 20% theory and 80% practice. Therefore, more time will be dedicated to writing code than to theoretical material.
Introduction to Python
Python is a high-level programming language created by Guido van Rossum. It is widely used for various types of programs, such as CLI programs, GUI applications (desktop), mobile applications, web applications, IoT, AI, machine learning, games, hacking programs, and more.
Python is also known for being easy to learn, as its syntax is clean and easy to understand.
Some features of Python include:
- A vast library; Python distributions come with ready-to-use modules for various purposes.
- Clear and easy-to-learn syntax.
- A layout rule for source code that facilitates checking, readability, and rewriting of source code.
- Object-oriented programming
Introduction to Basic Programming Algorithms
To begin understanding programming algorithms and writing code, we need to grasp the fundamentals as an introduction so that we can easily learn and follow the material in the future.
How to Write and Read
When writing a program, the first thing to pay attention to is how to read and write code. This is similar to how we read and write in general. In reading and writing code, the concept used is reading and writing from top to bottom. Sometimes this is taken lightly, which can lead to significant issues in writing code, resulting in errors in the program. This happens because the sequence of the program does not follow the rules/concepts of top-to-bottom writing. The computer reads our code sequentially from top to bottom, so if the writing is not orderly, it will lead to critical errors. It’s a simple yet very important aspect. That’s why a foundational understanding of writing code is necessary.The Importance of Documentation
In learning a programming language, it’s essential to read the official documentation to minimize mistakes and errors that may occur later. Each programming language has different standards for its syntax, making documentation crucial, important, and necessary to read. You can find the official documentation for each programming language you are learning on the internet.Indentation & Code Blocks
Indentation involves starting text with empty spaces between the text and the margin. Tabs are used for indentation, and the standard number of characters in a tab is four spaces. Indentation is typically used within code blocks. Sometimes, programmers worldwide use different indentation styles depending on their project’s standards. In individual projects, it is common to see programmers using two spaces for indentation. In some cases, such as the Linux kernel project initiated by Linus Torvalds, an eight-character standard is used to enhance the readability of code blocks. The most common and widely used indentation is four spaces, aligning with the standard tab character count.In programming, a code block is an approach that allows users to create programs by arranging interconnected blocks of code. Code blocks in programming languages generally start with an opening curly brace “{“ and end with a closing curly brace “}”. In some programming languages like Python, curly braces do not represent a code block; instead, a different symbol, such as “:”, is used.
To declare a code block (from { to }), it is shown in the following example, and the syntax is explained after the indentation “{“ and “}”.
1
2
3
4
5for ( i = 0; i < MSG_MAX; i++ )
{ //Entering Block Program FOR
[Tab]<Code>
[Tab]<Code>
} //End of Block Program of FOR1
2
3
4
5
6for i in range (5): # Entering Block Program FOR
[Tab]<Code> # Inside Block Program of FOR
[Tab]<Code> # Inside Block Program of FOR
# End of Block Program of FOR
<Code> # Outside of Block ProgramHere is an example of a code block that contains nested code blocks:
1
2
3
4
5
6
7
8
9
10bool fs_tf_analizeFileUpCommand( char *cmd, int size )
{ //Entering Block Program 1
[Tab]int i;
[Tab]for ( i = 0; i < size; i++ )
[Tab]{ //Entering Block Program 2
[Tab][Tab]<Code>
[Tab][Tab]<Code>
[Tab]} //End of Block Program 2
[Tab]return OK_CMD;
} //End of Block Program 11
2
3
4
5
6
7
8
9def fs_tf_analizeFileUpCommand( int cmd, int size ): # Entering Block Program 1
[Tab]for i in range (5): # Entering Block Program 2
[Tab][Tab]<Code> # Inside Block Program 2
[Tab][Tab]<Code> # Inside Block Program 2
[Tab] # End of Block Program 2
[Tab]return OK_CMD # Inside Block Program 1
# End of Block Program 1
<Code> # Outside Block ProgramComments
In writing code, it’s sometimes necessary to add comments in specific sections for clarification. Why is this important? Consider if you are working in a team on a complex program, and you write the code without any comments. How will your teammates understand and continue your work? It would certainly complicate things for your team. This highlights the importance of comments in programming. Comments can be made for a single line or multiple lines. For a single line, comments typically start with “//“ with no ending required. If you want to include comments spanning multiple lines, they usually start with “/“ and end with “/“. In other programming languages, there may be variations; for example, Python uses “#” to indicate a single-line comment. Therefore, if you plan to learn other programming languages, be sure to read the documentation for each language to avoid syntax errors in comments.Here’s an example of using comments:
1
2
3
4
5
6
7
8
9if( filePtr == null )
{ //Single Line Comment
/* Multi
Line
Comment */
return ERR_CMD;
}Note: Single-line comments “//“ cannot be used in C, so to create comments in C, use “/ /“. Single-line comments “//“ can still be used in C++ programming.
Naming Conventions
In studying programming languages, we need to pay attention to the rules for naming variables, functions, classes, etc. Most naming conventions are similar and designed to make it easier for us to read the program code later. There are three important points to consider in naming conventions:- Use names that differentiate between each type of data.
- Use data type keywords as parameters in naming to indicate the content type of a variable/function/class after it is declared, which will also minimize errors.
- Use names that are recognizable and understandable (do not use abbreviations known only to you, like x = 5).
There are other important things you should know when creating names:
- Use these naming conventions as a general guideline, and if necessary, adjust the naming rules to the programming language you are using, as each programming language has different naming conventions (Read the Official Documentation!).
- Do not use names that are the same as keywords (if, else, for, while, etc.), as this will cause errors and make the program unreadable.
- Avoid using initials, such as a single letter, for naming variables/functions/classes in complex programs, as this can be confusing and difficult to distinguish.
- Do not start variable/function/class names with numbers, as this will cause the compiler to interpret it as a value, not a variable/function/class. Therefore, if your variable/function/class requires a number, it should not be placed at the beginning.
- Avoid naming variables/functions/classes with generic terms like “data.” Naming something “data” does not clarify anything. This can lead to confusion when maintaining code or adding new features later. Instead, use names that describe the value of the variable/function/class itself.
- Variables in programming languages like JavaScript and others can only begin with a letter or underscore. You cannot create a variable starting with a number or using symbols other than an underscore.
- Variable/function/class names cannot contain spaces. If the name consists of more than two words, use camelCase format, such as: FirstName, LastName, CatName, or you can use underscores “_” as a space substitute if you do not want to use camelCase, like: First_Name, Last_Name.
- Variable/function/class names cannot contain special characters (!,/,+,*,=, etc.).
- Avoid the habit of using all capital letters for naming variables/functions/classes, such as: NAME, PLACE, LIFE, etc. Generally, variable names in capital letters are used for creating constants (values that cannot be changed).
Here are some rules for creating functions/classes:
- Avoid creating too many parameters in a function if not necessary. If there are too many arguments, it will be difficult to test or use. If more than three function arguments are needed, they can be consolidated/discussed with your team. Instead of having many function parameters, utilize objects as parameters.
- Make a function perform only one task, as functions that do multiple things will be difficult to compile and test. Functions that do many things also lack a clear purpose. When creating a function that performs more than one task, try to break it down so that each function truly does one thing. This also makes the code within the function cleaner and easier to read.
- The function name should represent its purpose. We also need to pay attention to the naming of functions. Ensure the name given reflects the intent or task of the function. This can also help other developers/programmers easily understand the purpose of the function you created.
- Create functions to avoid code duplication. If you find yourself frequently writing repetitive code, you should pay attention to it. Repeated code is a strong candidate for creating a function. The goal is to allow the code to be reused simply by calling the function.
Running a Program
To run our program code, we need to first determine whether the programming language we are learning is executed using a compiler or an interpreter.- Compiler: A compiler translates code from a high-level programming language into machine code before the program runs. The compiler reads the entire file, executes it, and produces results (either running successfully or generating errors) even if there are errors in the code. Examples of programming languages that use a compiler are C/C++ and Java.
- Interpreter: An interpreter translates code written in a high-level programming language into machine code line by line as the code runs. The interpreter reads line by line, and if an error occurs, the program will stop immediately at the line where the error occurred. Examples of programming languages that use an interpreter are Python.
Types of Errors
It wouldn’t be complete without discussing errors in programming algorithms. An error is a mistake that occurs in the writing of program code. Generally, there are many types of errors depending on each programming language. Here are some types of errors that may occur while learning a programming language:- Logical Error: This is the hardest type of error to detect. It occurs not because of a mistake in writing or a runtime error, but due to an error by the programmer in writing the algorithm. When the logic is wrong, the output will also be wrong. Detecting it is quite difficult and time-consuming. Most logical errors occur due to miscalculations or using the wrong variables. Typically, a logical error will not cause the program to stop completely; the program can continue to run normally but will not function as expected.
- Syntax Error: This is one of the most common types of errors in programming. Syntax errors occur due to typos in keywords or mistakes in the code structure. When a syntax error occurs, the code will not run normally because the computer cannot understand it. Fixing this type of error requires attention to detail in identifying the writing mistakes.
- Runtime Error: This error occurs while running a program. Several causes can lead to runtime errors, such as input errors, calculation mistakes, and output issues. When a runtime error occurs, there is a significant potential for the program to crash. To fix this type of error, programmers often have to return to the development phase to identify the mistakes.
- Compilation Error: This occurs during the process where a program written in a high-level language is converted into a machine-readable format. Various types of errors, like syntax errors, may arise during this process. Sometimes, even if the syntax code is correct, compilation errors can still occur due to issues within the compiler itself. However, don’t worry; this type of error can be fixed during the development phase.
- Interfacing Error: This type of error may occur due to a mismatch between the software program and the hardware interface being used. In the case of web applications, it usually occurs due to incorrect web protocol usage.
- Arithmetic Error: This is a type of error in programming that falls under logical errors. However, this error involves mathematical calculations rather than writing code. It typically occurs when the computer cannot perform calculations input by the programmer. For example, asking the computer to divide by zero is mathematically impossible and will result in an error that prevents the program from running properly. To address this, you can:
- Understand basic mathematical operations.
- Avoid mistakes in using parentheses or the order of operations.
- Use negative numbers in calculations.
- Implement error handling methods such as try, catch, except, etc.
- Resource Error: This type of error occurs when the value of a variable you input is too large, exceeding the maximum limit allowed in programming. A program uses a certain amount of resources provided by the computer to operate. When the program requires more resources than the computer can provide, it will cause a resource error. To handle this, you can use load-testing applications to see what happens when you run the same program simultaneously.
- Semantic Error: This type of error in programming is similar to a logical error. However, the difference is that a logical error produces incorrect data, while a semantic error produces something that has no meaning at all.
The occurrence of the above errors can actually be avoided if you are more meticulous and plan well during the coding stage.
Flowchart & Pseudocode
Flowcharts and pseudocode are fundamental tools for learning algorithms and basic programming before writing actual code. Generally, to understand the flow of a program, we need to grasp how the program operates. To simplify this, you can illustrate it using a flowchart. Another method besides drawing a flowchart is to write pseudocode, which is a representation of the code you will write later.
Flowchart
A flowchart is a visual tool used to represent workflows or processes in the form of a diagram. In the field of IT, flowcharts are commonly used to depict the flow of a program before executing (writing the code) the program. Generally, flowcharts are used to plan, analyze, and understand the steps required to complete a task or solve a problem. A flowchart follows several rules in its creation, which apply to each flowchart symbol that is made. Below are the rules for each symbol used in the creation of a flowchart.
Rules for Each Symbol in a Flowchart
Flowchart Symbols and Their Functions
The symbols in a flowchart have specific meanings and functions that help in understanding the workflow. Some of the basic flowchart symbols include:
Start/End Symbol:
This symbol represents the start and end of a process or algorithm. It is typically depicted as an oval or a rounded rectangle.Process Symbol:
This symbol is used to indicate steps or actions that must be performed in the process. It is typically represented by a rectangle.Decision Symbol:
This symbol represents a decision point in the workflow that requires a yes or no choice. It is typically depicted as a diamond shape.Input/Output Symbol:
This symbol is used to represent data input or output in the process. It is typically depicted as a parallelogram.Connector Symbol:
This symbol is used to connect separate parts of a flowchart. It is typically represented by a straight line or an arrow.
The Function of Flowcharts in the IT Field
A flowchart has several important functions in the IT field, including:
Planning the Process:
A flowchart helps in planning the steps required to complete a task or solve a problem in a clear and structured manner.Analyzing Algorithms:
By using a flowchart, we can analyze algorithms visually and understand the logic applied in the programming process.Facilitating Communication:
A flowchart becomes an effective communication tool between programmers, analysts, and users in understanding the workflow of a system or program.Correcting Errors:
By examining a flowchart, we can identify and correct errors or bugs in the algorithm more quickly and efficiently.
Example of a flowchart in Programming
Here is a simple example of a flowchart in programming:
Flowchart for Calculating the Area of a Triangle
This example demonstrates the workflow in a simple program to calculate the area of a triangle.[{"url":"https://azizahijzah.wordpress.com/wp-content/uploads/2014/03/azizah.gif","alt":"Flowchart for Calculating the Area of a Triangle","title":""}]Algorithm for Calculating the Area of a Triangle
Flowchart for Filtering Odd and Even Numbers
This example shows the flow of determining whether the input number is odd or even.[{"url":"https://dicoding-assets.sgp1.cdn.digitaloceanspaces.com/blog/wp-content/uploads/2021/07/Contoh-flowchart.jpg","alt":"Flowchart for Filtering Odd and Even Numbers","title":""}]Algorithm for Filtering Odd and Even Numbers
A flowchart allows you to more easily explain the flow of a program, as its purpose is to break down processes using symbols. Additionally, a flowchart can also serve as a tool to communicate information about a program to others.
Pseudocode
Pseudocode is a method used to describe the algorithm or logic of a program without the need to use any specific programming language. This method serves as a very useful tool for developers, especially for simplifying the planning process and understanding the flow of a program.
Characteristics of Pseudocode:
Using Natural Language
Pseudocode is generally written in everyday language or language that closely resembles natural language, making it easier to understand by anyone, whether they are programmers or non-technical individuals.Clear Structure
Pseudocode must have a well-organized structure, such as having a clear and structured sequence of instructions.Not Dependent on Syntax
Unlike programming languages, pseudocode does not have strict syntax rules, making it more flexible in its writing.Algorithm Details
Although not as detailed as programming languages, pseudocode still includes the main steps of an algorithm that need to be understood.Consistency
Maintaining consistency in writing pseudocode is important to ensure that readers can follow the logic from start to finish.Using Symbol
Sometimes, basic symbols such as the “=” sign or logical operators are used to clarify steps in pseudocode.Used for Basic of Programming
Pseudocode is often used as a foundation to convert steps into code in a specific programming language.
Function of Pseudocode
Facilitating Understanding
One of the main functions of pseudocode is to facilitate understanding of how an algorithm or program should operate.Program Planning
Before writing code in a specific programming language, pseudocode helps in planning each step logically.Problem-Solving Documentation Tool
Pseudocode can serve as a documentation tool to describe the solution to a problem, making it easier to reference in the future.Communication
Pseudocode functions as a communication tool between programmers or team members to discuss solutions more easily.Helps Translate to Programming Languages
Pseudocode provides an overview that can be translated into various programming languages.More Concise and Practical
Pseudocode is simpler and more concise in writing compared to program code, yet it still includes the essential steps.
Structure of Pseudocode
Title
Typically, the title in pseudocode indicates the purpose of the algorithm being created, such as “Calculating the Area of a Circle.”Declaration
This section contains the declaration of variables or parameters used in the algorithm.Implementation
The steps or instructions that must be executed in the algorithm are written in this section.
Advantages of Pseudocode
Easy to Understand
Because it is written in more general language, pseudocode can be understood by a wide range of people, both experts and beginners.Flexible
Pseudocode is not bound by any specific syntax, allowing for more freedom in its writing.Good Documentation
As documentation, pseudocode makes it easier to revisit and understand the algorithm in the future.
Disadvantages of Pseudocode
Not Standardized
Because it lacks standard rules, pseudocode can sometimes vary between writers, which may cause confusion.Cannot Be Executed
Pseudocode only serves as a description and cannot be run on a computer.Less Details
Since it only provides an overview, some details of the algorithm may not be included.Subjectives
Writing pseudocode is subjective, so the interpretation can be different.
Pseudocode Algorithm Example
Finding the Area of a Triangle
1
2
3
4
5Title: Finding the Area of a Triangle
Declaration: base, height
Implementation:
area = 1/2 * base * height
Display areaDetermining Whether a Number is Odd or Even
Pseudocode:1
2
3
4
5
6
7Title: Determining Odd/Even Numbers
Declaration: number
Implementation:
If (number % 2 == 0)
Display "Even"
Else
Display "Odd"Here’s another example of pseudocode and its implementation in code:
Pseudocode:1
2
3
4
5
6Title: Print the Following
Declaration:
Implementation:
PRINT my name
PRINT my origin
PRINT my professionPython Code:
1
2
3
4
5print("Zulma")
print("Bintaro")
print("Software Quality Assurance")
Pseudocode is a very important tool in programming that helps simplify the planning and understanding of algorithms before they are coded. By using pseudocode, we can design problem-solving solutions in a clear, structured, and easily understandable way for various audiences. Despite having some drawbacks, such as being non-executable, pseudocode remains a strong foundation in designing good algorithms.
Exercise
Do the following exercise to test your understanding of the material that has been taught above.
Flowchart & Pseudocode Exercise
Flowchart & Pseudocode Exercise 1
Create a flowchart and pseudocode to calculate the area of a football field. (estimated 10 minutes)
Flowchart & Pseudocode Exercise 2
Create a flowchart and pseudocode to calculate the area of a circle. (estimated 10 minutes)
Flowchart & Pseudocode Exercise 3
Create a flowchart and pseudocode to determine student pass/fail. (estimated 10 minutes)
Flowchart & Pseudocode Exercise 4
Create a flowchart and pseudocode to convert temperatures. (estimated 30 minutes)
- Celsius to Fahrenheit
- Celsius to Kelvin
- Fahrenheit to Celsius
- Fahrenheit to Kelvin
- Kelvin to Celsius
- Kelvin to Fahrenheit
Basic Exercise
Convert the pseudocode below into a program written in the Python programming language. (estimated 5 minutes)
1 | Title: Print the Following |