Photo by Chris Ried on Unsplash
Intro To Python Programming
An Introduction to Python programming for beginners
Hello and welcome to the latest blog in the Data Analysis, AI, Machine Learning and Everything In Between Series, today we will talk about python, how to install it, basic data types, conditionals & functions.
What Is Python?
Python is one of the most widely used programming languages. Guido van Rossum created it, and it was released in 1991.
Python is a dynamically semantic, interpreted, object-oriented high-level programming language. Its high-level built-in data structures, together with dynamic typing and dynamic binding, making it ideal for Rapid Application Development and as a scripting or glue language for connecting existing components.
Python's concise, easy-to-learn syntax prioritizes readability, which lowers software maintenance costs. Modules and packages are supported by Python, which fosters program modularity and code reuse. The Python interpreter and its substantial standard library are free to download and distribute in source or binary form for all major platforms.
Why is Python so well-liked?
Python is widely used for a variety of purposes. Here's a closer look at what makes it so flexible and user-friendly for programmers.
It features a straightforward syntax that resembles normal English, making it easier to read and comprehend. This speeds up the development of projects as well as the improvement of existing ones.
It's adaptable. Python can be used for a variety of purposes, including web development and machine learning.
It's user-friendly, making it popular among new programmers.
It's free to use and distribute, even for commercial purposes, because it's open source.
The Python module and library archive—bundles of code developed by third-party users to extend Python's capabilities—is large and growing.
Python has a vibrant community that contributes to the library of modules and libraries and serves as a resource for other programmers. Because of the large support network, finding a solution to a stumbling block is extremely simple; someone has almost certainly encountered the same issue before.
Install Python
There are various ways to install python, you can try to download it as a stand-alone from Python's Official Website or the most common way to install it with other Data science tools is through Anaconda
Anaconda is a Python and R programming language distribution aimed for simplifying package management and deployment in scientific computing (data science, machine learning applications, large-scale data processing, predictive analytics, and so on).
After you install Python you can run the following command to check that it was installed successfully:
python --version
Most Common IDEs
There are a lot of IDEs which we can use to write Python programs, but the most commonly used ones - Not in a particular order- are as follows:
*Note: Jupyter comes pre-installed with Anaconda *
Getting Started With Python
Python is an interpreted programming language, which means that you write Python (.py) files in a text editor before passing them to the Python interpreter to run.
On the command line, you can run a python script like follows:
C:\Users\your name>python helloworld.py
The name of your python file should be "helloworld.py."
Let's begin by writing our first Python file, helloworld.py, in any text editor or IDE:
print("Hello, From Amr's Tech Universe Blog!")
The output should read:
Hello, From Amr's Tech Universe Blog!
Indentation
Instead of curly braces, Python utilises indentation for blocks. Both tabs and spaces are supported, however normal Python code must utilize four spaces to be indented properly.
Variables & Types
Python is an object-oriented programming language that is not "statically typed." You don't need to define variables or their types before utilizing them. In Python, every variable is an object.
Commenting
Comments are used to explain our code for others reading our code or for us so we don't forget what is done here
You can comment codes like this:
# This is a single line comment
"""
This is a multiline comment
in Python
"""
Variables
Variables are storage containers for data values. You can't declare a variable in Python like in strongly-typed languages; a variable is only created when you initially assign a value to a it
For example lets say that you want to define a variabl;e and assign the number 1997 to it, you can do it like this: myVar = 1997
now lets say that you changed your mind and want to store it as a string or a float even, In other languages you would have to define a new variable and cast the existing one to match the new variable's data type, but in Python you can do it as follows:
myVar = 1997
# Casting myVar to float:
myVar = float(myVar)
print(myVar) # 1997.0
# Returning myVar to int:
myVar = int(myVar)
print(myVar) # 1997
# Casting myVar to string:
myvar = str(myVar)
print(myVar) # "1997"
Moreover, you can un-pack variable from a list, assign the same value to multiple variables and much more as we will show in the code example below:
# Multiple assignments
a, b, c = "Intro", "To", 'Python'
print(a) # "Intro"
print(b) # "To"
print(c) # "Python"
# one value to multiple variables assignment
a, b, c = "Intro To Python" # or 'Intro To Python'
print(a) # "Intro To Python"
print(b) # "Intro To Python"
print(c) # "Intro To Python"
# Unpacking lists
groupOfWords = ["Intro", "To", "Python"]
x, y, z = groupOfWords
print(x) # "Intro"
print(y) # "To"
print(z) # "Python"
As you have seen, the variables in python are dynamic and change their type based on the value assigned to them as variables are treated like objects.
However, there are a few aspects to consider:
Python is case-sensitive, so
MyVar
is different frommyVar
The name of a variable must begin with a letter or the underscore character
A number cannot be the first character in a variable name
String can be created with either
"
or'
, the only difference is with"
you can include apostrophesThe type() method can be used to return the data type of a variable
Built-in-Data Types
Data type is a crucial notion in programming. Variables can store a variety of data, and different types can perform different tasks. Python comes with the following data types pre-installed in these categories:
- Text Type:
str
- Numeric Types:
int
,float
,complex
- Sequence Types:
list
,tuple
,range
- Mapping Type:
dict
- Set Types:
set
,frozenset
- Boolean Type:
bool
- Binary Types:
bytes
,bytearray
,memoryview
Lists
As we have shown in the previous code example, arrays and lists are extremely similar. They can contain any sort of variable, as well as an unlimited number of variables. It is also possible to iterate across lists in a very simple method.
Lists are ordered, which means that any newly added items are inserted at the end by default. They can hold multiple data types at the same time and also allow duplicates.
Lets show some examples to better understand what was just saiud and explore some of Lists functionalities:
myList = ["Amr", 25.0, 1997]
# Accessing items in list
name= myList[0] # "Amr"
year= myList[-1] # Or myList[2] or myList[len(names) - 1]
print(myList) # ["Amr", 25.0, 1997]
# Add new items
myList.append("Hello") # Inserts at the end of List
myList.Insert(0, "New Item") # Inserts at the First position of the List
# Modify Items
myList[1] = "Second Item"
print(myList) # ["New Item" ,"Second Item", 25.0, 1997]
# Delete Items
myList.pop() # Removes the last item in List
myList.remove("Second Item")
print(myList) # ["New Item" , 25.0]
# List Looping
for item in myList:
print(item) # {0} -> "New Item", {1} -> 25.0
for i in range(len(myList)):
print(myList[i]) # {0} -> "New Item", {1} -> 25.0
List Comprehension
Whenever you want to create a new list based on the values of an existing list, list comprehension has a shorter syntax.
Taking the list from the past example and applying list comprehension on it:
"""
Instead of looping on all items by our selves to print them,
we can do something like this:
"""
[print(item) for item in myList] # {0} -> "New Item", {1} -> 25.0
Tuples
Tuples are a type of variable that allows you to store several elements in a single variable. A tuple is a collection of items that is both ordered and immutable.
Round brackets are used to write tuples. For example like GPS coordinates
egyptCoordinates = ("26.8206° N", "30.8025° E")
print(egyptCoordinates) # ('26.8206° N', '30.8025° E')
# Access Items
print(egyptCoordinates[0]) # '26.8206° N'
We stated that tuples are immutable, but there is a workaround that can be done. By casting the tuple to a list, it becomes mutable again and we can update its items then create a new tuple with the updated values.
myTuple = ("Intro", "To", "Python")
myList = list(myTuple)
myList[1] = 0.0
myList.append(5)
myTuple = tuple(myList)
print(myTuple) # ('Intro', 0.0, 'Python', 5)
If we want to assign all tuple values to variables as we did with lists, we can do as below:
# If number of variables is the same as items
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
# If number of variables doesn't match the items
fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")
(green, yellow, *red) = fruits
Note the use of *
before the variable red
, It is used to assign the excess items to the latest variable in the form of a list.
Dictionaries
Dictionaries are used to store data values in key:value pairs, they are mutable and don't allow duplicates in keys.
We will explore how to create, modify & delete dictionaries in the code example below:
person = {
"name": "Amr Khaled",
"gender": "Male",
"age": 25.0,
"occupation":{
"company": "CIT VeriCash",
"position": "Software Engineer"}
}
# Access Values
print(person["occupation"]) # {'company': 'CIT VeriCash', 'position': 'Software Engineer'}
The process of adding or modifying dictionaries is practically the same. If a key exists then it will be added, but if it is found then its value is updated
# Adding a new Key-Value Pair
person["hasCar"] = True
print(person) # {'name': 'Amr Khaled', 'gender': 'Male', 'age': 25.0, 'occupation': {'company': 'CIT VeriCash', 'position': 'Software Engineer'}, 'hasCar': True}
# Modifying a new Key-Value Pair
person["hasCar"] = False
print(person) # {'name': 'Amr Khaled', 'gender': 'Male', 'age': 25.0, 'occupation': {'company': 'CIT VeriCash', 'position': 'Software Engineer'}, 'hasCar': False}
Loops & Conditionals
Loops come in a variety of forms, and they're used to iterate over data and apply logic before moving on to the next item or returning a specific item.
They are often used in conjunction with logical conditionals and if ... else
statements, that we will discuss shortly
For Loops
# Loop over a string
for x in "banana":
print(x) # {0} -> 'b', {1} -> 'a', ......, {5} ->'a'
# Loop over a list
for x in ["Intro", "To", "Python"]
print(x) # {0} -> 'Intro', {1} -> 'To', {2} -> 'Python'
# Loop over a range
for x in range(20):
print(x) # {0} -> 0, {1} -> 1, ......, {19} -> 19
# Using Break statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break # used to stop the for loop and resume the code execution
# Using Continue Statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue # Skip the rest of the code in this iteration of loop and start with the next index
While Loops
We can use the while loop to run a series of statements as long as a condition is true.
# Print all numbers less than x
x = 100
i = 0
while i < x:
print(i)
i += 1
else:
print("i = x")
If Statements
Assume that we are at a party and we are responsible for handling door access, we have to set some ground rules as to who will we allow to our party, maybe we want people to be above 21 or if they are on the invitation list, then we can allow them to enter, but how do we translate that to python code? Lets see, shall we?
minimumAge = 21
invitedPeopleList = ["Amr", "Maryam", "Anas", "Habiba", "Merna", "Nada", "Ayman", "May"]
person = {"name": "Ahmed", "age": 19}
isAllowedEntry = False # Initially everyone is denied entry
if person["name"] in invitedPeopleList or person["age"] >= minimumAge:
isAllowedEntry = True
else:
isAllowedEntry = False
*Note: The else
statement above is redundant but was included for clarification purposes *
Functions
A function is a piece of code that only runs when it is invoked. It accepts data in the form of parameters and as a result of its operation, a function can return data in the form of one variable or more.
If we want to create a function that takes two integers as input and outputs a bunch of arithmetic operations - sum, multiplication, difference, reminder & power -
We can group all of those operations into a function and implement it as follows:
def getArithmeticOperations(x, y):
sum = x+y
diff = x-y
multi = x*y
power=x**y
rem = x%y
return sum, diff, multi, power, rem
a = 10
b = 2
sum, diff, multi, power, rem = getArithmeticOperations(a,b)
print(sum) # 12
print(diff) # 8
print(multi) # 20
print(power) # 100
print(rem) # 0
Wow! that was a lot. If you are still feeling fuzzy or don't know how to memorize all of this new information, it is perfectly okay.
Remember that Rome, was not built in a day and that practice makes perfect. Try and familiarize yourself with more python syntax and problems and you will surely be on your way!
In this tutorial, I tried to give you the basics that I wished someone had told me about when I started my coding journey, this is just an introduction so you and I still have a long way to go together. But we all have to start somewhere.
Thank you so much for reading, hope you enjoyed it as much as I enjoyed writing it! See you soon with more blogs & tutorials in our Data Analysis, AI, Machine Learning and Everything In Between Series