Rapid Intro To Python: Part 2
Basic statements, simple I/O operations, type casting, decision making and loops.
In my previous post, I dedicated my entire focus on providing an overview of Python, including its functionality, usage, and potential applications. If you haven't read it yet, I suggest going through that post before continuing with the current one.
Today, we are going to start learning about Python's syntax. To be more specific, I will be delving into the following concepts:
Basic output and input operations in Python
Types and type casting in Python
Decision making
Repetition and looping in Python
Alright, let's get started.
I/O operations
I/O stands for Input/Output, it is a term used in computer science to refer to the communication between software and its external environment. Python, like many other programming languages, has built-in functionality for handling input and output operations.
In Python, Input and Output operations are carried out through the use of the input
and print
functions respectively. Let's take a closer look:
input ()
In Python, input
is used to receive user input from the keyboard in the form of a string of characters. The syntax of this function is as shown below:
variable_name = input(prompt)
Where prompt
is simply any message you'd want to display to inform the user to type in something. variable_name
is the name of a variable that stores the data.
print()
print
does the exact opposite of what input
does. It's used to output messages in Python. While there are other methods to display messages in Python, print
is very clearly the most frequently used. The format of this function is illustrated as follows:
print(message)
Where message
simply refers to the text that we intend to show on the console.
Types & Type Casting
Sometimes, our programs need to handle user inputs that are not in string format. However, the input
function returns all user-entered data as a string. To handle this, we need to find a way to convert the data returned by the input
function to the appropriate data type for use in our code. A technique known as Casting can be used to convert data in Python. This is done by passing the desired data to convert as an argument to a type constructor.
Type constructors in Python have the following format:
name_of_type(data_we_want_to_convert)
Where name_of_type
can be the name of any one of Python's data types; int
, float
, str
, tuple
e.t.c. If you'd like me to talk about data types in Python in a future article, please let me know in the comment section below. As regards constructors, I'll explain what they are and how to create your own in a future article, so just stay tuned to the channel. Alright, let's go on.
Decision Making
As a programmer, it is essential to write flexible and adaptable code that can perform a wide range of actions based on predefined conditions, this allows the code to be more efficient and reusable, and it will be easy to maintain the code in the future. As an example, lets say that we wanted to write a program that determines a user's eligibility to vote based on their age, using a simple decision-making process. To create such a program, knowledge of how to perform decision-making in Python is required.
In Python, decision-making is implemented through the use of branching statements such as the if-elif-else
statement. Syntax:
if condition1:
statement1
elif condition2:
statement2
.
.
.
else:
default statement
if-elif-else
works as detailed below:
The
if
portion of the statement is evaluated first. Ifcondition1
proves True, then onlystatement1
is executed by Python and the rest of the statement is ignored.If
condition1
proves false and anelif
is provided, thencondition2
is evaluated. If True, then onlystatement2
is executed and the rest is ignored.If there are no subsequent
elif
or all subsequentelif
prove False, then theelse
, if it was provided, is executed by Python.
So with that in mind, can you create a Python program that prompts a user for their age, uses decision-making to determine their voting eligibility and displays a message? Give it a try!
Here's how I created mine:
user_age_string = input("Enter Age:")
user_age = int(user_age_string)
LEGAL_AGE = 18
if user_age >= LEGAL_AGE:
print("Hurray. You're eligible to vote")
else:
print("Oh oh. Sorry, you're not eligible to vote")
When I try to execute this program on the command line, I get:
$
Enter Age: 21
Hurray. You're eligible to vote
$
Repetition
A.K.A Looping. The need to repeat actions multiple times in a program is a common requirement. For example, creating a countdown program like the one used by NASA for rocket launches using individual statements for each operation can be time-consuming, as it would require typing out multiple print statements for counting down from 10
to 1
and then displaying BLAST OFF!!!
.
print("10")
print("9")
print("8")
print("7")
print("6")
print("5")
print("4")
print("3")
print("2")
print("1")
print("BLAST OFF!!!")
OUTPUT:
$
10
9
8
7
6
5
4
3
2
1
BLAST OFF!!!
$
One of the weaknesses of this program is its inflexibility to updates as demonstrated by it's need for us to add excessive lines of code, in this case 90 more lines to make it count down from 100
to 1
. This makes updating the program impractical and time-consuming. It would be more efficient to use a method that allows for easier updates and flexibility.
One such way will involve the use of loops and will require you to learn how to create looping statements in Python.
There are two main types of loops used in Python:
for loop
This loop is a good choice when we know exactly how many times we want our program to repeat a specific action. This loop also has two different ways it can be written:
using the range() function:
If we would simply like to specify a certain number of times we want our loop to repeat, this is a good choice. Its syntax looks like this:
for i in range(start, stop, step):
# statements to execute go here
Where:
i
is a variable that holds the current count of loop repetitions. It's usually namedi
by programmers and sometimes can be given names such asx
,y
,iter
e.t.c. Nevertheless, this is just a convention, you can give it whatever name you want.start
is the number from which the loop starts counting. It's optional, so if you fail to specify it the loop starts counting from zero.stop
is the maximum number at which the loop stops execution. Take note of the fact that once the loop gets to this number, it stops executing i.e If you're printing out the repetition count, this particular number is never going to be printed. This is also not an optional parameter.step
is the stepping value i.e The value added to the current count to get to the next count. It's optional, so if you fail to specify it the loop steps each count by one.
using a collection
A collection is like a container that holds a group of things together. In programming, it's a way to store and organize a set of related items, like a list of names or a group of numbers. Collections in Python include list
, tuple
, dictionary
, set
e.t.c. Collections are the subject of my next article, so I'll explain better in that article. For now, let's just talk about how to use a for loop on a collection.
A for loop can be used to go through each item in a collection one by one. The loop will keep going until it has looked at all the items. The way you would write a for loop to go through a collection would look like this:
for element in collection:
#do something with element
Here element
is a variable that holds the current element of the collection
while loop
A while loop is usually useful when we want the loop to operate conditionally i.e We want the loop to keep repeating until a certain condition is met. Its syntax looks like this:
while condition:
# statements to execute go here
And that's pretty much all there is to know about Python looping statements in a nutshell. Now, let's get back to creating our countdown program. Here's what I did:
for count in range(10, 0, -1):
print(count)
print("BLAST OFF!!!")
And when I try to execute this program on the command line, I get the following output:
10
9
8
7
6
5
4
3
2
1
BLAST OFF!!!
So, as you can see, it does the same thing our initial program did but it's shorter, easy to maintain and easy to update which is always how we want our code to be.
Conclusion
Today, you took your very first steps in learning about the Python programming language. Hopefully, in the course of reading this article, you learned how to perform basic I/O, type casting, decision making and repetition operations in Python.
In the next article, you will discover the various collections available in Python to efficiently organize and manage data.
Thank you for reading this far, I hope you enjoyed it. I look forward to your next reading. Till then
Keep Learning
Keep Growing