DEV Community

Cover image for Python 101 : Introduction To Python
Nyareki Gospel
Nyareki Gospel

Posted on

Python 101 : Introduction To Python

You might be wondering; "why would the inventor of Python name it after a snake?". That bothered me too when I was starting out. Well inventor Guido Van Rossum named his programming language after his favourite British Comedy series, "Monty Python's Flying Circus" and not a snake. He gave it this name because Python is a mysterious, short and unique language. Python is a high-level, general-purpose programming language with dynamic semantics released by Guido Van Rossum in the year 1991 after he had developed it .
Here is why you should learn python today:

  • Python is easy to read and can be read quite like English because it employs least verbosity. This makes it easy to learn too.

  • Python has user friendly data structures that add up to its simplicity, increasing it's productivity.

  • Python comes with an extensive library. It's code can be used for various purposes for example, in regular expressions, databases, emails and even image manipulation.

  • The extensibility of python is useful in projects. This means it can be written in other languages like C or C++.

  • Python opens up opportunities for Internet Of Things due to it's heavy featuring in platforms such as Raspberry Pi.

Real World Application Of Python

Python has grown and proven useful since it's birth allowing it's usage in various ways.

  1. Computer Aided Design Applications- These are applications that allow their users create 2D and 3D models digitaly. Python has been employed in the development of these applications for example Blender.
  2. Web Development- With it's wide range of frameworks, Python has been heavily used in the development of websites making the process almost effortless.
  3. Data Science- This field deals with the collection analysis and visualisation of data. Here, Python simplifies the complexity using tools like TensorFlow and Pandas.
  4. Game Development- As games have grown popular, the development of games using python has also grown resulting in it's use in development of games like Battlefield 3 and Pacman.
  5. Software Development- Python's Platform Independence and High Compatibility made it an ideal software development Language.

How Do I Install Python?

Well there is a wide range of ways to do this. The method I find simplest (for Windows Users) is Installing Python from the Microsoft store then in the code editor Visual Studio Code, write you Python program and run it From Visual Studio's Terminal.
Install Visual Studio Code HERE then The Code Runner Extension HERE
You could also check out these tutorials for installation on Linux, Windows or Android.

Getting Started With Python

Now you have the required tools. Let us birth our first program.

  • On your Desktop create a new folder by the name "PythonFiles".

  • Start Visual Studio Code and open a new file.

  • Save the file in the folder PythonFiles as Hello.py

NB

Python files are saved with the suffix '.py'

  • Type in the following code:
print("Hello World")
Enter fullscreen mode Exit fullscreen mode
  • Click the run button on the top right corner. The terminal will open displaying:
Hello World
Enter fullscreen mode Exit fullscreen mode

Explanation

The function 'print' in python is used to output the value in it's confines and so in this case the code prints out 'Hello World'

Python Comment.

In programming, a comment is a line of code added to a source code to give an explanation to the code and what it does.
Comments aren't executed with the code. In python, we comment by typing in a hash(#) before the comment as shown bellow.

#comment
Enter fullscreen mode Exit fullscreen mode

The comment above covers a single line only. For multiline comments type in triple quotes(""") before and after the line of code you wish to comment. Here is an example:

"""
This is a
multiline
comment
""""
Enter fullscreen mode Exit fullscreen mode

Python Variables.

Variable in programming are used to store values that are later used by the program to execute tasks. This is how to crate and assign a variable a value:

variable_name = variable_value
Enter fullscreen mode Exit fullscreen mode

There are rules to naming variables. These rules include:

  • The variables can be named in alphanumeric characters (A-Z),(a-z),(1-9) and (_).
  • A variable must start with a letter or underscore and not a number.
  • Variable names are case sensitive.
  • Variables cannot be named after keywords for example "print".

Here is an example of a variable and its value:

boys = 3
Enter fullscreen mode Exit fullscreen mode

Basic Python Datatypes.

Datatypes are categorisation of data items. There are 3 basic Datatypes in python

- String.

This ranges from a single alphanumeric character to a series of alphanumeric characters. A string can be assigned to a variable in two ways: typing it between double or triple quotation marks as below:

#double quotation marks
people="Ladies and Gentlemen"
print(people)

#Output.
Ladies and Gentlemen

#triple quotation marks
thanks="""Be grateful for everything"""
print(thanks)

#Output.
Be grateful for everything
Enter fullscreen mode Exit fullscreen mode

You can as well output a string without initially declaring it as a variable as we did before:

print('Hello World Again')

#Output.
Hello World Again
Enter fullscreen mode Exit fullscreen mode

- Numeric.

Numeric data is in three forms; Integers, Float and Complex numbers.
- Integersare whole numbers for example 4,96
- Float are numbers with a floating decimal value for example 4.96
- Complex numbers are numbers with complex classes for example cj6+7
Here is how they are assigned:

first = 7 #integer
second = 7.77 #float
third = M40i #complex number
Enter fullscreen mode Exit fullscreen mode

- Boolean.

Boolean integers may have one of the two values true or false.

#boolean
x = false
type(x)
y = true
type(y)

#Output:
<class 'bool'>
<class 'bool'>
Enter fullscreen mode Exit fullscreen mode

The output is verifying the datatype of both y and x is Boolean.

Operators in python.

Arithmetic Operators.

These include addition(+),subtraction(-) ,multiplication(*) ,exponent(**) ,division(/) ,floor division// and modulus(%).
Exponent is used for square roots, floor division divides the numbers then outputs the result rounded off to it's lower digit and modulus returns the remainder during a division. Here is an example of how the arithmetic operators work:

a = 2
b = 9

print(a + b)#addition 
print(b - a)#subtraction
print(b/a)#division
print(b*a)#multiplication
print(b//a)#floor division
print(b**a)#exponent
print(b%a)#modulus

#Output:
11
7
4
18
4
81
1
Enter fullscreen mode Exit fullscreen mode

The addition operation can also concatinate a string:

print("Hello "+"world"+".")

#Output:
Hello world.
Enter fullscreen mode Exit fullscreen mode

Assignment Operators.

These operators assign a variable its value. They include: =, +=, -=, /=, *=, //=,**=, %=.
Here is an illustration of how they are used;

a = 9;
b = 4;
#above the '=' sign assigns the values to the variables

b+=4 #This adds 4 to the value in b then assigns the result to d
print(b)

#Output:
8
Enter fullscreen mode Exit fullscreen mode

All other assignment operators work in ta similar way.

Comparison Operators.

Examples of this are: equal to ==, not equal to !=, greater than >, less than <, greater than or equal to >=and less than or equal to <=. These operators are used to compare variables then return true or false. They are often employed in python conditions for instance if...else conditions.

a = 7
b = 4
print(a==b)#equal to
print(a!=b)#not equal to
print(a<=b)#less than or equal to
print(a>=b)#greater than or equal to
print(a<b)#less than
print(a>b)#greater than

#Output:
False
True
False
True
False
True
Enter fullscreen mode Exit fullscreen mode

Here is some enlightenment: The equal to and not equal to operators can also be used to compare strings as shown below:

print("me"=="you")
print("me"!="you")

#Output:
False
True
Enter fullscreen mode Exit fullscreen mode

Logical Operators.

Logical operators are three in number; and, or and not. When run, they return True or False.
and returns true only when both operands are true and false when both or one of the operands is false. Here is how it works:

print(True and True)
print(True and False)
print(False and True)
print(False and False)

#Output
True
False
False
False
Enter fullscreen mode Exit fullscreen mode

or returns true when one or both operands are true and false when both operands are false.

print(True or True)
print(True or False)
print(False or True)
print(False or False)

#Output
True
True
True
False
Enter fullscreen mode Exit fullscreen mode

not returns the opposite of the operand.

print(not True)
print(not False)

#Output
False
True
Enter fullscreen mode Exit fullscreen mode

Python Logical Conditions

If Statement.

This statement is written using the if keyword. It evaluates whether a condition is true or false then if true goes ahead and executes a specified code.

a = 4
b = 6
if a<b:
   print(6 is greater then 4)

#Output:
6 is greater than 4
Enter fullscreen mode Exit fullscreen mode

If...else Statement.

The If...else statement evaluates a condition and runs one of two codes specified as per the outcome.

a = 4
b = 6
If a>b:
   print("4 is greater than 6")
else:
   print("4 is less than 6")
#note: an if else statement without indentation will result to an error

#Output:
4 is less than 6
Enter fullscreen mode Exit fullscreen mode

If...elif...else Statement.

The elif keyword is adopted in python to allow more than two conditions to be accomodated in a syntax.

a = 10
b = 5
if a=b:
   print(a is equal to b)
elif a>b:
   print(a is greater than b)
else:
   print(a is less than b)

#Output;
a is greater than b
Enter fullscreen mode Exit fullscreen mode

Data Structures In Python.

Data structures provide a way of arranging data so it can be accessed efficiently whenever needed.

Dictionary.

This is an ordered collection of data values that holds the key and value pair that optimizes its functionality. You can create a dictionary with an integer key or a mixed key.
Here is an example of a dictionary:

#with an integer key
one = {
    1:'Be',
    2:'You',
    3:'Everyday'
}
print(one)

#with mixed key
two = {
    Name:'Ace',
    1:[3,4]
}
print(two)

#Output.
{1:'Be', 2:'You', 3:'Everyday'}
{1:[3,4], Name:'Ace',}
Enter fullscreen mode Exit fullscreen mode

Array Datatypes.

Here we will focus on list and tuple.

1. List.

A list in python is an ordered grouping of any arbitrary datatypes that can be accessed by their indexes. Values in a list are assigned indexes starting from zero then one onwards. The first value in a list gets the index 0 then the second 1 and so on. Here is an example of a list:

brands = ['Nike', 'Adidas', 'Puma']
print(brands[1])

#Output:
Adidas 
Enter fullscreen mode Exit fullscreen mode

Lists have distinct characteristics from other data structures;

  • Lists can be nested on other lists.
  • Lists can be muted in a program.
  • Lists are accessed by their indexes.
  • Lists can accommodate any arbitrary values ranging from strings to numeric values.
  • Lists can be modified:

Accessing values in a list.

shoes=['boots', 'loafers', 'sneakers', 'crocs', 'slides']
print(shoes[3])

#Output:
crocs
Enter fullscreen mode Exit fullscreen mode

Slice of list.

Slice of a list is useful in extraction of subsets in a list. The values are extracted up to a specified index. Here is an example;

shoes=['boots', 'loafers', 'sneakers', 'crocs', 'slides']
print(shoes[0:3])
print(shoes[:3])

#Output:
['boots', 'loafers', 'sneakers']
['boots', 'loafers', 'sneakers']
Enter fullscreen mode Exit fullscreen mode

The list is retrieved up until but not including the value at index 3 in both cases

Updating Items on a list

This is how we update a list's items;

shoes=['boots', 'loafers', 'sneakers', 'crocs', 'slides']
shoes(1)=['monk']
print(shoes[1]

#Output:
['monk']
Enter fullscreen mode Exit fullscreen mode

The 'loafers' in the list has been replaced by the 'monk'.

List Methods.

Methods are specifically designed to modify lists.

Append Method.

Adds an item to a list

shoes=['boots', 'loafers', 'sneakers', 'crocs', 'slides']
shoes.append(chukka)
print(shoes)

#Output:
['boots', 'loafers', 'sneakers', 'crocs', 'slides', 'chukka']
Enter fullscreen mode Exit fullscreen mode

Remove Method.

Removes the first instance of an item in a list

shoes=['boots', 'loafers', 'sneakers', 'crocs', 'slides']
shoes.remove(boots)
print(shoes)

#Output:
['loafers', 'sneakers', 'crocs', 'slides',]
Enter fullscreen mode Exit fullscreen mode

2. Tuple.

Tuple is quite similar to list apart from a few features as listed below.

  • Tuples are defined by enclosing items in them in parenthesis () and not square brackets []
  • Tuples are immutable
school = ('medicine'', 'law', 'engineering', 'education', 'business')
print(school)

#Output
['medicine'', 'law', 'engineering', 'education', 'business']
Enter fullscreen mode Exit fullscreen mode

The greatest resource in life being time, let me thank you for spending yours on this publication. Gratitude.
Find me on Twitter at i_njili

Top comments (0)