Introduction to Python:

Python is one of the great among the greatest of all the programming languages. It has an Object Oriented nature. It is interpretive. Highly informal in taste. And it is interactive to program. Python’s syntax is simple, and elegant.

In this part of the primer, you will learn the beginner stuff about Python. You can also see this to learn how to learn a programming language. I will cover most of the stuff that I believe a beginner should know. I will also try to be a bit concise but comprehensive in scope.

Let’s start.

print() function

You can use print() to print any information on the screen. E.g. if you want to print a string, you can use

For now just remember this. We will come to more advanced usage of the print() function, as we move along.

Indentation

First get to know what the block is. A block is a piece of code that acts as a standalone piece of code or as a unit to serve some specific purpose. This can come in multiple places in python. In python, we do not use parentheses for code blocks (which is normally the think in some other programming languages). Instead a tab character, or more than one space used to denote a block. Let’s see an example

Remember to be consistent in the usage of indentation.

Variables and Types

If I were called a variable, my name would be Khawar, and my Type would be Human. A variable is anything that has a specific value, name, and type. A variable can attributed. As it is not possible to convert some human into other species, but in computer science variables, sometimes, can be converted from one form to the other.

In python, you do not need to declare types of variables e.g. you do not need to specify a particular variable is of type human or else. You just use them, and python interpreter will know what you meant. I will show how you use them. This sort of programming in which you do not declare types is called non-“statically-typed” programming. Also remember that every python variable is considered as an object. We will come to this latter. But if you have a background in linux as well, then its like saying everything in linux is a file.

You just assign a value to the variable e.g.

Variables are of different types in Python. Let me cover some of them here.

Numbers

Python gives you power to use two types of number. First type is an integer. Second type is a floating point number. In an extended way it also supports complex numbers. Let’s see an example

In the above code, you will notice we have used the print statement in a different way. If you want to show or evaluate some variable in a print statement you use object argument specifiers. What happens is that you use %d to show an integer and %f to show a float. You use the % sign just before the variable names that you want to represent in your print statement.

We will work with complex numbers in part 2 of this primer.

Strings

Strings are sort of an array of characters or in python terms a list of characters. You can represent strings in a double quatation marks or single quotation marks. It is suggested that you use double quotation marks because then you can easily include single quotes in the string representation itself. Here are the examples

You use %s argument classifier in the print() function to represent a string e.g.

String concatenation

You can use + operator to join two strings together. Remember you cannot use integers and strings together as concatenation e.g.

Variable Assignment

You can give more than one variables in the same line. And then you can assign them different values in the same line. E.g.

Lists

One of the most important topics in Python are lists. Lists are similar to arrays in certain languages. But lists are somewhat different in Python. But for now you can think of as arrays. List can contain unlimited number of values. You can put variables of different types in the same list. This is somewhat different then the concept of arrays in some languages, where you are required to put variables of the same type. You can use append() method to add values in the list. You can access values from the list using an integer index. The index starts from 0 (Zero). So the maximum number represented by the index is one less than the total number of values in the list.

If you access an element using an index which is greater than the maximum index, your program will not run. So always get to know what is the length of your list. Use the len() function to get the length of a list. You can also use the len() function with strings, which gives you the number of characters in the string. The maximum index is always one less than the length of a list or a string.

Here is an example

Operators

Operators are symbols which, when applied to variables, manipulate the variables. There are many types of operators in Python. Lets start with the basic ones.

Basic Operators

Arithmetic Operators

You can use + for addition, – for subtraction, * for multiplication, / for division, % for modulo (remainder in mathematics), and ** for powers of integers. You can also use + and * with strings as well. In case of + with string, you get the concatination effect that we have already shown earlier. And with * you get the repetition of the string.

There is a concept called operator precedence. Python follows all rules of operator precedence. Operation precedence dictates how the expression should be evaluated while working with operators. You can use a simple way to remember precedence of arithmetic operators e.g. PEMDAS (PARENTHESES EXPONENTS MODULUS DIVISION ADDITION SUBTRACTION). You can easily remember the rule if you can remember the phrase “Please Excuse My Dear Aunt Sally”.

Here are few examples

You can also use Operators with Lists. + operator will make two or three lists joined together as in Union. You can also use * operator to repeat lists. E.g.

String Operations

You can use len() function to get the length of a string, as said earlier. You can access the characters in the string just like you access values in the list. You can get the index of a particular character in the string using index() function. You can use count() function to get the number of particular characters in the string. E.g.

String slicing is a very important topic. In string slicing you can cut the string in whatever way you like. You can use a step as well to slice in a manner that you can skip some characters while slicing. The syntax follows this rule string[<start>:<end>:<step>]. E.g. You can use – with the index, so that the slicing starts from the end.

You can use upper() and lower() function to change the case of a string. You can check the startwith() and endswith() functions to check whether a string starts or ends with a particular sequence of characters. You can use split() function to split a string into multiple parts based on a delimiter. You get a new list out of it. E.g.

There are other operators as well. We will be defining them as we move along in the primer.

Conditions

Conditions are a topic which gives you power to control the flow of you program. One such example is if Bob comes to office, then great him with a cupcake, if he doesn’t come at the office, then call him on his mobile. If mobile is off, then send an email. You can use an “if” statement to control the flow of your program.

Conditional Operators

The output of a conditional operator is represented by a Boolean operator e.g. TRUE or FALSE. == operator is used to check whether two operands are equal or not. != is used to check whether two operands are NOT equal or not. > operator is used to check if one operand, to the left, is greater than the other operand, on the right. < is operator is used to know whether operand on the left is less than the operand on the right or not.

Similarly there is an “in” operator which check whether some value is inside some list or not.

You can use “and” and “or” operators to combine two or more conditions as well. Similarly you can have “if” condition coupled with either “elseif” or “else” statement.

Remember, everything in Python is considered to be an object. There is an “is” operator which check whether two objects are same or not.

There is a “not” operator as well. This operator just inverts the Boolean relation of some object.

Let us see some examples

Loops

Python has got two variants in loops. These are “for” and “while” loops. In “for” loops you need a sequence on which to work the block inside the “for” loop. You can also use range() function to generate a range of number on which your “for” loop can iterate.

“while” loop is a bit different. It checks a specific condition in its block. As long as that condition is TRUE, it repeats otherwise it stops.

You can use “break” and “continue” statement inside “for” or “while” loops. “break” statement exits the loop. And “continue” states exits the iteration, but continues with the next one.

You can also use “else” statement inside a loop. This doesn’t happen in some of the major languages. But python is unique in that sense. When the condition returns a FALSE inside a loop, the “else” statement is evaluated. If you are using a “break” statement inside a loop then “else” statement will NOT be evaluated. This is an important point to remember.

Let us see some examples.

 

Functions

Now we are going into the realm of organization, reusability, segmentation, and ordering. Functions are blocks of code. You define functions. You name them. Then you can reuse them in any other accessible part of the code. You can give different attribute to the function which defines their behaviour.

You create functions using “def” keyword at the head of the function definition. You define the block inside the block location of the function name and argument definition. Function name should be a readable name which follow certain conventions. You can give functions some value to operate on them in the body or block. These values are called arguments of the functions.

A function can return a value, using a return statement. This statement should go at the end of the function.

You can call a function from other parts of your program using the function name and the argument(s), if any.

Let’s see an example. You will notice that I have used (jockers, hearts) in the example. This is called a tuple. Tuple is basically a list of comma separated values enclosed in a parentheses. The print statement operates on them individually.

Classes

As mentioned earlier that Python is an Object Oriented Programming language. This means we can create objects that have a meaning, and which can interact with other objects in some capacity. You have already seen how to create variable and functions. You can put these variables and functions inside classes. You can expose the function and variables through the classes they are in. These functions will become the interfaces for other classes. Developers create interfaces to reuse the code, or provide services from the application. Objects are actually instances of a class, which essentially provides the definition.

You use the “class” keyword at the start of the class definition, to define a class.

You can instantiate, that is create an object of the class, using an assignment operator.

You can access the properties and functions, defined in the class, using access operator which is “.” i.e. DOT.

You can access the functions in the same way as you access properties.

You can instantiate multiple objects of the same class, and you can assign different values to those object’s properties.

Let’s see an example.

Dictionaries

Dictionaries are sort of like lists or arrays. But they do not work using indexes. They work using keys, and values. You provide a key, and you get a value for that key. These keys and values are location in the dictionary. A key can have any type. Similarly the value can be of any type.

You can iterate over the values of a dictionary using items() function of the dictionary.

You can remove a (key, value) tuple from the dictionary using del keyword in front. You can also use pop() function of the dictionary.

Let’s see an example

There are more aspects to dictionary, I will cover in a different primer.

Modules and Packages

Any Python file which has .py extension is coined as a Module. This module contains all the functions, that module provides to external or internal entities. You can import other modules using the import keyword. There is a huge list of built in modules in the Python standard libraries. Plus there are a lot of custom modules available out in the wild.

Packages are those entities which are basically namespaces. Each namespace can have one or more modules in it or even one or more namespaces. E.g. WordPress package can have a theme Module, db Module etc. Each package is actually a directory in your filesystem. That directory must contain a file called __init__.py file. This file can contain nothing. This only tells other namespaces or modules that it is actually a separate namespace.

Let’s see an example

I hope you would have enjoyed, and learnt from this primer. If you have any question, you can comment in the comment section.


The author can be reached at khawar@infoginx.com.

If you would like to contribute on Infoginx, feel free to reach out at info@infoginx.com.

 [/fusion_builder_column][/fusion_builder_row][/fusion_builder_container]