DEV Community

Cover image for INTRODUCTION TO PYTHON
Naftal Rainer
Naftal Rainer

Posted on

INTRODUCTION TO PYTHON

Getting started in coding can be tough. Choosing which language to learn can as well be tough. Staying true and consistent to your language of choice can equally be tough. But despite all these tough conditions it's only passion that can drive us through.
In a world of over 500 programming languages, I find python the most interesting due it's simplicity and versatility. It's wide scope of applications is even more meritorious. In Python programming language, you will find that it can be easier than ever to learn about coding and to even read it like a professional.

Brief History
Python is an interpreted high-level general-purpose programming language developed in the late 1980s Guido van Rossum and released for public in 1991.
Its name was derived from the BBC TV show Monty Python's Flying Circus and has so far had release of various streams of versions from the early version 2.0, version 3.0 up to the latest version 3.9.6 and it can be downloaded from www.python.org Mac OS X systems as well as those with Ubuntu will already have Python preloaded. You will simply need to download a text interpreter to get started.
It is quite different from other programming languages in its syntax and semantics which focuses on code simplicity and readability. This is made possible by its well-defined English keywords and minimal punctuation dependence. For example, python uses whitespace indentation for delimiting code blocks instead of curly brackets and semicolons aren't required for statement termination unlike in c and c++ amongs others.
In general, python is kept much simpler and you may find it is easier to read through the lines and see what you are doing.
Python programs are written in files having a .py filename extension which is supported by various operating systems e.g. Windows, Linux/UNIX, macOS and more.

Desirable Python features are:

Python is really interactive. This makes it easier for testing the functionality of a program. This may be done by modularization - extracting out small bits of code and testing to see if they work. You can also bundle it with a development environment called IDLE.

Python has numerous libraries. This widens a programmer’s scope enabling him/her to work with other programming tools required for different fields such as web development, data science, machine learning e.t.c. to enable different functionalities e.g. connecting with web servers.

Python is platform independent. Python programs can be run on any unit including Unix, Linux, Windows, and Mac OS X.
Python is extensible. It is easy to extend into other modules like C or C++ and write snippets to perform various functions.

Python is open Source. The product is free to download, use, make modifications and redistribute. It is under an open source license so others are able to use it

Easy to debug. Errors can be caught quickly since data types are dynamically typed, when you mix types together that don’t match, it will raise an exception for you to notice. You can group the codes into packages and modules if needed.

Applications of python

Python has various uses across applications, platforms, and services as discussed below.

  • Web and Internet Development

Web development is one of the areas where python shines as it offers numerous Frameworks such as Django and Pyramid,Micro-frameworks such as Flask and Bottle and Advanced content management systems such as Plone and django CMS. These frameworks which enhances functionality and implementation have been used to power some of the world’s most popular sites such as Spotify, Mozilla, Reddit, the Washington Post and Yelp.

Python's standard library supports many Internet protocols:

  1. HTML and XML 2.JSON
  2. E-mail processing.
  3. Support for FTP, IMAP, and other Internet protocols.
  4. Easy-to-use socket interface.
  • Artificial Intelligence

Python contains some of the top libraries for machine learning and artificial intelligence which a whole new approach to problem-solving.
Python for machine learning development can run on any platform including Windows, MacOS, Linux, Unix, and many others. this saves time and money for tests on various platforms and makes the overall process more simple and convenient.

  • Automation

Python has range of libraries, tools, and frameworks available to bolster your programming efforts in task automation e.g. selenium , smtplib library, beautiful soup etc. which automation efforts simpler and more intuitive.

  • IoT

Python is scalable, expandable, portable, and embeddable. This makes Python system-independent and allows it to accommodate multiple single board computers, irrespective of the operating system or architecture.

  • Game Development.
  • Scientific and Numeric Applications.
  • Software Development.
  • Data science.

Python is capable of handling almost any development requirement

Getting Started with Python

After understanding some of the benefits of python, it's time to get started with it. In order to learn some of the great steps that are needed to create a python program, we need to set up the environment

Installing Python:

The installation procedure involves downloading the official Python .exe installer and running it on your system
https://www.python.org/downloads/. For windows users, Select a link to download either the Windows x86-64 executable installer or Windows x86 executable installer.

Add python to path variables:
Setting up the Python path to system variables alleviates the need for using full paths. It instructs Windows to look through all the PATH folders for “python” and find the install folder that contains the python.exe file.
When running the installer, select the Install launcher for all users and Add Python 3.7(or the version of your choice) to PATH checkboxes which places the interpreter in the execution path automatically.
If your version of the Python installer does not include the Add Python to PATH checkbox or if you have not selected that option, then you have to do it manually by following the steps bellow.

1.Go to control panel.

  1. open the System Properties window.

  2. Navigate to the Advanced tab and select Environment Variables.

  3. Under System Variables, find and select the Path variable.

  4. Click Edit.

  5. Select the Variable value field. Add the path to the
    python.exe file preceded with a semicolon

  6. Click OK and close all windows.

By setting this up, you can execute Python scripts like this: Python script.py

Instead of this: C:/Python34/Python script.py

For more information check the site below
https://www.educative.io/edpresso/how-to-add-python-to-path-variable-in-windows

Verify if Python Was Installed On Windows
Navigate to the directory in which Python was installed on the system. For example if it is C:\Users\Username\AppData\Local\Programs\Python\Python3.7.
Double-click python.exe.
The output should be similar to what you can see below:

CMD Output

Install Text Editor:
A code editor is a tool that is used to write and edit code. They are usually lightweight and can be great for learning especially for a beginner.

1.) Visual Studio Code
Visual Studio Code (VS Code) is a free and open-source IDE created by Microsoft that can be used for Python development.
https://code.visualstudio.com/download

2.) Sublime Text
Sublime Text is a popular code editor that supports many languages including Python.
https://www.sublimetext.com/download

3.) Atom
Atom is a highly customizable open-source code editor developed by Github that can be used for Python development
https://atom.io/

4.) Thonny
Thonny is a simple UI Python dedicated IDE that comes with Python 3 built-in. Once you install it, you can start writing Python code
https://thonny.org/

5.) Pycharm
PyCharm is a Jetbrain-powered IDE for professional developers
https://www.jetbrains.com/pycharm/download/

Hello World

"Hello world" is usually the first example for any programming language.

To write and run a simple program, start IDLE and open up a new window (choose New Window under the File Menu), create a new file and save as hello.py in your desired program folders then enter the following code.

print("Hello World!")
Enter fullscreen mode Exit fullscreen mode

Save the document (CTRL + S) then execute.
When using the IDLE commands, under the Run menu, choose Run Module (or press F5). IDLE will ask you to save the file if haven't done so.
To execute hello.py from the command prompt (CMD)
first launch the Command Prompt on Windows or Terminal on macOS or Linux then, navigiate to the folder containing the file.

After that, type the following command to execute the hello.py file:

python3 hello.py
Enter fullscreen mode Exit fullscreen mode

If everything is okay then it will execute with no errors and should display the following message on the screen.

Hello World!
Enter fullscreen mode Exit fullscreen mode

Every program has got a structure that defines it's building blocks and so does python. These are constructs and patterns used to develop programs in any programming language and they include:

  • input
    This is data from an external source (outside environment) that is fed into the program for it to manipulate and process. The various sources may be sensors, keyboard, data from other programs, files e.t.c.

  • output
    This is the result of a program process which is displayed on a screen or stored in a file.

  • sequential execution
    This is an orderly execution of scripted statements.

  • conditional execution
    This is the execution of a given block of statements if a specified condition is met.

  • repeated execution
    Perform some set of statements repeatedly, usually with some variation.

  • reuse
    This involves writing a given set of codes once and then use them in several instances of the program whenever necessary.

Comments
A comment is an information intended to explain to a reader what a given code (or sequence of codes) does. They have no effect in the program therefore can never generate any error unless if written in a wrong syntax.

A single-line comment is written using the # character.

Multi-line comment span several lines and can be written using triple quotes.

#This is a single line comment

'''
Author: Naftal Rainer
Date: 23/07/2021
''' 
Enter fullscreen mode Exit fullscreen mode

A very good use of the multiline comments is to comment out parts of a code. A programmer may want to modify part of a program and retain the old code in case the changes don’t effect. The programmer would then comment out the old code so that it is still there if needed, and it will be ignored when the new program is executed.

Variables
Variables are named memory locations where data is stored for referencing and manipulation by programs. In simple terms, variables are containers for storing data

The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable


# X is the variable name and 2 is the value assigned

x = 2

# y is the variable name and 100 is the value assigned

y = 100

# name is the variable name and "Naftal" is the value assigned

name = "Naftal"
Enter fullscreen mode Exit fullscreen mode

Python variables are not declared explicitly since the declaration happens automatically when a value is assigned to the variable.

Data Types
Python has various standard data types that are used to define the operations possible on them and the storage method for each of them.
The standard data types-

1.) Strings

Strings are a data type in Python for dealing with text. They are a set of characters enclosed within quotation marks.
Various operations can be performed on strings using the various string methods available.

Creating a string - A string is created by enclosing text in quotes. You can use either single quotes,', or double quotes, ". A triple-quote can be used for multi-line strings.
Here are some examples:

x = 'Hello'
y = "World"
m = """My name is Paul Mwasame and
       I find learning python to be super exciting."""
Enter fullscreen mode Exit fullscreen mode

For string methods and apllications refer to w3schools

2.) Numbers

Number data types are the ones that will store the numeric values and are classified as:
-Complex (such as complex numbers)
-Float (floating point real values
-Long (long integers that can also be shown as hexadecimal and octal.)
-Int (signed integers)

It also involves numbers and simple mathematics in Python.
Common operators in python include:

Operator Description
+ addition
- subtraction
* multiplication
/ division
** exponentiation
% modulo (remainder)
// integer division

Python has a module called math that contains familiar math functions, including sin, cos, tan, exp, log, log10, factorial, sqrt, floor, and ceil.
For more information on number check programmiz.com

3.) List

Lists are one of the most versatile data types that you can work on in Python. It contains different items enclosed within square brackets and separated out with commas.
Lists are mutable and can contain elements of different data types and even other lists.

Creating lists - Use square brackets to indicate the start and end of the list, and separate the items by commas.

L = [1,2,3]

L2 = [1, 2.718, 'abc', [5,6,7]]

Enter fullscreen mode Exit fullscreen mode

An empty list The empty list is [].
Long lists can span several lines like the one below:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,20,30, 
           40,50,60,70,80,90,100,200,300,400,500]
Enter fullscreen mode Exit fullscreen mode

We can also use eval(input()) to allow the user to enter a list. Here is an example:

myList = eval(input('Enter a list: '))
print('The first element is ', myList[0])
Enter fullscreen mode Exit fullscreen mode

For more on lists, check programmiz.com

4.) Tuple

Tuples are immutable lists enclosed in parentheses.

t = (1,2,3)
Enter fullscreen mode Exit fullscreen mode

To convert an object into a tuple, use tuple() constructor.
The following example converts a list and a string into tuples:

t1 = tuple([12,25,93])
t2 = tuple('abcde')
Enter fullscreen mode Exit fullscreen mode

The empty tuple is written as:

t1 = ();
Enter fullscreen mode Exit fullscreen mode

To write a tuple with one element include a comma(,) after the element.

t1 = (5,)
Enter fullscreen mode Exit fullscreen mode

To access tuple values at various indices, make use of the square brackets as shown below:

tuple1 = ('Nairobi', 'New York', 1997, 2000)
tuple2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
Enter fullscreen mode Exit fullscreen mode

Tuples are immutable hence no change can be made on them. However, one can take portions/slices of existing tuples and create a new tuple.
Get more operations on tuples here

5.) Dictionary

Dictionaries are key-value pairs and are surrounded by {}.

Creating dictionaries - To declare a dictionary we enclose it in curly braces, {}. Each entry consists of a pair separated
by a colon. The first part of the pair is called the key and can be of any data type and the second is the value. The key acts like an index.

# Empty dictionary
d = {}

dict = {'A':100, 'B':200}

# To change the value of A to 300
d['A']=300
Enter fullscreen mode Exit fullscreen mode

-To access data at a given index say A, the key d['A'] gives value at index A.
-To add a new entry to the dictionary, we can just assign it, like below:
d['C']=500
-To delete an entry from a dictionary, use the del operator:
del d['A']

The order of items in a dictionary will not necessarily be the order in which put them into the dictionary. Python rearranges things in a dictionary in order to optimize

Top comments (0)