Python 101: The Ultimate Python Tutorial For Beginners.

Python from scratch

Python 101: The Ultimate Python Tutorial For Beginners.

Python Fundamentals: All you should grasp as a beginner

  • Python as a programming language, programming techniques supported python programming language and its programming language category.

  • Python Hello World: Writing and Executing.

  • Comments, keywords, identifiers, and rules to follow when defining identifiers literals.

  • Variables, defining and using variables in the python programming language.

  • Operators in the python programming language.

  • Functions e.g built-in functions in the python programming language like print(" ")

  • Data Types in Python.

1. Python as a programming language: What is Python?

Python is a general-purpose programming language. Created in 1991 by Guido Van Rossum, who named it after the comedy series 'Monty Python'.
Python programs have the extension .py and can be run from the command line by typing the python filename.py

It is open source and has tons of libraries for various implementations, and can be used both as object-oriented and procedure-oriented language!

It is a high-level interpreted language, which is best suited for writing python scripts for automation and code reusability.

Python's outstanding characteristic is that it uses significant white space to delimit blocks of code, instead of the more popular {} symbols. Also, end-of-line semicolons (;) are optional and usually not used in Python.

Applications Of Python

  • Implementing artificial Intelligence

  • Developing desktop applications

  • Automation eg face recognition

  • Web Development -etc

Features Of Python

  • Simplicity: Its syntax is simple and English like to help one focus on the code more than the syntax.

  • Open Source: It is free for everyone to use and alter according to their needs.

  • Embeddable & Extensible: Python can have snippets of other languages inside it to perform certain functions!

  • Interpreted: The worries of large memory tasks and other heavy CPU tasks are taken care of by Python itself leaving you to worry only about coding.

  • Tons of libraries: Its rich libraries eg Numpy, Pandas etc are suitable for a wide scope of use, including Data Science, web development, and machine learning, just to mention a few.

Installing Python

Download the latest Python version here

Installing an IDE and setting up a Python environment

After installing Python, you will need an Integrated Development Environment to edit Python scripts.

vscode1-1.png

One of the best IDEs is Visual Studio Code where you will then set up the Python environment using this tutorial from Python tutorials.

2. Python Hello World

a) Writing the program

If you can write "Hello World" you can change the world.
-Raghu Venkatesh.

First, create a New folder where your work will be saved, say PythonProjects
Second, launch VS Code and open the folder you created by navigating using the Open folder in VS Code.
Third, create a new Python file, for example, FirstApp.py then enter the following code, then save by clicking on save or Ctrl + S keyboard shortcut.

print("Hello, World!")

The print() is a built-in function that displays a message on the screen as the output. In our case, it will show 'Hello, World!'

b) Executing the program

To execute the FirstApp.py file we created above, click on run and select run without debugging option. You will see a console with an output similar to the one below. Alternatively, launch the Command Prompt on Windows or Terminal on a macOS or Linux.
Then navigate to the folder containing the Python file, in our case the folder is PythonProjects.
After that, type the following command to execute the FirstApp.py file:

Python3  app.py

You’ll see the following message on the screen if everything is fine with your setup:

Hello, World!

3. Comments, keywords, identifiers, and rules to follow when defining identifiers and literals.

a) Comments
A comment is a text in a program's code, script or file, that is not meant to be seen by the user while running the program, or by the compiler while executing the program.
Comments explain the code and prevent portions of the code from being executed i.e commented piece of code cannot be executed while the program executes.

#This is a single line comment

'''
This is a multiline comment, using docstring
'''

NB: Use comments where appropriate, comments should not be overused.

b)Keywords
Keywords are the reserved words used to define the syntax and structure of the Python language. Keywords in Python are case sensitive, in that they are written in lowercase and used as they appear, except for False , True and None
Examples of keywords include if, else, class, for etc

c)Identifiers
An identifier is a name given to entities like variables, classes, functions etc, to help in differentiating one entity from another.

d) Literals
Literals in Python are defined as the raw data assigned to variables or constants while programming.
There are mainly have five types of literals which include string literals**, numeric literals, boolean literals, literal collections** and special literal.

e)Rules for writing identifiers

  1. Identifiers can be a combination of letters in lowercase, uppercase, or underscores. Eg var1, var_1, Var

  2. An identifier must not start with a digit.

  3. Keywords can not be used as identifiers.

  4. Special characters like "! @, #, %" etc cannot be used in an identifier.

  5. An identifier can be of any length and may be separated with underscores to enhance readability eg this_is_a_long_variable.

4. Variables: Defining and using variables in the python programming language

Variables are containers for storing data values. In Python, variables are not declared with any particular type, but they are created when a value is assigned to them. Eg

x = 5
y = "Reagan"
print(x)
print(y)

However, if you want to specify the data type of a variable, you can do so through a method called casting.

x = str(3)      # x will be '3'
y = int(3)      # y will be 3  
z = float(3)   # z will be 3.0

You can also assign multiple values to multiple values in one line:

x, y, z = "Liverpool", "Mancity", "Chelsea"  
print(x)
print(y)
print(z)

Assigning one value to multiple variables:

x = y = z = "Liverpool"  
print(x)
print(y)  
print(z)

5. Operators in the python programming language

Operators are used to perform operations on variables and values. Example include +

Arithmetic Operators: + , - , / , % , //

print(6 + 2)  # 8 (addition)
print(10 - 1)  # 9 (subtraction)
print(3 * 3)  # 9 (multiplication)
print(4 / 2)  # 2.0 (division)
print(2 ** 2)  # 4 (exponentiation)
print(11 % 2)  # 1 (remainder of the division)
print(11 // 2)  # 5 (floor division, whole number divisor)

Comparison Operators: ==, != , < , > , >= , <=

==  Equal to    2 == 2
!=  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

Logical Operators: and, or, not

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 not true(x < 5 and x < 10)

Conditionals: if, else, elif

grade = 88
if grade >= 70:
  print("Grade A ")  
 elif grade >= 60:
  print("Grade B ")  
 elif grade >=50:
  print("Grade C ")  
 elif grade >=40:
  print("Grade D ")  
else:
  print(" FAILED!")

6. Functions in Python

A function is a block of code that runs when it is called.
Functions are defined using the keyword def
Data can be passed into a function i.e they are specified in the parentheses of a function as arguments and may be separated with commas. Functions return data as the result.

def  my_function(greeting):  
   print("Hello, I am from Python")

Functions can be either inbuilt e.g print() or user-defined. User-defined functions are created by users for specific functions and given unique names/ identifiers.

7. Data Types in Python.

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
1) Numbers
These are numeric data types including int, float, complex
There is no need of specifying them as they are inferred by Python.

2) Lists
This is the same as an array in other programming languages. They contain any type of data inside them.
They are nested in [ ]

# store any type  
multiple_types = [ 1.2, False, "Python"

3) Tuples
Tuples are similar to lists, but they can not be modified i.e are immutable.
They are surrounded by ().

4) Dictionaries
Dictionaries are key-value pairs. They are surrounded by { }
The values are can have any data type. Eg:

language_creators = {
"Python" : "Guido van Rossum"  
"C"  : "Dennis Ritchie"  
"Java" : "James Gosling"  

 # access, modify, delete  
print(language_creators ["Python"])  #Guido van Rossum  
print(language_creators ["C"])  #Dennis Ritchie  
print(language_creators ["Java"])  #James Gosling

8. Control Structures

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 the while loop and for loops.

For Loop

  • It Iterates(repeats) 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

  • Keeps on executing 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 the moment i is equal to 3

Continue Statement

It is used to skip the execution of the current iteration and continues to the next line or blocks if statements.

i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)
#Continues to the next iteration if i  is 3

Pass Statement

The pass statement is used as a placeholder for future code.

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")
 pass


def myfunction():
  pass
#having an empty function definition like this, would raise an error without the pass statement

Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away.
– Antoine de Saint-Exupery


Congratulations, you are now ready for intermediate Python! See you there! Thanks a bunch for reading up to this very last period. Please consider throwing a thumbs up and leaving a comment on this article so that it is visible to many people.