Introduction
Python is one of the most versatile, popular, easy to learn and general purpose programming languages. This tutorial is designed for beginners with zero programming knowledge who wants to learn python or anyone with prior programming knowledge who wants to learn python or refresh their memory.
In this tutorial, we are going to be using a web based IDE called Replit for writing our python code. With Replit, you do not need to download or install anything on your computer. Note that you can use any other web based or any of traditional IDEs, it must not be Replit. Just google for web based IDE and you will see one to use.
Sign up to Replit
To access Replit IDE, just follow the four simple steps below:
Go to www.replit.com
Sign up
Create a python Repl by selecting python under the template dropdown
Replit will create a file named main.py for you. Note all python files must end with “.py” extension whether you are using web based IDEs or traditional IDEs
The IDE will open for you. Replit IDE is divided into left and right portions. You write your code on the left portion, click on the green “Run” button and the output or error message - where you make syntax error will be displayed on the right portion. See Fig 1e below:
Fig 1e
Your First Python Code
Now that you have your IDE ready, it’s time to write your first code. Open your IDE and *TYPE the line of code as shown Fig 2i below. Run the code and see the output in the console
Fig 2i
print("Hello World")
Note:
*Please pay attention to the emphasis on TYPE above. It is highly advisable that you type all the practice codes in this and all of our tutorials. Avoid copying and pasting the practice codes into your IDE. Typing them significantly enhance your learning and understanding
print() is a function or an instruction to the computer in python that is used to display the output of a code on the console/screen. You will learn more about functions as you progress in your coding journey.
Anything that is written inside the parentheses at the front of the word “print” will be displayed on the console. What you want to be displayed on the console can be strings, numbers or even the result of arithmetic operations as shown in the line of codes in Fig 2ci below. Note that you need to wrap strings inside double or single quotation in addition to the parentheses. Practice with the code on Fig 2ci in your IDE
Fig 2ci
print("Hello world") print(234) print(4 + 5) print(4 * 5) print('Hello class')
If you type a line of code without making it an *argument of the print( ) function, such line of code will not be displayed on the console and you will not get any error message as long as the line of code is syntaxically correct. If you run the codes in Fig 2di below, python will not display lines 3, 5 and 7 in the console. In addition, you will not get an error message because all the lines of code meet python syntax rule. Practice with the codes in Fig 2di in your IDE.
Fig 2di
print("Hello world") print(234) 5 * 6 #This is line 3 print(4 + 5) "Hello Michael" #This is line 5 print(4 * 5) 4 * 5 #This is line 7
*argument - in a lay man explanation, this is simply the value that is inserted into the parenthesis of a function when the function is called.
Python executes the codes line by line from the top to the bottom and ignores blank lines. In the Fig 2ei below, python ignored the blank lines 3 and 4, that is why there will be no space in the output on the console when you run the code. Practice with the codes in Fig 2ei in your IDE
Fig 2ei
print("Hello world") print(234) #This is blank line 3 #This is blank line 4 print(4 + 5) print(4 * 5) print('Hello class')
Comments in Python
You can comment out (i.e make python to ignore) a line of code by starting the line with “#”. To comment out multiple lines of codes, enclose the lines in triple quotes. Try the codes in Fig 3i below in your IDE. When you run the codes, lines 1 and 3 will be ignored because they started with “#” while lines 5 to 7 were commented out because they were wrapped inside triple quotes.
Fig 3i
#Examples of comments in python - This is line 1 print("Hello world") #To display greeting on the console #print("234") - This is line 3 '''print('4*5') #This is line 5 print("4*10") #This is line 6 print('Hello class') #This is line 7''' print("I will post a new tutorial next week")
Why do we use comments?
To add a general description about the code as we did in line 1 of the screenshot above
To add information or explanation about a line of code as done in line 2
To disable a line of code as done in line 3
Variables
Variables are containers used for storing data values. A variable acts as a placeholder for information you want python to recall later in the coding process when an action is required to be completed.
Usually, a variable has three parts: the variable name, the assignment operator “=” and the variable value. The general syntax for a variable is as follows:
variablename = variablevalue
Note that the equal “=” is not serving the same purpose as it does in mathematics, it does not mean equality between the variable name and variable value. Rather, it is used as an assignment operator to assign values to the variable
Things to note about python variables
A variable name can only start with a letter or an underscore. It cannot start with a number but a number can be in between or at the end of the name. Try the code in Fig 4ai below in your IDE. Then, attempt to start one of the variables’ names with a number (for example, in Fig 4aii below, we started variable in line 4 with “3”) and run the code again, you will get the error message.
Fig 4ai
example = "This is an example of a variable" number = 50 * 4 number1 = 100 + 400 test2num = 12 * 10 print(example) print(number) print(number1) print(test2num)
Fig 4aii
example = "This is an example of a variable" number = 50 * 4 number1 = 100 + 400 3test2num = 12 * 10 #This is line 4 print(example) print(number) print(number1) print(test2num)
The variable name must always be on the left side. If you type the following code on your IDE, it will run successfully:
number = 50 * 4 print(number)
However, if the code is rearranged as shown below, you will get an error message when you run the code
50 * 4 = number print(number)
A variable name cannot be any of python keywords such as if, for, while, and, as, try, True, False, else, elif, except etc. You will know more about python keywords as you progress in python programming
A variable name can only contain alpha-numeric characters and underscores
Variable names are case sensitive. For Example, all the variable names below are not the same because variable name “price” was written with an inconsistent case. “price” in line 1 starts with small letter “p”, “Price” in line 2 starts with capital letter “P” while “PRICE” in line 3 was written in CAPs.
price = 10 Price = 12 PRICE = 15
In python, where the variable name case is maintained as it was when it was originally declared, the most recent value assigned to the variable will overwrite the prior (earlier) value that was assigned. For example, when you run the code in Fig 4ei below, the value assigned to “price” in line 1 will be overwritten by the value assigned to “price” in line 3 but not the value assigned to “Price” in line 4 because “Price” in line 4 starts with an uppercase “P”, hence it is not the same with “price” in line 1 and 3 which starts with lowercase “p”
Fig 4ei
price = 10 #This is line 1 PRICE = 12 #This is line 2 price = 15 #This is line 3 Price = 20 #This is line 4
Give your variables a meaningful name to enhance readability of your code. For example, python allows you to name your variables with single letter such as:
x = 30
However, x could be age, price, length or anything. Hence, it is best practice to use a name that reflects the property or quantity they represent to make them more readable and meaningful. For example:
If the variable represents age, the variable is better written as: age = 30
If it represents price, it is better written as price = 30
If it represents distance, it is better written as distance = 30
You can assign multiple values to multiple variables on the same line provided they have the same number of column on both side as indicated in Fig 4gi below, try the code in your IDE
Fig 4gi
age, height, sex = "18", "5.6", "male" print(age) print(height) print(sex)
Benefits of using Variables in programming
It allows for easy and faster maintenance of code
It enables reusability of codes
4hi
age = 40 name = "David" school = "St Joseph College" length_service = 15 print(f"The name of {school} principal is {name}. {name} is {age} years old. {name} has been working at {school} for {length_service} years")
Refer to Fig 4hi above, imagine we are required to write a 10 page report for multiple schools where the school name, age, name, length of service of the principal is repeated severally in the report, if we need to adapt the report for another school, we would need to read through the 10 page report to make all the changes, or use ctrl-find-and-replace. Either way, the risk is very high that we can miss out some of the necessary corrections. However, with the use of variables, we only need to make changes on 4 lines and the document is ready without any risk of errors of omission in the adaptation of the document.
NOTE: We used formatted string (f and { }) with print( ) function to bring in the variable values into our print statement; the variable(s) are wrapped in curly brackets { }. The standard syntax for formatted string is as follows:
Print(f“the string you need to type {name of variable you want to bring in} more strings {name of another variable you want to bring in} any other string”)
A variable can be used to store numbers, strings or boolean
Boolean is a data type that is either True or False. Examples of this can be:
is_male = True or False; normally an animal can either be a male or female
is_white = True or False; a colour can either be white or not
is_alive = True or False; someone can only either be alive or dead
x > y; this expression can either be True or False. A number “x” can either be greater or less than another number “y”. When you compare two values, python evaluates the expression and returns either True or False (a boolean answer). Try the following codes in your IDE
print(5>10) print(7 == 7) print(4 == 7) print(5<10)
Strings in Python
Strings are simply texts characters. Any set of character(s) enclosed in double or single quotes is treated as string(s) by python. For example in Fig 5ai below, “Hello world” and “234” etc are strings. If you enclose numbers in double or single quotes, they automatically become strings. Try the code in Fig 5ai in your IDE
Fig 5ai
print("Hello world") print("234") print('4*5') print("4*10") print('Hello class')
If you fail to follow the syntax in any of the lines, e.g forget to use the parenthesis, or insert a string in a single or double quote, python will yell at you. In Fig 5bi below, we deliberately did not close the parenthesis in line 5 and python gave an error message without executing the instructions for the lines of code which were correctly written. Try the faulty lines of code in your IDE.
Fig 5bi
print("Hello world") print("234") print('4*5') print("4*10") print('Hello class' #This is line 5
String Length - You can get the length of a string with len() function. Try the code in Fig 5ci below in your IDE. Note that python counts the space between the two words as a character and returned 11 as the output of the code.
Fig 5ci
greeting = "Hello World" print(Len(greeting))
String index position - Python indexes characters in a string starting with index number 0 from the first character in the string, moving from left to right. Indexing allows us to pick any character from the arrays of characters that make up the string. In python, it is also possible to start the indexing from the last character in a string, in this case, the indexing starts from -1 for the last character in the string. Practice with the code in Fig 5di below in your IDE. You can ignore the comments in your practice, they were included for further explanations.
Fig 5di
name = "Tutorial" #indexes 01234567 indexing from the first letter #if you want to index from the last character, "l" will have index of -1, -2 for "a", -3 for "i", -4 for "r" etc print(name) print(len(name)) #the length of characters in "Tutorial" is 8 print(name[0]) #the index of the first character "T" is 0 print(name[4]) #the index of character "r" is 4 print(name[-2]) #starting from the end, the index of "a" is -2 print(len("Tutorial")) #You can get the string length directly
Manipulating strings with functions
You can perform a number of operations on strings using python built-in functions such as:
len() - used to count the number of characters in a string. Note that len() function counts space as character. The syntax is: print(len(string))
.upper() - used to convert strings into upper case. The syntax is: print(string.upper())
.lower() - used to convert strings into lower case. The syntax is: print(string.lower())
.capitalize() - used to convert strings to sentence case. The syntax is: print(string.capitalize())
.title() - used to capitalize each word in a string. The syntax is: print(string.title())
.replace() - used to replace a character or a word in a string. The syntax is: print(string.replace(“character_or_to_be_replaced”, “replacement_character_or_word”))
Practice with the codes in Fig 5ei below in your IDE for better understanding, you can ignore the comments
Fig 5ei
course_name = "Python Tutorial" print(len(course_name)) #python also counts the spaces print(course_name.upper()) #To convert the string to upper case print(course_name.lower()) #To covert the string to lower case print(course_name.capitalize()) #To convert to sentence case print(course_name.title()) #To capitalize each word print(course_name.replace("Tutorial", "Training")) print(course_name.replace("P", "T")) print(len("Python Tutorial"))
Math Operations in Python
Numbers in python can either be an integer (whole number) or float (numbers with decimal fractions) The keywords “int” and “float” are used to tell python whether we want the data type to be an integer or a float
Integers are whole numbers, we use the int() function when we want the data type to be whole numbers such as 10, 20, 22, 28, 60……..
Floats are numbers with decimal fraction, we use the float() function when we want the data type to be numbers with fractions
As already seen in section 2 python can perform arithmetic operations such as:
Multiplication e.g
print(4 * 3)
Addition e.g
print(2 + 5)
Division, e.g
print(18/6)
Modulus, e.g
print(14 % 3)
#This is refer to as 14 mod 3, the instruction will divide 14 by 3 and give us the remainder which is 2Raising a number to the power of another, e.g print(3 ** 2) #This operation raises 3 to the power of 2
Combination of addition, subtraction, addition, division and multiplication. e.g
print(5 + 4 * 3)
#Note that this type of operation will follow the order of operations as follows: first multiply 4 by 3 and then add 5 to the result of the multiplication operation. You can use parentheses to change the order of operations; for exampleprint((5 + 4) * 3)
, in this case python will add 5 to 4 and then multiply the result by 3By order of operation variables inside parenthesis take priority and get evaluated first, this is followed by multiplication, then division, then addition and finally subtraction. What is called BODMAS in math
Try the examples above in your IDE as shown in Fig 6bi below:
Fig 6bi
print(4 * 3) print(2 + 5) print(18 / 6) print(14 % 3) print(3 ** 2) print(5 + 4 * 3) print((5 + 4) * 3)
Storing numbers in variables - numbers or arithmetic operations can be stored in variables. Practice the examples in Fig 6ci below in your IDE
Fig 6ci
number = 5 result = 2 + 3 * 6 print(number) print(result) print(number * result)
Converting number to string - you can convert a number to a string with str() function. E.g
str(x)
where x is the number you want to convert. For example,age = 25 print(str(age)) # Even though this line of code displays 25, the 25 is no longer an integer, it is now a string. Try this code in your IDE
This conversion comes in handy when you need to print a number alongside strings. When you run the code in Fig 6di below, you will get an error message because the age was not converted to a string
Fig 6di
name = "James" age = 25 print("My name is "+ name + " I am "+ age + " years old.")
To fix this error, all we need to do is just convert the age to string by changing
age
in the print() statement tostr(age)
as shown in Fig 6dii below:Fig 6dii
name = "James" age = 25 print("My name is "+ name + " I am "+ str(age) + " years old.")
You can perform math operations with python in-built functions such as:
abs(); this is used to get the absolute value. E.g
print(abs(-5))
pow(); this is used to compute a number raised to the power of another number. E.g
print(pow(3, 3))
max(); this is used to return the bigger of the numbers inside the parenthesis. E.g
print(max(18, 32))
min(); this is used to return the smaller of the numbers inside the parenthesis. E.g
print(min(18, 32))
round(); this is used to round numbers in the parenthesis to the nearest whole number. E.g
print(round(8.4))
Try all the examples in Fig 6ei below in your IDE
Fig 6ei
print(abs(-7)) print(pow(3, 3)) print(max(18, 32)) print(min(18, 32)) print(round(8.6))
Comparison Operators
See below the list of common comparison operators in python. These operators are highly invaluable in coding, most especially for if/conditional statements.
== This is the equal sign
!= Not equal to sign
>= Greater than or equal to
<= Less than or equal to
Python List
List is used to store arrays of data in python programming. It enables us to organize and manage multiple related data. Unlike a variable that is usually assigned one value, a list can be assigned multiple values.
Creating and naming a list is somehow similar to creating a variable. For example, you need to give your list a meaningful name
To make it simple, we recommend that you follow the same naming rule for variables while naming your list
A list is created with a name and square brackets [ ] containing the list items separated by commas.
A list can contain a different type of values such as number, string, boolean, etc. Where the list item is a string, you need to wrap it in a double quotation. See the syntax below:
list_name = [listItem1, listItem2, listItem3, listItem4, listItem5]
See below the list of fruits as an example:
fruits = [“Apple”, “Grape”, “Orange”, “Mango”, “Cherry”, “Plum”, “Avocado”]
Some list operations:
You can print the entire list with print() function. For example you can print the entire fruits list with the following lines of code:
fruits = [“Apple”, “Grape”, “Orange”, “Mango”, “Cherry”, “Plum”, “Avocado”] print(fruits)
Similar to variables, you can access a particular item in the list using their index value. Recall that index numbering starts from number “0” moving from the left to right, e.g. in the fruit list above, Apple index number is 0, Grape is 1, Orange is 2, etc. If you are moving from right to left, the index numbering starts with number “-1”, e.g. in the fruit list above, Avocado index number is -1, Plum is -2, Cherry is -3, etc. Practice the following codes in your IDE. You can exclude all the comments, they were included for explanatory purpose.
fruits = [“Apple”, “Grape”, “Orange”, “Mango”, “Cherry”, “Plum”, “Avocado”] print(fruits[0]) #this code will return Apple print(fruits[3]) #this code will return Mango print(fruits[6]) #this code will return Avocado print(fruits[-1]) #this code will return Avocado print(fruits[-5]) #this code will return Orange print(fruits[-7]) #this code will return Apple print(fruits[1:]) #this code will return items from index 1 (Grape) to the end print(fruits[2:5]) #this code will return values at index 2 to 4 but excludes index 5
Modification of items in a list: We can modify the items in a list using their index number. For example, we can change the Grape in our fruits list to Banana by adding the following lines of code:
fruits[1] = "Banana" print(fruits) #to see the impact of fruits[1] = "Banana"
Using functions to modify lists: There are in-built python functions which can be used to modify lists in python. Practice the examples below in your IDE
fruits = ["Raspberry", "Mango", "Banana"] fruits2 = ["Pear", "Papaya", "Blackberry"] print(fruits) print(fruits2) fruits.extend(fruits2) #To add fruits2 list to fruits print(fruits) fruits.append("Apricot")#To add Apricot to the end of fruits list print(fruits) fruits.insert(4, "Lemon") #To insert Lemon into index no 3 in fruits list print(fruits) fruits.remove("Raspberry") #To remove Raspberry from the list print(fruits) fruits.pop() #To remove the last item in the list print(fruits) print(fruits.index("Mango")) #To get Mango index number fruits.sort() #To sort items in the list in alphabetical order print(fruits) fruits.clear() #To remove all the items in the list print(fruits) fruits.append("Apple") print(fruits)
Python Tuples
Tuples are similar to lists. However, unlike lists, tuples are immutable. That is, tuples cannot be changed or modified once they are created. In addition, tuples are created with parenthesis ( ) instead of square brackets that are used in lists. Tuples indexing is similar to lists indexing, it starts from “0” (zero) if you are moving from left to right and “-1” if you are moving from the right to left
Tuples are used in situations where the data are not expected to change or where you do not want the data to be modified. Practice with examples in Fig 8i below in your IDE:
age = (12, 14, 15, 18) # this is a tuple age2 = [10, 11, 13, 16] # this is a list print(age[1]) #To print the tuple element at index 1 age2.append(19) #If you try this with age (a tuple) you will get an error message. Remember that tuples are immutable print(age2) coordinates = [(2, 4), (3, 6), (4, 8)] #This is a list of tuples. Hence, you can make modification to the list but you cannot make modification to the tuples within it coordinates.append((5, 10)) print(coordinates)
Python if Statement
if statement is used to program computers to make decisions based on predefined conditions. It makes our program respond and make intelligent decisions based on input provided by the user. If statements are usually used with a boolean (True or False) data type. Here is the general syntax for if statement:
if condition = True:
Perform taskA
elif condition is False:
Perform taskB
Else condition is neither True or False:
Perform taskC
When you are using an if statement in python, you need to ensure proper indentation and close each conditional statement with a “:” as shown in the general syntax above, otherwise, you will get an error message. Most IDE will automatically indent your code for you provided you follow the syntax correctly
Note:
elif is used for an intermediate alternative course of actions. It is possible to have no elif in an if statement where there are only two alternative courses of actions; in which case the if statement will end with “else”.
You can have one elif where there are only three alternative course of actions
You can have multiple elif where there are multiple courses of actions
else is used for the final or the last course of action, you can only have one else in a block of if statement
Practice the examples in Fig 9i below in your IDE. Before you practice, note that: we used “and” to combine multiple conditions and the “not()” function to negate the booleans in the if statement. For example, not(is_sunny) is the syntax for “is not sunny” or a way of telling python that is_sunny is false.
“and” is used to combine two or more conditions if all the conditions must be satisfied
“or” is used to combine two or more conditions where only of of the conditions needs to be satisfied
Practice by changing the values of the variables from True to False one after the other and see the what you get as your output
Fig 9i
is_raining = True is_sunny = True is_cold = True if is_raining and not(is_sunny) and not(is_cold): print("Wear your raincoat") elif is_sunny and not(is_raining) and not(is_cold): print("Take your umbrella") elif is_cold and not(is_raining) and not(is_sunny): print("Wear your winter jacket") elif is_raining and is_cold and not(is_sunny): print("The weather is bad! Wear waterproof winter jacket") elif is_raining and is_sunny and is_cold: print("This is an odd scenario! Wear waterproof jacket") else: print("It's a nice weather")
Getting input from users
Getting input from users makes the program interactive. This is achieved with the help of python-inbuilt “input()” function.
Note that when you use input( ) function to get input from users the output is usually automatically converted to a string irrespective of the data type entered by the user. Hence, if you need the output to be an integer or a float to perform arithmetic operations on it, you will need to convert it to the appropriate data type to avoid getting an error message.
Let us go to the IDE and do some practice
Getting input from user - string. Practice with sample codes in Fig 10ai below
Fig 10ai
first_name = input("Enter your first name: ") last_name = input("Enter your last name: ") age = input("Enter your age: ") address = input("Enter your address: ") print("Hello " + first_name +" " + last_name + " you are " + age + " years old. You reside at " + address +".") #See below an alternative way to print your output print(f"Helllo {first_name} {last_name} you are {age} years old. You reside at {address}.")
Getting input from user - integers and float
The output of operations using input() function are strings even when the user enters a number. We need to convert the output to integers or floats using int() or float() function if we need to perform arithmetic operations on them. Practice with the lines of codes in Fig 10bi below
Fig 10bi
first_num = input("Enter the first number: ") second_num = input("Enter the second number: ") print(first_num + " x " + second_num + " = " + str(int(first_num)*int(second_num)))
The code in the Fig 10bi above will work perfectly as long as the user enters whole numbers (integers). If the user enters a fractional number such as: 5.5, 4.5, 7.8 ….. the code will run into problem. Try and run the code with at least one fractional number, you will get an error message. To address this problem, we need to modify the code by changing all the “int” to “float” as shown in Fig 10bii below. Note that the modified code will accept both integers and floats as input without raising any error. Try this out on your IDE
Fig 10bii
first_num = input("Enter the first number: ") second_num = input("Enter the second number: ") print(first_num + " x " + second_num + " = " + str(float(first_num)*float(second_num)))
Micro-Project - Build a Simple Calculator
We shall round this tutorial up with a micro-project to build a simple Calculator. Study and practice with the code in Fig 11i below to build your simple calculator. You can attempt to make modifications to the code and compare your output with that of the original code in Fig 11i
Fig 11i
first_num = input("Enter the first number: ") operator = input("Enter the operator: ") second_num = input("Enter the second number: ") if operator == "+": print(first_num + " + " + second_num + " = " + str(float(first_num)+float(second_num))) elif operator == "-": print(first_num + " - " + second_num + " = " + str(float(first_num)-float(second_num))) elif operator == "/": print(first_num + " / " + second_num + " = " + str(float(first_num)/float(second_num))) elif operator == "*": print(first_num + " x " + second_num + " = " + str(float(first_num)*float(second_num))) elif operator == "**": print(first_num + " raised to the power of " + second_num + " = " + str(float(first_num)**float(second_num))) else: print("Operator Not Valid!")
Conclusion
This is the end of Python Made Easy - Part One. We shall continue and go deeper into Python Programming in Part Two of this tutorial. Watch out for it.
Discussion about this post
No posts