Introduction to Programming
Over the past 20 years, we have seen dramatic jumps in technological gains in areas of
- Distributed Computing
- Cloud Computing
- AI Improvements
Programming history:
A lot of human error in the calculations â A Solution â Difference engine
INFO
The difference engine used mechanical gears with numbers 0 to 9 etched onto their gaps separated by gearâs teeth. Its key function was to carry out one operation that was computed by manually moving hand cranks until the final answer was revealed.
After building a working prototype, Babbage spent many years working on further improving his designs and constructing improved versions of the original idea. He created another device called a different engine two, but ultimately produced a new and better concept called the analytical engine.
The analytical engine is widely accepted as being the basics of modern day computing. Babbageâs friend, Ada Lovelace published a document describing how the analytical engine could perform a sequence of calculations, which is essentially what a computer program does.
However, the analytical engine was never completed and Babbage, like a lot of developers did not invest in good documentation.
Computers only understand binary code, which consists of two digits 0 and 1. 0 and 1 relate to different electrical states similar to a light switch, 0 is equal to off and 1 is equal to on.
Decimal (0,9) | Binary (0,1) |
---|---|
0 | 0 |
1 | 1 |
2 | 10 |
3 | 11 |
4 | 100 |
5 | 101 |
Computer represents the binary code by using tiny electrical conductors called transistors. These transistors are housed inside the central processing unit. CPU, which is essentially the brain of the computer.
TIP
When a program is written using any type of language it needs to be compiled or interpreted. The outcome is to turn readable programming code for us into readable programming code for the computer.
Programming
Programming is the ability to provide a computer with a set of instructions in a particular language that it can understand and perform those operations or tasks. In other words, you need to tell the computer what you wanted to do in a format and language it can understand.
TIP
Programming is a skill. The more you practice and learn, the better you become.
Why Python?
Python was created by Guido van Rossum and released in 1991. It was designed to be readable and takes a lot of similarities between the English language and mathematics. Since its release, it has gained greatly in popularity and supports a rich selection of frameworks and libraries.
At present, itâs currently one of the most popular programming languages to learn today. Itâs widely used in all areas of business, such as web development, artificial intelligence, machine learning, data analytics and various different programming applications.
- Web development
- Artificial intelligence
- Machine learning
- Data analytics
TIP
One of Pythonâs key advantages is that it makes developers very productive and allows projects to be completed more quickly.
The simplistic nature of Python abstracts a lot of complexity away from the developer to allow them to focus on the task at hand.
TIP
It lends well to the philosophy of write less, do more.
Installing Python paths (Optional for Windows Users)
If you want to work on your local device and have a Windows machine you will need to install Python. To install Python on Windows you first need to download the latest version from the python.org website.
-
Select the latest release.
-
Depending on what best suits your operating system, select either the 32-bit or 64-bit offering.
-
Click the link to download the file from the Windows Installer - Recommended.
-
Once downloaded, open the file.
-
In the installation window, check the following boxes:
- Install Launcher for all users
- Add Python 3.10 to PATH
-
Select Install Now.
-
Select Yes in the next window to allow the app to make changes to your device.
-
The installation process will begin. Wait for it to finish and then select Close once itâs successful.
-
You should now be able to access the latest release of Python from the Windows menu.
Required dependencies
On completion of this reading, you will be able to identify any required dependencies for your operating system.
Setting up Python on Windows is straightforward and it will install without any required dependencies. On Mac, however, you do need some additional dependencies prior to installing Python.
XCode
To install brew, you need to install Xcode first. Homebrew does not come with its own compiler and it needs Xcode installed for it to work correctly. To install Xcode do the following:
- Open a terminal.
- Run the following:Â
shell xcode-select --install
- A popup will appear asking you to confirm the installation. Click on the Install button.
- Agree to the license agreement.
brew
Macs do not come with package managers like most Linux distributions. To make up for this an external tool called brew was created. To install brew, do the following:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Running code - Command line VS IDE
The first way is using the Python shell, and the second way is to run a Python file directly from the command line terminal. The Python shell is useful for running and testing small scripts.
Letâs explore the second main way to run Pythonâs programs, which is running a Python file directly from the command line or terminal.
NOTE
Note that any file that has the file extension of
.PY
can be run by following command.
VS Code is a better choice than using the Python shell or running it directly from the terminal because besides including both of these options, it comes with a plethora of additional improvements that make coding in Python a better experience.
- Auto-completion
- Debugging
- Code syntax
- Highlighting
- Whitespace
- Indentation helpers
There are two options run programs through Python.
- One is to run directly from the command line or the terminal if youâre on Mac,
- and then the other option is run directly from the IDE, which in this case is Visual Studio Code.
Python syntax, spaces matter
TIP
If you put
;
at the end of a line of code, you can continue the next code in the same line.print("Hello"); print("Wordl!")
TIP
If you want to write a part of the code on a line, and the rest of that in the next line, you can use a
\
at the end of the first line.x = 1 + 2 \
+ 3
Python syntax cheat sheet
This reading provides you with a cheat sheet that can be used for quick reference.
Spacing
Correct
Incorrect
Indentation
Correct
Incorrect
Commenting code
On completion of this reading, you will be able to explain why and where to use comments in coding.
Adding comments to code not only helps you as a developer but also helps other members of your team. Comments are great for refreshing your memory of code you may have written months ago and you may have forgotten what it was intended to do. There are multiple reasons why you need to add comments to a code file. They can range from the following:
- Explaining what the code is intended to do.
- Let developers know that code is deprecated.
- Add TODO comments for work to be completed at a later time.
Below are examples of the different types of comments that can be used.
Single-line comments
The use of a #
 symbol tells Python to ignore everything after this point until the end of the current line.
Multi-line comments
Python does not really have a method of declaring multiline comments so a # symbol can be used at the beginning of every line of the comment.
Inline comments
The #
symbol tells Python to ignore everything after this point until the end of the current line, this allows the placement of comments within the code itself. Inline comments should be used to supply important information about the code they deal with.
Remember to always have a reason for a comment, they should supply information to the reader and not be a distracting nuisance
Variables
For a variable that has already been declared, you only need to reassign or redeclare it.
The examples so far have relied on simple naming conventions such as X, Y, and Z. When working on a project with other developers, it will become increasingly difficult to know what these variables mean or refer to. As a programmer, you will write a loss of code over time, and if itâs been a few months, youâre most likely not remember exactly what the code was supposed to do. Using generic variables like X and Y doesnât give any information about that variable and where it is used. Giving meaningful names to your variables that makes sense in the given context will allow you and other programmers to easily understand whatâs going on.
NOTE
The key function of the variable is to keep a reference to some value.
Naming conventions
One option is called camelCase. The first letter of the first word is lowercase, and the first letter of every word after that is uppercase with no spaces between words.(eg. myName
)
I can take a different approach with snake_case. When using snake_case, you keep everything in lowercase letters, but you use an underscore between words.(eg. my_name
)
TIP
Although you have different options as a developer, itâs a good idea to be consistent when you are creating variables across your programs.
TIP
Single line declaration
Deleting a variable â del
Basic data types
Data type
A data type is an attribute associated with a piece of data that tells a computer system how to interpret its value.
Knowing what data types to use ensures that data is collected in the preferred format. It also ensures that the value of each property is as expected.
Python offers raw data types to allow data to be assigned to variables or constants. The five main types which are classed as literals consist of:
- numeric,
- sequence,
- dictionary,
- Boolean,
- and set.
Numeric
- Integers
- Floats
- Complex numbers
type()
To determine a type of variable, Python also provides a function names type, which will provide the class type based on the variable being passed.
The integer class
represents any non-fractional number, that is whole numbers with no decimal places. These numbers can be positive or negative.
Floats
are numbers that contain decimal places and are represented by the floats class.
The complex
class is used to represent complex numbers which are made up of both real and imaginary numbers.
a = 10 + 10j
Sequence
Sequence types of clusters container types that contain one or more of the same type in an ordered list. They can also be accessed based on the index in the sequence.
Python has three different sequence types, namely
- strings,
- lists,
- and tuples.
String
is a sequence of characters that is enclosed in either a single or double quotes. Strings are represented by the string class or str for short.
Lists
are a sequence of one or more different or similar types. They are essentially an array and hold any type inside square brackets. Each item can be accessed by its index.
Tuples
are similar to lists in many ways. They contain an ordered sequence of one or more types, but the main difference is that they are immutable. This means that the values inside the tuple cannot be modified or changed. Tuples are represented by the tuple class and hold datatypes wrapped in parentheses.
Dictionary
Dictionary store data in a key value object structure. Each value can be accessed directly by its key. Dictionaries can also store any data type.
Boolean
Boolean data types which are simply represented as true or false. Combined with logical operators, Booleans are used to check whether a condition is true or false.
Set
which is an unordered and non-indexed collection of non-repeated values.
WARNING
Whenever you declare a variable in Python, the datatype is automatically assigned for you based on the value of that variable.
Strings
String
A sequence of characters in single or double quotes.
'We are open'
"24 hours a day!"
Computers only understand binary code, which consists of ones and zeros. This means that characters need to be converted to a form that computers can interpret, a process known as encoding. Python uses a type of encoding called Unicode to communicate with computers.
Single Line
Multi Line
NOTE
Itâs important to know that a string is just a sequence of characters, which in turn means it is essentially an array. Each character in the sequence can be accessed based on its index.
len()
Concatenation
TIP
The plus symbol is usually used as an arithmetic operator, but when applied on strings, it combines them instead.
Basic Data type and Function Cheatsheet
Data types
Data type | Meaning | Example |
---|---|---|
string | Text | âHelloâ, âTesting 123â |
integer | Numbers | -5, 4, 3, 2, 0 |
float | Decimals | 2.4, 5.2, 1000.00 |
Flow Control
Comparison operators
Operator | Meaning | Example |
---|---|---|
== | Equals | a == b |
!= | Not Equal | a != b |
< | Less than | a < b |
> | Greater than | a > b |
â | Less than or Equal to | a â b |
>= | Greater than or Equal to | a >= b |
Comments
Single-line comments
Placing a #
 symbol in front of the text you want to be a comment causes Python to ignore everything from that point until the end of the current line.
Multi-line comments
Python does not really have a method for multi line comments, so a #Â symbol can be used on every line.
Inline/code comments
The #
symbol will cause Python to ignore everything from that point until the end of the current line, so inline comments can be created in this way.
Built-in Functions
print()
This function looks for the default output device, your terminal, and displays the value passed to it.
input()
This function looks for the default input device, your keyboard, and captures the value. This value can then be assigned or used.
len()
This function returns the length or the count of the elements contained within the structure it is applied on. This may be a string, array, list, tuple, dictionary or any sequence.
str()
This function can be used to convert the provided value into a String
.
int()
This function can be used to convert the provided value into an int
.
float()
This function can be used to convert the provided value into a float
.
Creating Functions
Functions in Python require a keyword to define them : def
followed by an identifier (a name) this forms the function signature. The body of the function contains the code to run when the function is called.
Type casting
Type Casting
Typecasting is the process of converting one data type to another.
Python has two different types of conversions;
- implicit
- explicit
Implicit
Implicit data type conversion is performed automatically by Pythonâs compiler to prevent data loss.
It will convert, for example, an int
to a float
if it picks up that the inserted value is a decimal.
WARNING
Python will only be able to convert values if the data types are compatible. int and float are compatible but Strings and int are not. If data types are not compatible, Python will throw a type error.
Explicit
Using Python functions. There are many functions but some of the most common are
- string
- integer
- float
string cost function
This is used to convert any datatype into a string datatype.
int type casting function
float function
Some Other functions
ord()
: which returns an integer representing the underlying unicode character.hex()
: which converts a given integer to a hexadecimal string.oct()
: which takes an integer and returns a string representing an oct to a number.- There are also:
tuple()
set()
dict()
User input, console output
input()
'Please enter your email address: '
â a prompt
print()
can be used to print all different types of data and it allows for more complex formatting. The print function itself accepts any number of arguments.
Print arguments
Pythonâs print function also has reserved keywords that can be parsed as additional arguments:
objects
: that is values that are printed on screensep
: which defines how the objects being printed or separatedend
: which defines what gets printed at the endfile
: which specifies where values get printed to, and by default it is STD outflush
: a Boolean expressions to flush the buffer, which essentially just moves the data from a temporary storage to the computers permanent memory storage
Direct formatting
Output formatting
Type casting, a deeper look
Another, more informal way to refer to it is âdata type conversionâ. The simplest example of converting data could be the following comparison:
In the above piece of code, Iâm asking Python if the number 10 is equal to the number 10, and Iâll get the boolean value of True printed, confirming that indeed, they are the same. What if I do this?
Again, the boolean value of True
 is output on the screen.
Now, you might complain that, well, 10
 is not technically equal to 10.0
 - because, one might argue, the first number is an integer, and the second number is a float. You would be right - although these are the same numbers, they are not the same data types.
However, Python here performs whatâs known as âimplicit type conversionâ.
To understand how this works, Iâll slightly tweak the previous example. Instead of asking Python to compare the two numbers and return if they are the same or not, Iâll ask Python to print the result of adding these two numbers together.
The printed result is 20.0
.
This output allows me to conclude that when Python runs operations involving integers and floats, it implicitly converts the integers type to a float, and then completes the operation.
To really drive this point home, I can extend my previous example, using the type()
 function:
The output is <class 'float'>
, so this confirms my conclusion.
Let me know show you a small program in Python, working with numbers:
When I run this program, I could, for example, provide the first numberâs value as 5
, and the second numberâs value also as 5
, expecting that the printed user_sum
 value will be 10
.
However, when I do exactly that, the number 55
 gets printed instead.
Why was this not working?
Well, the answer is pretty simple: everything that a user types in, is converted, by Python, to the string data type.
This means that, although I typed numbers into these two inputs, what was saved in user_num_1
 and user_num_2
 were actually strings.
Effectively, itâs exactly the same as if I just did this:
This time, the output of printing user_sum is still â55â, but this comes at no surprise. In order to have my Python code work as I intended, I need to perform explicit type conversion. In other words, I have to convert the value of â5â to the value of 5.
Hereâs my updated code:
What Iâm doing here is, Iâm making sure that my program can handle even accepting floats as inputs, and still work correctly.
In other words, Iâm making sure that if a user provided, say, the float value of 5.5
 as both the first and second numbers when running the above code, the output would not throw an error. Instead, it will be the expected 11.0
.
What if I decide to output some words to the user, telling them what happened? Hereâs an attempt at doing that:
If I run the above code, it will throw the following error:
What this means is, I cannot concatenate a string and a float like that. In other words, although Pythonâs implicit type conversion works when I use the + operator on strings and integers, it does not work on strings and floats.
The solution to this is to perform explicit type conversion, as follows.
This time, the output is: The sum of 5.5 and 5.5 is 11.0
.
Additional resources
Python allows you to do quite a lot with very little code. Compared to other languages such as Java or C#, Python has a much easier learning curve. It lends itself well to the âwrite less, do more philosophyâ. Python developers are also in high demand and learning how to program in Python makes for a good career choice.
You can access the links below to learn more about programming in Python.
Check out the Python website to find out more about built-in functions: Python
Check out W3 Schools to learn more about coding and web development: W3Schools
Check out HackerRank to practice your new acquired Python skills: HackerRank
Previous one â 6.Introduction to React | Next one â 2.Control flow and conditionals