DEV Community

King
King

Posted on • Updated on

PYTHON PROGRAMMING

WHAT IS PROGRAMMING?

Programming is simply giving a list of instructions for the computer to follow, these instructions given are what we know as algorithms. Even though computers are very reliable in following instructions, we can’t give instructions in the natural language we speak because natural languages have a lot of ambiguity, for instance; words or sentences have multiple meanings which computers won’t be able to figure out. Instead we have to give them instructions in a programming language which computers can understand because they have specific set of rules.

How to learn programming languages?

The process of learning programming is more than just learning the rules of the python programming, it’s also about how to break down and solve problems regardless of the programming language. Think of programming as a translation technique where you are trying to translate natural language to programming language. The best way to learn programming is through practice.

PYTHON

Python is a widely used programming language which is very easy read and simple to implement. It is free to use, even for commercial applications hence it is considered as open source. It is known to be a high-level programming language because of its closeness to human language than to machine language. This language is the invention of Guido van Rossum in 1991.

WHAT IS PYTHON USED FOR ?

  1. It is used for manipulating large volumes of data and performing complex mathematics.
  2. It is used to create web applications
  3. It is used to create software
  4. It is used for reading and modifying files.

Data Types

When we write code we write what is known as expressions and when we write expressions the python interpreter computes the value of the expression and every value has a type, that’s the type of data. For instance, when we write an expression such as 10, the python interpreter computes the value of the expression which is 10 and then the type of the value for this expression in this case is an integer.

WHAT ARE THE DATA TYPES IN PYTHON?

Numeric Types: int, float, complex
Sequence Types: list, tuple, string
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types bytes

NUMERIC DATA TYPES IN PYTHON

Integers (int) : These are whole numbers. Examples include (1,2,3,4,5)

Float : These are numbers with a dot/point within them. Examples include (1.0,2.0,3.0,4.0,5.0)

How can we find out the type of an object in python?

we use the function type() and the number in parenthesis. When we execute that python tells us whether the number is a float or integer

eg. type(4)
class "int"

type(3.2)
class "float"
Enter fullscreen mode Exit fullscreen mode

Operators and Operands

You can build complex expressions out of simpler ones using operators. Operators are special tokens that represent computations like addition, multiplication and division. The values the operator works on are called operands.

Addition +

5+5
10

Subtraction -

5-4
1

Multiplication * That’s the star symbol

5*5
25

Division / the slash symbol

Anytime we use the division symbol we get a float. For instance 10/3 would give us 3.33. There are times we would want an integer hence we use the truncated division (double slash) and then 10 // 3 would give us 3.

Modular % This gives us the remainder

So 10 % 3 would give us a remainder of 1 because 3 goes into 10 3 times perfectly and then we have a remainder of 1.
Exponential equations . So 42 would give us 16. That means 4 raised to the power 2 giving us 16.

Just like bodmas, python also follows the normal order of operations in math. Bracket eg (1 +1) -> Exponentiation eg 4**2 -> Multiplication & Division -> Addition & Subtraction.

SEQUENCE MUTATION

Sometimes we create an object and along the line we feel the need to change it. For instance, you create a list and along the time you want to keep adding items to it. There are two ways to change a list after you’ve created it;

  1. You make a modified copy of the object
  2. Modify the original

That process is what we call mutation. It can be very confusing however, I’m going to talk about how it works.

SEQUENCE

A sequence is an ordered collection. Basically what that means is that it has a list of items that come in first, second, third order etc and it also has a length. The three types of sequence in python are strings, lists and tuples.

Strings

A string is an ordered collection of characters of a single type. I create a string by assigning a sequence of characters in single, double or triple quotes to a variable. If I want to create a single lined string I use a single or double quote

Eg

S = “Hello world”
Print(s)

However, if I want to create a multi-lined string I use triple quotes

Eg

S = “”” Hello world
I hope you are all having a nice time
I wish you well”””

Print(s)

A string that contains no characters, often referred to as the empty string, is still considered to be a string. It is simply a sequence of zero characters and is represented by ‘’ or “” (two single or two double quotes with nothing in between).

"Carl is a good man"
'Carl is a good man'

'Carl's a good man'
syntax error <-- This happens because the single quote before the Carl is closed by the single quote before the s. In this instance we correct it by using double quotes.

"Carl's a good man"

Carl = Handsome
Carl
Handsome

If i want lets say the d and s in Handsome i can call it by using the square bracket.
Carl[3:5]
ds <--- in python the first element is always assignment the index value of 0.The first number within a square bracket is always inclusive and the last number is exclusive hence we used [3:5] to call out the 'ds' in Handsome

Methods in strings

There are numerous methods in strings and we are going to use a few.

Carl = Carl.upper
HANDSOME <-- you notice all the letters are in upper case

len(Carl)
7 <--- there are 7 letters in the word "handsome"

LIST

A list is an ordered sequence of characters of any type in a square bracket where every element is identified by an index. Lists are similar to strings, which are ordered collections of characters, except that the elements of a list can have any type and for any one list, the items can be of different types.

There are several ways to create a new list. The simplest is to enclose the elements in square brackets ( [ and ]).

Example;

[10, 20, 30, 40]

["spam", "bungee", "swallow"]

The first example is a list of four integers. The second is a list of three strings. As we said above, the elements of a list don’t have to be the same type. The following list contains a string, a float, an integer, and another list.

["hello", 2.0, 5, [10, 20]]

Alt Text

lets say we want to call out a particular element in the list we use the square brackets;

Alt Text

we can also work backwards using a negative number;
Alt Text

we can also use the slice method to get a range of elements in the list. Always remembering that the first member is inclusive and the last member is excluded;

Alt Text

We can also concatenate the several lists of elements and join them together to make one list;

Alt Text

we can also change an element within a list by equating that variable to another. For instance;

Alt Text

Tuples

A tuple is a sequence of characters of any type just like a list. It is enclosed in parentheses and separated by comma. One way to create a tuple is to write an expression, enclosed in parentheses, that consists of multiple other expressions, separated by commas.

julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia")

The key difference between lists and tuples is that a tuple is immutable, meaning that its contents can’t be changed after the tuple is created.

To create a tuple with a single element we have to include the final comma, because without the final comma, Python treats the (9) below as an integer in parentheses:

S = (9,)
Print(type(S))

Also;

S = “100”
A = [100]
B = 100

Python views all three as different data types. S is a string, A is a list and B is an integer.

STANDARD INPUT
my text editor of choice is visual code and i created a python file called basic.py and i ran everything at the terminal below.

first of all i use ( cd "path to python file") to navigate into the directorate and i use (exit()) to leave a directorate.

So in python , we can ask the user of our programme questions and user can type in data, strings or numbers and we can take that data into the programme and do something with it and we do that by using the function called (input). For instance;

Alt Text

PYTHON CONDITIONS AND IF STATEMENTS

The if statement allows us to control the flow of our code based on certain conditions. For instance, if the condition is true and it would perform a certain function but if it is false then it performs another function. It follows a cause and effect model.

Python supports the usual logical conditions from mathematics:

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
Enter fullscreen mode Exit fullscreen mode

Examples of "if, elif and else" statements;

Alt Text

ITERATION

Iteration is used to describe repetitive execution in computing. This process may involve sending an email to countless number of people or updating bank balance to over millions of customers every night. It involves running a piece of code for every item in a sequence be it a string, list or tuple.

FOR LOOPS

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

With the for loop we can execute a set of statements, once for each item in a list, tuple, string.

The overall syntax is for in :
• Between the words for and in, there must be a variable name for the loop variable. You can’t put a whole expression there.
• A colon is required at the end of the line
• After the word in and before the colon is an expression that must evaluate to a sequence (e.g, a string or a list or a tuple). It could be a literal, or a variable name, or a more complex expression.

Alt Text

Lets say i only want to go through a specific portion of the list, i use the slice method.

Alt Text

Alt Text

Alt Text

WHILE LOOP

The while loop allows us to cycle through a certain portion of code while a specific condition is true

Alt Text

Alt Text

Alt Text

RANGE

A range generates a list of numbers for us which we can then use to iterate over with a loop

Examples

All the range does is to generate a list of numbers. It would loop through a range of members from 0 to 5 except 5 itself.

Alt Text

If we want to specify our starting point we use range( , ) the first number before the comma is the starting point and the number after the comma is the end point which is always non-inclusive in python

Alt Text

If we want to specify the step size we include another comma and mention a number( , , ).

Alt Text

FUNCTIONS

A function allows us to create a block of code which we can call out and used when we want to. To create a function we use the "def" which stands for "define"

If we want to pass data into a function , we can specify the parameters we can use to pass through the function.

Alt Text

We can issue defaults and then subsequent inputs can override previous inputs

Alt Text

Also,

Alt Text

THE SCOPE OF A VARIABLE

A scope refers to an area or zone in which a variable can be accessed in. There are two areas involved here, the local area and the global area.

Alt Text

You realize that when the global variable is defined from within the function it affects it locally and any other instance of "my_name" outside of the function.

Alt Text

Here is an instance where the local variable overrides the global variable in the "my_name" variable which occurs inside the function only

Alt Text

If we want to override the global variable from within a local function we use the "global" statement and call out the name of the variable as seen below.

Alt Text

DICTIONARY

Dictionary is a collection of key and value pairs. A dictionary doesn’t allow duplicate keys but the values can be duplicate. It is an ordered, indexed and mutable collection of elements. In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value.

Alt Text

If i intend to retrieve the value of one of the keys we can use the square bracket notation with the quotes in it [''].

Alt Text.

If i try accessing a key or value that is not present in the dictionary i get an error.

Alt Text

In order to avoid that error we can check the existence of a key before we try to retrieve them. We use a statement known as the "key in dict". The "key" here is the name of the key you are trying to retrieve, 'in' is a key word in python and "dict" is the name of the dictionary you want to retrieve the key from. False indicates the absence of the key and True indicates its presence.

Alt Text

Another way to check of the availability of the key is to call out the full list of the keys in the dictionary using "name of dictionary".keys() afterwhich we can change it to an actual list using list("name of dictionary".keys())

Alt Text

The same process is done when you want to retrieve the values using "name of dictionary".values() afterwhich we can change it to an actual list using list("name of dictionary".values())

Alt Text

We can typecast this into a list and store it into a variable so we can work with it. Example;

Alt Text

Now that we have stored it into a variable if we want to count how many instances of a value we can use (values.count(name of value or value number).

Alt Text

If we want to add a new key:value pair to an existing dictionary we can use name of dictionary['new key'] = new value

Alt Text

Now applying all that;

Alt Text

SETS and SORTING
SORTING
We are going to learn how to sort a collection of elements in numerical or alphabetical order. We do that using a method called sorted(). In the first example you'd realize the elements have been sorted according to numerical order.

Alt Text

If you pay attention to the next example you'd realize that it is true that it has been sorted in alphabetical order, then again you'd also realize that all the elements starting with capital letters were sorted first before those starting with small letters

Alt Text

SETS

In sets, duplicates aren't allowed unfortunately they do not preserve order.

Alt Text

Alt Text

Applying this in python, lets say we want to remove duplicates.

Alt Text

CLASSES

A class describes how an object to look and behave. Let's go on to how to create a class;

We start by creating attributes for the class

Alt Text

We further create a method for this method;

Alt Text

If we want to pass in our own parameters we can allow the initialization function accept custom values by;

Alt Text

METHODS AND ATTRIBUTES

Every time we see 'self' introduced to a method then it is an instant method and also everything defined in that attribute is an instant attribute. We can apply class level attributes by coming out of the init function and defining our attribute. The class level attribute is not peculiar for a particular instance but rather the same for all. We can access a class attribute (pleasantries) by an instance class (Asare) or the class itselfs (Family) and below is an example of that;

Alt Text

class methods

we can create a class method by using the decorator @classmethod.This method is going to be common for all instances (families) and not peculiar to a particular instance. It takes the attribute (cls) which refers to the class. It has access to class level attributes and it is defined by

Alt Text

static method

This is a method that doesn't have access to "self" and it also doesn't have access to "cls". It only has access to the parameters that we pass into it individually.

Alt Text

MODULES AND PACKAGES

A module is a single Python file, a package is a directory of Python modules containing an additional init.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts.

When you are working on a complex python project and you have loads of different functions in them with different custom classes, tons of lines of codes. it would become very hard to update because its very long. We can split that code into logical sections and those sections are going to encompass some kind of functionality for your program. Each of these different sections will have their own python file and those files could be called upon when we need them, we can import them and use them. These files are what we call modules.

Alt Text

HOW TO CREATE A PACKAGE

  1. You create a new folder 2.Inside the folder you create a new file called init.py which tells python that this is a package. We don't need to place anything in this file. Just the existence alone tells python this is a package.
  2. We can then create other new files and begin to code.
  3. We import files within the package by (from "package name"."name of module" import "class name")

  4. If we want to import multiple functions or classes we could do that by separating the names of the functions by a comma.
    (from "package name"."name of module" import "class name","function")

LIST COMPREHENSIONS

A list comprehension gives us a simple way to construct a list based on other collections. Example

In the list comprehension we pass in what we want to do first followed by the loop and any conditional statement followed.

Alt Text

For the first example there is no conditional statement

Alt Text

In this example there is the presence of a conditional statement

Alt Text.

MAPS

The map() function applies a given function to each item of a list or tuple and returns a list of the results.

new_list = map(function,data)

So first of all we have the map function and then it takes in two parameters that is the function we want to pass the data through to change the data and then the data itself.

First example we using the long approach using a for loop.

Alt Text

Using the same data we apply the simple map function approach

Alt Text

Applying my knowledge on list comprehension

Alt Text

FILTERS

The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.

For the first example we have a sample end of semester results and we attempt filtering out the grades that are not equal to F

Alt Text

Using the loop method

Alt Text

Applying list comprehension

Alt Text

LAMBDA

What are lambda functions in Python? In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions

lambda argument : expression

Alt Text

DECORATORS

A decorator is a design pattern in Python that allows a user to add new functionality to an existing object without modifying its structure. Decorators are usually called before the definition of a function you want to decorate. It starts with an @ symbol attached to any word/name of your choice. It starts with an @ symbol attached to any word/name of your choice.

In this example a decorator named Hello was created (@Hello). Anytime we called on it it printed an output above and below a function.This decorator doesn't modify the function itself in the sense that in the absence of the decorator the function still works.

Alt Text

READING/WRITING FILES IN PYTHON

When it comes to reading files in python we use a special command called 'open'.

open("name of file","mode i want to open the file in")

"name of file"

  1. absolute path of the file in whatever format
  2. relative path of the file
  3. exact file name if it is in the same directorate.

"mode i want the file in"

'r' = this stands for read, you can only read the information in the file without being able to modify it.

'w' = write, you have the authority to write new files or change existing files with this mode.

'a' = append, you can only add new information to existing information. you cannot change or modify existing information, you can only add new information to existing one.

'r+' = you can read and write.

here is an example.

Alt Text

Top comments (0)