DEV Community

Cover image for Python 101: Ultimate Python Guide
Owino
Owino

Posted on

Python 101: Ultimate Python Guide

Working in Cloud Orchestration, automation skills are vital; python lends a hand to this. Python is easy to learn!

What is Python?
Python is a high-level programming language. It can be used in scripting/automation, Artificial Intelligence(AI), Machine language (ML), Data Science, APIs and web development.

My Programming environment and setup
As I share this, below find my setup and programming environment:

Follow me along as I take you through an exciting journey needed to keep you up and running in Python. Feel free to type the code as we get along. I will try to will make it as simple as possible!

Overview of Python
Variables and Datatypes, Comments in Python, How to get input from users, Operators, Data structures (lists, tuples and dictionaries), functions and control flow.

1. Variables and Datatypes
Python supports the following data types:

  • Strings
  • Numbers
  • Boolean

The below example shows how to use these three variables in Python. My file is saved as variables_and_datatypes.py in Visual studio code.

#Lets declare three variables names firstName, age and isMale all of different data type.
firstName = 'Mel' 
age = 10
isFemale = True

print(firstName) #This will print out Mel
print(age)       #This Will print out 10
print(isFemale)  #This will print out True
Enter fullscreen mode Exit fullscreen mode

2. Comments in Python
It is very important to comment your line(s) of code as it helps others understand your code.
Moreover this helps you incase you come back to that section to see what you did days, months or even years later since it is easy to forget what your did days back.
You can use single line comment using # or multi-line comments by having text between a block of ''' ''' . See below example:


'''
This is my first program.
Python is a high-level programming language.
Here am using multi-line comment style.
'''

#This prints out strings to the user. Here I have used single line comment.
print('Python programming is fun!')
Enter fullscreen mode Exit fullscreen mode

3. Getting input from users
Incase you need your program to get inputs from users, you need to use python input function. See below example on how this function is used.

'''
Here we are using input function to get name of the user and 
store in a variable named firstName'''
firstName = input("Enter your name: ")

'''
In this case are converting string input to an integer.
By default all inputs in Python are treated as strings so we have to convert them to our desired data type; in this case an integer.
'''

age = int(input("Enter your age: "))

#Here we concatenate(link together) the strings using f-string during printing to make a meaningful sentence.
print(f"Your name is: {firstName} and your {age}")
Enter fullscreen mode Exit fullscreen mode

Below is what I will get if I run my python file named input.py:

Enter your name: Mel
Enter your age: 10
Your name is: Mel and your 10
Enter fullscreen mode Exit fullscreen mode

4. Python Operators: Let's build a basic calculator
To perform mathematical operations in python, we use the following operators: + (for addition), - (for subtraction), * (for multiplication), ** (for exponentials) / (for division), % (for modulus), / (for division) and // (for quotient.
See below code snipped for the example of our simple calculator:

firstNumber = float(input("Enter the FIRST number: "))
secondNumber = float(input("Enter the SECOND number: "))

sum = firstNumber + secondNumber
print(f"The sum of {firstNumber} and {secondNumber} is {sum}")

multiplication = firstNumber * secondNumber
print(f"The product of {firstNumber} and {secondNumber} is {multiplication}")

exponential = firstNumber ** secondNumber
print(f"{firstNumber} raised to the power of {secondNumber} is {exponential}")

division = firstNumber / secondNumber
print(f"The Division of {firstNumber} by {secondNumber} is {division}")

subtraction = firstNumber - secondNumber
print(f"The Subtraction of {secondNumber} from {firstNumber} is {subtraction}")

modulus = firstNumber % secondNumber
print(f"The Modulus of {secondNumber} and {firstNumber} is {modulus}")

quotient = firstNumber // secondNumber
print(f"The quotient of {firstNumber} and {secondNumber} is {quotient}")
Enter fullscreen mode Exit fullscreen mode

See the below output when we run our Python file named calculator.py:

Enter the FIRST number: 4
Enter the SECOND number: 2
The sum of 4.0 and 2.0 is 6.0
The product of 4.0 and 2.0 is 8.0
4.0 raised to the power of 2.0 is 16.0
The Division of 4.0 by 2.0 is 2.0
The Subtraction of 2.0 from 4.0 is 2.0
The Modulus of 2.0 and 4.0 is 0.0
The quotient of 4.0 and 2.0 is 2.0
Enter fullscreen mode Exit fullscreen mode

5. Data structures in Python
You also need to understand the key data structures in Python. These are Lists, Tuples and Dictionaries. Let's go through each one:

5.1 Lists

Lists in python is in other terms what other programming languages call arrays. Lists are mutable i.e. their elements can be changed, removed, new ones added etc. The elements in a list are enclosed in square "[]" brackets. see below examples:
Here we declare a list named myFriends and use it.

myFriends = ["Mike", "John", "Peter", "Lenny", "Peter"]
print(myFriends)
Enter fullscreen mode Exit fullscreen mode

When we run our python program it will print out the below:

['Mike', 'John', 'Peter', 'Lenny', 'Peter']
Enter fullscreen mode Exit fullscreen mode

To count all my friends called 'Peter':

print(myFriends.count("Peter"))
Enter fullscreen mode Exit fullscreen mode

Output:

2
Enter fullscreen mode Exit fullscreen mode

Let's insert a friend to the list at index 1 of the list and print the list again:

print(myFriends.insert(1,"Arnold"))
print(myFriends
Enter fullscreen mode Exit fullscreen mode

output:

['Mike', 'Arnold', 'John', 'Peter', 'Lenny', 'Peter']
Enter fullscreen mode Exit fullscreen mode

Let's remove Friend 'Lenny' from the list and print the list once more:

print(myFriends.remove("Lenny"))
print(myFriends)
Enter fullscreen mode Exit fullscreen mode

Output:

['Mike', 'Arnold', 'John', 'Peter', 'Peter']
Enter fullscreen mode Exit fullscreen mode

Feel free to try out other list functions available in Python such as: clear(), copy(), extend(), index(), pop(), reverse() and sort().

5.2 Tuples
Tuples are similar to list but their contents cannot be changed; they are immutable.
The elements in a tuple are enclosed in round brackets "()".
See below example with our tuple named daysOfTheWeek.

daysOfTheWeek = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
print(daysOfTheWeek)
Enter fullscreen mode Exit fullscreen mode

The output when we run above:

('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday')
Enter fullscreen mode Exit fullscreen mode

To print the third element of the tuple:

print(daysOfTheWeek[3])
Enter fullscreen mode Exit fullscreen mode

Output:

Wednesday
Enter fullscreen mode Exit fullscreen mode

If we try to change any element of the tuple e.g. assigning a new value to element at index 1:

daysOfTheWeek[1] = "Friday"
Enter fullscreen mode Exit fullscreen mode

Python will throw the following TypeError since elements in a tuple cannot be changed (tuples are immutable):

TypeError: 'tuple' object does not support item assignment
Enter fullscreen mode Exit fullscreen mode

5.3 Dictionaries
Dictionaries are used to store data in key:value format.
See below code:

student = {
    "firstName" : "Mark",
    "Age" : 23,
    "Hobby" : "Soccer"
}
print(student)
Enter fullscreen mode Exit fullscreen mode

The output will be:

{'firstName': 'Mark', 'Age': 23, 'Hobby': 'Soccer'}
Enter fullscreen mode Exit fullscreen mode

To print out the value of key Hobby in the student dictionary:

print(student["Hobby"])
#also the below code will do the same
print(student.get("Hobby"))
Enter fullscreen mode Exit fullscreen mode

Output:

Soccer
Enter fullscreen mode Exit fullscreen mode

6. Functions
A function is a set of code which execute a particular logic in your program. For example you could be having multiple lines of code which are geared to perform a certain function in you program. To make it easier to maintain your program and also to call/refer that particular block of code in your program, you need to implement functions. Functions help to decompose a program (modular programming).
Functions in Python are declared using key word def. Lets explore a simple example of a function in Python. Please take note of the comments in the program:

def getUserInputs():
    #Here we are making sure that these variables are scoped even outside the function.
    global firstName, lastName, age  

    firstName = input("Enter your first name: ")
    lastName = input("Enter your last name: ")
    age = int(input("Enter your age: "))

#Now we are calling the function in our program.
getUserInputs()

print(f"Your name is {firstName} {lastName} and you are {age} years old")
Enter fullscreen mode Exit fullscreen mode

The output with test inputs will yield the below:

Enter your first name: James
Enter your last name: Michael
Enter your age: 23
Your name is James Michael and you are 23 years old
Enter fullscreen mode Exit fullscreen mode

7. Control Flow
Python supports the following logical conditions(operators):

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

These logical operators are used in various flow control mechanisms in Python. Let's use them in below cases:

7.1 If...else statements
For If statements, if the condition at the logical check is True, only that block of code gets executed. Lets see below code:

x = 4
y = 42

if x > y:
    print(f"{x} is greater than {y}")
elif x < 42:
    print(f"({x} is less than  {y})")
else:
    print(f"{x} is equal to {y}")
Enter fullscreen mode Exit fullscreen mode

The output is:

(4 is less than  42)
Enter fullscreen mode Exit fullscreen mode

7.2 While loop
For while loop, a block of code will continue to be executed as long as the condition remains True. For example the values printed will 0, 1, 2, 3, 4 and 5. It will stop there since 6 will not satisfy the condition; it will be False.

i = 0 #Here we have initialized our variable i to value 0.

while i <= 5:
    print(i)
    i = i + 1 # Here we are incrementing our value of i by 1 each time.
Enter fullscreen mode Exit fullscreen mode

Output when we run the above program will be:

0
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

7.3 For loop
For loop is nice for iterating through a list, tuple or dictionary. see below example:

myFriends = ["Mike", "John", "Peter", "Lenny", "Peter"]

for name in myFriends:
    print(name)
Enter fullscreen mode Exit fullscreen mode

The output will be:

Mike
John
Peter
Lenny
Peter
Enter fullscreen mode Exit fullscreen mode

8. Let's improve our calculator
Now lets improve our calculator. We will use most of the concepts we have learned so far including functions and control flow.
See below code:

firstNumber = input("Enter the first number: ")
operator = input("Enter the operator ('+,*,-,/ or %) you want to use: ")
secondNumber = input("Enter the second number: ")

def calc(firstNumber, operator, secondNumber):
    if operator == "+":
       return (float(firstNumber) + float(secondNumber))
    elif operator == "*":
       return (float(firstNumber) * float(secondNumber))
    elif operator == "-":
       return (float(firstNumber) - float(secondNumber))
    elif operator == "/":
       return (float(firstNumber) / float(secondNumber))
    elif operator == "%":
       return (float(firstNumber) % float(secondNumber))   
    else:
       return print("Invalid operator")  

result = calc(firstNumber, operator, secondNumber)

print(f"{firstNumber} {operator} {secondNumber} equals {result}")
Enter fullscreen mode Exit fullscreen mode

9. Let's put all we have learn in practice: Fibanocci sequence numbers!
Now to spice things up let's try to explore Fibanocci sequence numbers.
The Fibonacci sequence is the series of numbers where each number is the sum of the two preceding numbers. For example, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 etc.
I created a program to check if a number is a Fibanocci number.
Please check it out on my github: https://github.com/emwadun/fibanocciCheck

What's next on my mind?
In this blog post, I have tried to keep it as simple as possible to address only the core concepts. Please feel free to review, comment and share some feedback.

On my next blog post I will explore the following aspects in Python:
[x] Reading files
[x] Writing to files
[x] Modules and PIP
[x] Classes and Objects
[x] Object Functions
[x] Inheritance


Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
techbytes profile image
Tech Bytes

Really informative article on python. Covered the essentials really well. I am learning it at the moment. Looking forward to the next article.

Collapse
 
owino profile image
Owino

Awesome feedback @itswachira! Thanks for the checking it out. You will hear more soon.