What is Python?
Python is a general purpose ,dynamic, high level and Interpreted programming language created by Guido van Rossum. It was released in year 1991,since then, Python has been used widely thanks to the great features it offers.
Features provided by Python include:
- Python has a simple syntax similar to the English language.
- Python has a syntax that allows developers to write programs with fewer lines of code compared to other programming languages such as Java.
- Python works on different platforms (Windows, Mac, Linux) hence it's portable.
- Python supports multiple programming patterns such as object oriented, functional and procedural programming styles.
- Open Source: It is completely free to use python.
Applications of Python include:
- Web Development -used in development of websites using popular frameworks such as Django, Flask, FastApi.
- Game Development - used in development of interactive games using popular libraries such as pygame.
- Data Science and Data Visualization - Data can be manipulated, represented, analyzed and visualized using data libraries such as Matplotlib and Seaborn
- Graphical User Interface applications(GUI) - uses Tkinter to develop user interfaces.
- Machine Learning and Artificial Intelligence -With the help of libraries such as Pandas, Scikit-Learn, NumPy, computers get to learn algorithms based on the stored data.
- Embedded Applications -Python is based on C which means that it can be used to create Embedded C software for embedded applications such as Raspberry Pi.
How to install Python
Download the latest Python version here based on your operating system.
How to install Pycharm
Pycharm is a popular IDE(Integrated Development Environment) used for writing ,debugging and running python scripts.
Download Pycharm IDE to start coding.
How to install Visual Studio Code
Visual Studio Code is a Text-editor used to write and run python scripts. Download Visual Studio Code based on your Operating System.
You can read more about setting up a python environment using VS Code here.
Time to Code
Building your first Python Program
"Hello World"
Start your Pycharm IDE,select a new file and save it with the .py extension. Example hello.py.
NOTE: All Python files are named with the .py extension.
Write the following code in the hello.py file and click the run button.
print("Hello World")
Print() is an inbuilt function used to render outputs.
The following Output will be displayed:
Hello World
Variables
Variables are containers for storing data values.
Here's the syntax for assigning variables to data values.
variable name = data value
For example, planet = earth
Rules for Naming Variables
- A variable name must start with a letter or the underscore character.
- A variable name cannot start with a number.
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
- Variable names are case-sensitive (age, Age and AGE are three different variables).
NOTE:
Variables do not need to be declared. Their data types are inferred from their assignment statement, which makes Python a dynamically typed language. This means that different data types can be assigned to the same variable throughout the code.
Keywords
Keywords are special reserved words that have specific meanings and purposes .Examples of Keywords in Python include False, True, and, is, class, def, return, try, as ,pass, break, continue, for, while and except.
Identifiers
Identifiers are names used to identify variables, functions,
classes, modules or other objects. Identifiers start with letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9).
Literals
Literals in Python are defined as the raw data assigned to variables or constants while programming. We mainly have five types of literals which includes string literals, numeric literals, boolean literals, literal collections and a special literal.
Data Types
A Data Type is a classification that specifies which type of value a variable has and of what type. Examples of in-built data types include
Binary Types: memoryview, bytearray, bytes.
Boolean Type: bool.
Set Types: frozenset, set.
Mapping Type: dict.
Sequence Types: range, tuple, list.
Numeric Types: complex, float, int.
Text Type: str.
Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program .Generally comments enhance the readability of the code and help the programmers to understand the code very carefully.
Types of comments include:
- Single line comments
#This is a single line comment
- Multi-line comments
'''
This
is a multi-line
comment
'''
Operators
Operators are special symbols in python that carry out arithmetic and logical computation. The value that the operator operates on is called an Operand. Example
print(2+3)
# The output is 5
Here the addition (+) symbol is the operator while numbers 2 and 3 are the operands. The output of the operation is 5.
Types of Operators include
- Arithmetic Operators
print(46 + 2) # 48 (addition)
print(10 - 9) # 1 (subtraction)
print(3 * 3) # 9 (multiplication)
print(84 / 2) # 42.0 (division)
print(2 ** 8) # 256 (exponent)
print(11 % 2) # 1 (remainder of the division)
print(11 // 2) # 5 (floor division)
- Comparison Operators
== Equal to 2 == 3
!= Not equal 2 != 3
> Greater than 3 > 2
< Less than 2 < 3
=> Greater than or equal to x => y
<= Less than or equal to x<=y
- Assignment Operators
= x = 5 same as x = 5
+= x += 3 same as x = x + 3
-= x -= 3 same as x = x - 3
*= x *= 3 same as x = x * 3
/= x /= 3 same as x = x / 3
%= x %= 3 same as x = x % 3
//= x //= 3 same as x = x // 3
**= x **= 3 same as x = x ** 3
- Logical Operators
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
- Membership Operators
n Returns True if a sequence with the specified value is present in the object x in y
not in Returns True if a sequence with the specified value is not present in the object x not in y
Conditions and If Statements
Python statements such as if , elif and else display some messages depending on the conditions specified.
grade = 88
if grade >= 90:
print("Grade A ")
elif grade >= 80:
print("Grade B ")
elif grade >=70:
print("Grade C ")
elif grade >=60:
print("Grade D ")
else:
print(" Sorry, you have failed terribly!! Repeat the semester")
Loops
A Loop is a control flow statement that is used to repeatedly execute a group of statements as long as the condition is satisfied. Such a type of statement is also known as an iterative statement.
Python has two primitive loop commands which are while and
for loops.
- For Loop - It Iterates through the elements(list, tuple, dictionary, set, string)in the order that they appear.
names = ["alex", "james", "joy","sarah"]
for all_names in names:
print(all_names)
#Prints each name in the name list:
- While Loop - executes a set of statements as long as a condition is true.
i = 1
while i < 6:
print(i)
i += 1
#prints i as long as i is less than 6:
The Break Statement
It is used to exit a loop when an external condition is triggered.
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
#Exits the loop when i is equal to 3
Continue Statement
It is used to skip the execution of the current iteration and continues to the next.
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
#Continues to the next iteration if i is 3:
Pass Statement
When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed.
Empty code is not allowed in loops, function definitions, class definitions, or in if statements.
def info():
print("This function will get executed while the second function won't be executed")
info()
def myfunction():
pass
#having an empty function definition like this, would raise an error without the pass statement
Functions
A Function is a named section of a code that performs a specific task. This typically involves taking some input, manipulating the input and returning an output. You can pass data, known as arguments, into a function.
How to create a function in Python
Use the def keyword to define a function
example
def sum():
print(100+50)
#Calling the sum function
sum()
#The output is 150
Arguments and Parameters
Data can be passed to functions through parameters inform of arguments.
Parameters are specified after the function name, inside the parentheses and are separated with a comma.
An Argument is the actual data passed to the function.
def sum(a,b):
'''a and b are the parameters
sum is the function
def is used to define the function
'''
print(a+b)
#Calling the function
sum(10,50)
#10 and 50 are the arguments
#The output is 60
"In some ways, programming is like painting. You start with a blank canvas and certain basic raw materials. You use a combination of science, art, and craft to determine what to do with them." - Andrew Hunt.
Thanks for taking some time to read through this article, Stay tuned for more Python Concepts articles.
Top comments (3)
Great tutorial 🚀
Well written. Keep up the good job.
Thanks
Some comments have been hidden by the post's author - find out more