Introduction to Python Programming Language.
What is Python?
Python is a highly programming language which is:
Open source and community driven: Python is free for everyone to access and use and you have the ability to change the source code to fit your needs
Dynamically typed and interactive: You type Python prompts and directly interacting with the interpreter when writing your programs.*
Object oriented: Python supports Object Orienting method of programming.
Interpreted: Python is compiled and processed at runtime by the interpreter
A Beginner's Choice: Python is easy to learn, read, maintain source code and supports the development of a wide range of programs.
Key Points to Note:
- When writing a python program code you have to use the .py extension at the end of your file name for the program to run for instance app.py
- It is not necessary to define the type of variable in python and also you don't need to add a semicolon at the end of the statement.
- Python uses new lines to complete and run a command, uses whitespace to define scope for example scope of loops, functions and classes. It largely relies on indentation.
History of Python.
In the late 1970s, a programming language called ABC which is a general-purpose programming language is developed at CWI in the Netherlands, Armsterdam.
In the 1980s, Guido Van Rossum joins the ABC team and in the late 1980s he conceptualizes Python.
In 1991, Guido Van Rossum published the first version on Python(0.9.0) at CWI in the Netherlands, Armsterdam.
Guido Van Rossum liked Monty Python Flying Circus and thats why he choose to name the previously developed ABC programming language to Python.
Why Python Programming Language For Beginners?
- Python has simple structure, clearly defined syntax and a few keywords therefore allows for beginners to understand it quickly.
x=4 ; y=8 # Declaring two integers
z= y - x # Subtracting two integers
print(subtract) # Displaying the output
Python written programs can run on a variety of platforms including LINUX, Windows and Mac OS.
Python provides a better structure and support for large programs then shell scripting.
Python has a well, clear and simple syntax with very few lines compared to other programming languages.
colors =[red, orange, yellow, green, blue, indigo, violet]
print(colors)
Python support OOP technique of programming therefore you can end up treating it either procedurally or functionally.
Python programs are executable as soon as the program is written meaning it facilitate fast prototyping it is run on an interpreter system.
Important Uses of Python.
Software development and SAAS products: Technology and Software-driven companies use Python for software building and other SaaS products creation.
Mobile Web Creations: Developers use Python to build customer and enterprise mobile app for customer engagement and workforce productivity.
Database access and management: Python is used by many companies to access, connect, read and modify files in the company's database system.
Data Analysis, Data Visualizations and Data Wrangling: Python helps companies to leverage cloud platforms for building solution since it has the ability to handle big data and perform complex mathematics
AI and Automation: With the fast growing AI usage by many companies, Python has been used significant tool in building AI models and variables by a number of companies.
Desktop GUI Applications: Python has been used by organizations to build desktop apps to capture and monitor results from several connected devices.
Education: Software Developer, Data Engineers, Data Scientist and others have learned python as part of their career.
Network programming and IoT solutions.
Python Features
Easy to Learn and Write
Python has a clear syntax with simple structures and fewer lines thus enables you to focus and think of the code mostly.
Portable
You can run Python on a wide range of hardware platforms and has the same interface on all the platforms.
Extendable and Embeddable
You can add and combine other low modules to the Python Interpreter. The modules enables programmers to add to or customize their tools to be more effective as well as efficient at the same time.
Interactive Mode
Since Python supports an interactive mode, You can interact with the interpreter while write your code and also debug the snippets of your code.
A Broad Standard Library and Large Community
Python has many build-it libraries and is compatible with other cross-platforms like UNIX, Windows and Mac OS therefore accessible in any part of the world and you don't have to code everything by yourself.
Databases
Python provides interface to all major commercial databases and you can be able to read, interpret and modify your database using python programs.
GUI Programming
Python supports GUI apps that can be created and ported to many system calls, libraries and windows systems such as Macintosh and Windows MFS.
HOW DO WE INSTALL PYTHON ON YOUR DEVICE?
Once your device is open and set with internet working properly, Click Here and depending on your Operating System of your device then Go and
Select 1 if you are using Windows, Select 2 if you are using Mac OS, Select 3 if you are using UNIX/LINUX and finally Select Others4 if you are using a different OS than the other three mentioned above.
After clicking on the above links and choosing the correct link as per your Operating System, On the same page of that link select the type of version/release you want and click on it for the downloading process to begin.
Once the Installer file has been downloaded, double click on the installer file on your Downloads Folder to run and the installer file and install.
NOTE:
Always ensure you have set up the path of the system variable to allow for easier and swift execution of the python file plus the appropriate environment storage variable is set correct For more information click To Read More on PATH VARIABLE Set-up
*You can install Integrated Development Environment (IDEs) on your device or language programming interpreters like VS Code, Sublime text or even Notepad++ where you can run and execute your Python programs. PyCharm,
JupyterNoteBook, Spyder, Visual Studio, Google Collab
How Do We Confirm Whether Python is Fully Installed in You Device?
1.Windows User
On your device search box next to the START Menu type and search in cmd for Command Prompt then run this command line:
C:\User\Zawadi python --version
2.Mac OS User
On your Mac device open up the terminal and type:
python --version
3.UNIX/LINUX
While on Unix or Linux open your terminal and type the command:
Zawadi@Ubuntu python --version
If you receive back a feedback say 'Python is Not Found' after typing the above command then that implies that Python has not been install in your device, so what you do click HERE again to download and access it on your device.
Once you run the above command line and obtain the following output:
C:\User\Zawadi python --version
Python 3.11.2
C:\User\Zawadi
that means Python has now been installed in your device.
Our First Python Code.
Once python is now installed on your device you can now start to write your own python programs on your device.
You can start with a simple python program named myprogram_one that gives the following output: How are you feeling Today?
Go on your favorite IDE or text editor and save it as myprogram_one.py
print(How are you feeling Today?) # First Print Statement
print(Awesome) # Second Print Statement
Then run the file which will produce the output:
How are you feeling Today? # First declared output
Awesome # Second declared output
Python Keywords and Identifiers.
Keywords in Python
Python keywords are predefined reserved words that have a special meaning to the interpreter or compiler.
They can never be assigned to identifiers.
Some example of keywords include def, class, while, if, else, true, lambda, nonlocal, false e.t.c
Python Identifiers
Python identifiers are names used to identify variables, functions, classes, modules or other objects.
You must never assign Python keywords as the name of your identifiers.
NB:
- Identifiers start with A to Z or a to z or an underscore(_) followed by letters or digits from 0 to 9 example Fullname, fullname, full_name, data_34 or _file1
- Python is case sensitive meaning that Birthdate and birthdate are two separate identifiers one starting with upper case while the other one starts with a lower case.
- In Python, Identifiers must never be keywords because the interpreter already knows Python keywords and using them as identifiers can lead to syntax errors
- Python does allow the use of special characters thus your identifers must not have space characters for instance &Age, day-1, year%100, @my.net
Literals in Python
Literals are data or constant values stored in variables.
In Python, when you assign a constant value 10 to a variable 'a' the value is stored in 'a'. 10 which is an integer value is called Integer Literal
Python supports the following literals
Numeric Literals
They comprise of int (integer):10 , long (long integer)314215869, float(floating integer):-22.7 and complex(complex numbers):3.142jString Literals
is formed by enclosing a text with a single or double quotes '' "" example "Tap" , '123456'
text1 = "Hello" # single line string
text2 = 'Hello\ # multi line string
Team'
text3 = '''How do you #string with triple quotation marks
do
today?'''
Boolean Literals
They are True or false.Special Literals
Python has only on special literal, None which you can use to specify when the field is not created and also use it at the end of lists.
Python Statements and Comments.
A Python statement instructs the python interpreter to run or execute a given program. They include: if while and for statements Where you want to use various statement in your program then always use brackets[], braces{} or parentheses() and suppose you want to get two or more statement from a single line statement you use a semi-colon.
if statement
age = int(input(enter your age)) # input age
print("Your age is", age)
if age > 18 # checking eligibility
print(You can take part in voting process)
else:
print(You cannot take part in voting process)
while statement
a = 20
b = 15
while a > 0 and b > 0 :
a -= 3
b -= 2
print{(a , b)}
for statement
for value in range(1,10)
print(value)
print(Today is my birthdate)
Python Indentation
Indentation refers to the spaces at the beginning of the code line. In Python, Indentation is something you use to define a block of codes take for instance a simple
if statement
x=4
y=8
if y > x : # statement ends with colon
x = 8 # whitespace showing indentation
y = 16
print(sum(x , y))
In this statement it ends with a colon and whitespace is used (indentation) to describe what takes place in the case of a statement. In Python the end of a line is the same as the end of a statement. Also it is important for you to remember when you are using indentation be keen and consistent throughout your code to avoid getting syntax error.
Python Comment
Gives an explanation and description of a certain python code. You use the # symbol at the start of the statement to denote a comment. You can place it at the start after the code in the same line or at the end of the line Python will still ignore both of them while executing the program.
#This is a comment
print(Dear Team) # This is a comment
Dear Team # output
A Comment is not only supposed to give the explanation of the code but also can be used to prevent the python code from executing.
#print(What is my name?) # Ignores this line declared
print(My name is John Doe) # declared statement to be executed
My name is John Doe # output from the declared statement
For multiple comments, you either use # symbol on each line or triple quote ''' / """ which is a multi-line string
'''This is an example of a
set created by a team in
Juxpoints.edu.ac.uk'''
set4 = (python, java, react, ruby, perl, kotlin)
print(len(set4))
#This is one type of a
#multi-line comment that
#goes to the next page
print(I love to code everyday.)
Python Variables
Variables are nothing more than reserved memory location to store value which means that when you create a variable reserve some space in memory.
Based on the data type of the variable, the compiler allocates memory and decides what can be stored in the reserved memory thus by assigning different data types to variable you are able to store integer, decimals and character in these variable.
The declaration of python happens automatically when you assign a value to a variable using the equal sign = which assigns value to the variable.
The operand to the left is the name of the variable whereas the operand to the right is the value stored in the variable
age = 45
distance = 11.11
name = "Zawadi"
print(age)
print(distance)
print(name)
In the above example, 45, 11.11 and "Zawadi" are values assigned to age, distance and name variables respectively.
With python you can assign a single value to several variable simultaneously as well as as multiple objects to multiple values.
y = m = c = 10
print(y)
print(m)
print(c)
y, m, c = 2, 3.14, "Shakti"
print(y)
print(m)
print(c)
Python Operators
Operators in Python allows for the processing of variables and value. Two or more numerical values can be added subtracted, multiplied or divided to give out a new output
Python supports the following operators:
- Arithmetic Operators In python, you perform your mathematical operations using + (addition) , - (subtraction), // (quotient), / (division), %(modulus) and so forth and so on. for example:
a = 9
b = 27
print(a + b) # Addition
print(a - b) # Subtraction
print(a * b) # Multiplication
print(a / b) # Division
print(a % b) # Modulus
print(a // b) # Quotient
print(a ** b) # Exponent
- Assignment Operators You assign values or content of the variable to the variable using assignment operators.
m = 7 # assigning value to m
c = m # assigning value of m to c
y = m + c - 3 # execute the expression and find value of y
print(m)
print(c)
print(y)
m += 7
c -= 7
y *= 7
print(m)
print(c)
print(y)
m /= 4
c %= 4
y //= 4
print(m)
print(c)
print(y)
- Comparison Operators In Python, you can compare the value of two variables and the result is a Boolean value either true or false.
p = 12
v = 18
print(p == v) # if p and v are equal then output is true
print(p != v) # if p and v are not equal then output is true
print(p > v) # if p is greater than v then output is true
print(p < v) # if p is less than v then output is true
print(p >= v) # if p is greater than or equal then output is true
print(p <= v) # if p is less than or equal then output is true
- Relational or Logical Operators You can combine two or more comparison operations using Logical or Relational Operators and the output value is a Boolean value i.e True or False
x = 2
y = 4
print(x > 3 and y < 5) # if both conditions are true output is true
print(x > 2 and y < 6) # if both conditions are true output is true
- Membership Operators Python's membership operator tests for membership in a sequence such as strings, lists or tuples.
fruits = [apple, mango, banana, orange, guava]
print("tunip" not in fruits)
#output is true since in the sequence with value "tunip" is not in the list
- Identity Operators Identity operators are used to check if the location or address of two variables is the same or not.
a1 = 3
b1 = 3
a2 = 4
b2 = 5
a3 = [10, 3.14, "Zawadi"]
b3 = [10, 3.14, "Zawadi"]
print(a1 is not b1) # output is false
print(a2 is b2) # output is false
print(a3 is b3) # output is true
- Bitwise Operators In Python you can use Bitwise operators to perform a bit by bit operation among given operands.
z1 = 4
z2 = 5
print(~z1)
print(z1 in z2 =', z1 & z2)
print(z1 ^ z2)
print(z1 | z2)
print(z1 << z2)
print(z1 >> z2)
Python Data Types
Data Types in Python include:
Numeric type(numbers)
integer(int) i.e 10, 8 ,6
float i.e 3.14, 37.5
complex numbers i.e 12 + 20j, 13 +30iDictionary
{'x': 4, 'y' : 8}Boolean
True or FalseSequence type i.e
string e.g
list e.g ["Zawadi", 24, Korea", 6.4]
*tuple*e.g((a, b, c) ,10 ,3.147j)Set
{"Hello World", 12345, (x, y, z)}
Python Loops
In a loop, statement are executed following the sequence the code is written the first statement of the function is executed first then followed by the second statement then third statement and so on.
1.For Loop
In Python, For loop is the simplest form of repetition. A For Loop repeats a group of statement a specified number of times.
cars = ["BMW", "Rolls Royce", "Toyota", "Tesla", "Honda"]
for i in cars:
print(i)
You can loop in string because a string has sequence of characters.
for x in "Demitrius":
print(x.capitalize())
You can introduce Else Statement in your For Loops but it is optional and that Else part is executed by the interpreter once it has run all the elements in the sequence.
for i in range(7):
print(i)
else:
print('The range ends here')
In Python, For Loops allows Continue Statement in its structure which you can use to stop the current iteration of the loop, and go to the next:
r = trolls
for x in r:
if x == 'n':
continue
print(x)
2.Nested Loops
Nested loops are loops found inside another loops.
What the interpreter does when a nested loop program is run is it executes the Inner Loop first and it is executed one time for each iteration of the Outer Loop
names = ["Bingo", "Zawadi", "Dalton"]
scores = ["50", "75", "68"]
for a in names:
for b in scores:
print(a , b)
3.While Loop
While Loops are similar to If statement in that the code is executed when the condition or expression is true, the only difference between the two is that While Loop continue to execute the code repeatedly as long as the condition is true as opposed to if statement.
a = 4
while a < 12:
a += 1
print(a)
You can add an else block on your while loop which is going to be executed if the condition is false or all the conditions have been met.
count = 7
while count > 0:
print(Hello Python)
else:
print(End of cycle)
In Python you can also use break statement to stop the while loop even if the condition is true and continue statement to skip the current iteration and continue with the next.
y = 1
while y < 8:
if y == 6:
break
print(y)
y = 1
while y < 8:
y += 1
if y == 4:
continue
print(y)
Python Conditional Statements
These statements are based on if statement that executes the code after check if the condition is satisfied or the given expression is true
passmark = 78
if passmark < 45
print("Student failed the test, try again.")
# Output Student failed the test, try again since the expression is true
In the above example if the condition was not satisfied i.e false then you will not get an output.
In the If Else statement if the condition is false the interpreter will move to the next code line.
user = input('Enter your username')
password = input('Enter your password')
if user == 'Zawadi' :
print('Welcome' , user)
else:
print('incorrect username')
age = 35
if age == 35 :
print('Adult')
else:
print('Teenager')
In the Else If statement the interpreter runs on multiple conditions:
a = 4
if a == 1:
print('One')
elif a == 2:
print('Two')
elif a == 3:
print('Three')
elif a == 4:
print('Four')
else:
print('Out of range')
- In the next article We will be continuing with Introduction to Data Structures in Python such as Lists, Tuples, Dictionaries, Sets, Stacks, Queues as we know Data plays a critical role in Web Development, Machine Learning Artificial Intelligence and Automation. STAY TUNED!!!
Top comments (0)