INTRODUCTION TO PYTHON

Ravi shankar
16 min readJun 21, 2021

--

BY- RAVI SHANKAR

Hello Guys,

Today’s blog is all about starting the journey towards python programming. so this blog is dedicated to all those who are from any domain whether they are students, working employees, mechanical engineers who are willing to learn to program, and newbies. Nowadays python is the most widely used programming by tech giants like Google, Netflix, Facebook. Looks interesting right, then let’s get started.

1. What is Python??

Python is a high-level object-oriented programming language that was created by Guido van Rossum. It is also called general-purpose programming language as it is used in almost every domain.

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python’s simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.

Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmers with other programming languages like C++ and Java.

1.1 Python Keywords

Python keywords are special reserved words that have specific meanings and purposes and can’t be used for anything but those specific purposes. These keywords are always available — you’ll never have to import them into your code.

Python keywords are different from Python’s built-in functions and types. The built-in functions and types are also always available, but they aren’t as restrictive as the keywords in their usage.

As of Python 3.8, there are thirty-five keywords in Python.

1.2 Python Identifiers

An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.

Rules for writing identifiers

  1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all are valid example.
  2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.
  3. Keywords cannot be used as identifiers.

4.We cannot use special symbols like !, @, #, $, % etc. in our identifier.

5.An identifier can be of any length

1.2.1 Python Statement

Instructions that a Python interpreter can execute are called statements. For example, a = 1 is an assignment statement. if statement, for statement, while statement, etc. are other kinds of statements which will be discussed later.

1.2.2 Multi-line statement

In Python, the end of a statement is marked by a newline character. But we can make a statement extend over multiple lines with the line continuation character (\). For example:

a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9

This is an explicit line continuation. In Python, line continuation is implied inside parentheses ( ), brackets [ ], and braces { }. For instance, we can implement the above multi-line statement as:

a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [ ] and { }. For example:

colors = ['red',
'blue',
'green']

We can also put multiple statements in a single line using semicolons, as follows:

a = 1; b = 2; c = 3

1.3 Python Comments

Comments are very important while writing a program. They describe what is going on inside a program, so that a person looking at the source code does not have a hard time figuring it out.

You might forget the key details of the program you just wrote in a month’s time. So taking the time to explain these concepts in the form of comments is always fruitful.

In Python, we use the hash (#) symbol to start writing a comment.

It extends up to the newline character. Comments are for programmers to better understand a program. Python Interpreter ignores comments.

#This is a comment
#print out Hello
print('Hello')

1.3.1 Multi-line comments

We can have comments that extend up to multiple lines. One way is to use the hash(#) symbol at the beginning of each line. For example:

#This is a long comment
#and it extends
#to multiple lines

Another way of doing this is to use triple quotes, either ‘’’ or “””.

These triple quotes are generally used for multi-line strings. But they can be used as a multi-line comment as well. Unless they are not docstrings, they do not generate any extra code.

"""This is also a
perfect example of
multi-line comments"""

2.Python Data Types

Built-in Data Types

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

2.1 Numbers

Python numbers variables are created by the standard Python method:

var = 382

Most of the time using the standard Python number type is fine. Python will automatically convert a number from one type to another if it needs. But, under certain circumstances that a specific number type is needed (ie. complex, hexidecimal), the format can be forced into a format by using additional syntax in the table below:

Type Format Descriptionint a = 10 Signed Integerlong a = 345L (L) Long integers, they can also be represented in octal and hexadecimalfloat a = 45.67 (.) Floating point real valuescomplex a = 3.14J (J) Contains integer in the range 0 to 255.

Most of the time Python will do variable conversion automatically. You can also use Python conversion functions (int(), long(), float(), complex()) to convert data from one type to another. In addition, the type function returns information about how your data is stored within a variable.

message = "Good morning"
num = 85
pi = 3.14159
print(type(message)) # This will return a string
print(type(n)) # This will return an integer
print(type(pi)) # This will return a float

2.2 String

Create string variables by enclosing characters in quotes. Python uses single quotes ' double quotes " and triple quotes """ to denote literal strings. Only the triple quoted strings """ also will automatically continue across the end of line statement.

firstName = 'john'
lastName = "smith"
message = """This is a string that will span across multiple lines. Using newline characters
and no spaces for the next lines. The end of lines within this string also count as a newline when printed"""

Strings can be accessed as a whole string, or a substring of the complete variable using brackets ‘[]’. Here are a couple examples:

var1 = 'Hello World!'
var2 = 'RhinoPython'
print var1[0] # this will print the first character in the string an `H`
print var2[1:5] # this will print the substring 'hinoP`

Python can use a special syntax to format multiple strings and numbers. The string formatter is quickly covered here because it is seen often and it is important to recognize the syntax.

print "The item {} is repeated {} times".format(element,count))

The {} are placeholders that are substituted by the variables element and count in the final string. This compact syntax is meant to keep the code more readable and compact.

Python is currently transitioning to the format syntax above, but python can use an older syntax, which is being phased out, but is still seen in some example code:

print "The item %i is repeated %i times"% (element,count)

2.3 List

Lists are a very useful variable type in Python. A list can contain a series of values. List variables are declared by using brackets [ ] following the variable name.

A = [ ] # This is a blank list variable
B = [1, 23, 45, 67] # this list creates an initial list of 4 numbers.
C = [2, 4, 'john'] # lists can contain different variable types.

All lists in Python are zero-based indexed. When referencing a member or the length of a list the number of list elements is always the number shown plus one.

mylist = ['Rhino', 'Grasshopper', 'Flamingo', 'Bongo']
B = len(mylist) # This will return the length of the list which is 3. The index is 0, 1, 2, 3.
print mylist[1] # This will return the value at index 1, which is 'Grasshopper'
print mylist[0:2] # This will return the first 3 elements in the list.

You can assign data to a specific element of the list using an index into the list. The list index starts at zero. Data can be assigned to the elements of an array as follows:

mylist = [0, 1, 2, 3]
mylist[0] = 'Rhino'
mylist[1] = 'Grasshopper'
mylist[2] = 'Flamingo'
mylist[3] = 'Bongo'
print mylist[1]

Lists aren’t limited to a single dimension. Although most people can’t comprehend more than three or four dimensions. You can declare multiple dimensions by separating an with commas. In the following example, the MyTable variable is a two-dimensional array :

MyTable = [[], []]

In a two-dimensional array, the first number is always the number of rows; the second number is the number of columns.

2.4 Tuple

Tuples are a group of values like a list and are manipulated in similar ways. But, tuples are fixed in size once they are assigned. In Python the fixed size is considered immutable as compared to a list that is dynamic and mutable. Tuples are defined by parenthesis ().

myGroup = ('Rhino', 'Grasshopper', 'Flamingo', 'Bongo')

Here are some advantages of tuples over lists:

  1. Elements to a tuple. Tuples have no append or extend method.
  2. Elements cannot be removed from a tuple.
  3. You can find elements in a tuple, since this doesn’t change the tuple.
  4. You can also use the in operator to check if an element exists in the tuple.
  5. Tuples are faster than lists. If you’re defining a constant set of values and all you’re ever going to do with it is iterate through it, use a tuple instead of a list.
  6. It makes your code safer if you “write-protect” data that does not need to be changed.

It seems tuples are very restrictive, so why are they useful? There are many datastructures in Rhino that require a fixed set of values. For instance a Rhino point is a list of 3 numbers [34.5, 45.7, 0]. If this is set as tuple, then you can be assured the original 3 number structure stays as a point (34.5, 45.7, 0). There are other datastructures such as lines, vectors, domains and other data in Rhino that also require a certain set of values that do not change. Tuples are great for this.

2.5 Dictionary

Dictionaries in Python are lists of Key:Value pairs. This is a very powerful datatype to hold a lot of related information that can be associated through keys. The main operation of a dictionary is to extract a value based on the key name. Unlike lists, where index numbers are used, dictionaries allow the use of a key to access its members. Dictionaries can also be used to sort, iterate and compare data.

Dictionaries are created by using braces ({}) with pairs separated by a comma (,) and the key values associated with a colon(:). In Dictionaries the Key must be unique. Here is a quick example on how dictionaries might be used:

room_num = {'john': 425, 'tom': 212}
room_num['john'] = 645 # set the value associated with the 'john' key to 645
print (room_num['tom']) # print the value of the 'tom' key.
room_num['isaac'] = 345 # Add a new key 'isaac' with the associated value
print (room_num.keys()) # print out a list of keys in the dictionary
print ('isaac' in room_num) # test to see if 'issac' is in the dictionary. This returns true.

3. Python Input, Output and Import

We use the print() function to output data to the standard output device (screen). We can also output data to a file, but this will be discussed later.

An example of its use is given below.

print('This sentence is output to the screen')

Output

This sentence is output to the screen

Another example is given below:

a = 5
print('The value of a is', a)

Output

The value of a is 5

In the second print() statement, we can notice that space was added between the string and the value of variable a. This is by default, but we can change it.

The actual syntax of the print() function is:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Here, objects is the value(s) to be printed.

The sep separator is used between the values. It defaults into a space character.

After all values are printed, end is printed. It defaults into a new line.

The file is the object where the values are printed and its default value is sys.stdout (screen). Here is an example to illustrate this.

print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')

Output

1 2 3 4
1*2*3*4
1#2#3#4&

3.1Output formatting

Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format() method. This method is visible to any string object.

>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10

Here, the curly braces {} are used as placeholders. We can specify the order in which they are printed by using numbers (tuple index).

print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))

Output

I love bread and butter
I love butter and bread

We can even use keyword arguments to format the string.

>>> print('Hello {name}, {greeting}'.format(greeting = 'Goodmorning', name = 'John'))
Hello John, Goodmorning

We can also format strings like the old sprintf() style used in C programming language. We use the % operator to accomplish this.

>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

3.2 Python Input

Up until now, our programs were static. The value of variables was defined or hard coded into the source code.

To allow flexibility, we might want to take the input from the user. In Python, we have the input() function to allow this. The syntax for input() is:

input([prompt])

where prompt is the string we wish to display on the screen. It is optional.

>>> num = input('Enter a number: ')
Enter a number: 10
>>> num
'10'

Here, we can see that the entered value 10 is a string, not a number. To convert this into a number we can use int() or float() functions.

>>> int('10')
10
>>> float('10')
10.0

This same operation can be performed using the eval() function. But eval takes it further. It can evaluate even expressions, provided the input is a string

>>> int('2+3')
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2+3'
>>> eval('2+3')
5

3.3 Python Import

When our program grows bigger, it is a good idea to break it into different modules.

A module is a file containing Python definitions and statements. Python modules have a filename and end with the extension .py.

Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use the import keyword to do this.

For example, we can import the math module by typing the following line:

import math

We can use the module in the following ways:

import math
print(math.pi)

Output

3.141592653589793

Now all the definitions inside math module are available in our scope. We can also import some specific attributes and functions only, using the from keyword. For example:

>>> from math import pi
>>> pi
3.141592653589793

While importing a module, Python looks at several places defined in sys.path. It is a list of directory locations.

>>> import sys
>>> sys.path
['',
'C:\\Python33\\Lib\\idlelib',
'C:\\Windows\\system32\\python33.zip',
'C:\\Python33\\DLLs',
'C:\\Python33\\lib',
'C:\\Python33',
'C:\\Python33\\lib\\site-packages']

4. Python Operators

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Identity operators
  • Membership operators
  • Bitwise operators

4.1 Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

4.2 Python Assignment Operators

Assignment operators are used to assign values to variables:

4.3 Python Comparison Operators

Comparison operators are used to compare two values:

4.4 Python Logical Operators

Logical operators are used to combine conditional statements:

4.5 Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:

5. Python Namespace and Scope

To simply put it, a namespace is a collection of names.

In Python, you can imagine a namespace as a mapping of every name you have defined to corresponding objects.

Different namespaces can co-exist at a given time but are completely isolated.

A namespace containing all the built-in names is created when we start the Python interpreter and exists as long as the interpreter runs.

This is the reason that built-in functions like id(), print() etc. are always available to us from any part of the program. Each module creates its own global namespace.

These different namespaces are isolated. Hence, the same name that may exist in different modules does not collide.

5.1.1 Python Variable Scope

Although there are various unique namespaces defined, we may not be able to access all of them from every part of the program. The concept of scope comes into play.

A scope is the portion of a program from where a namespace can be accessed directly without any prefix.

At any given moment, there are at least three nested scopes.

  1. Scope of the current function which has local names
  2. Scope of the module which has global names
  3. Outermost scope which has built-in names

When a reference is made inside a function, the name is searched in the local namespace, then in the global namespace and finally in the built-in namespace.

If there is a function inside another function, a new scope is nested inside the local scope.

Example of Scope and Namespace in Python

def outer_function():
b = 20
def inner_func():
c = 30
a = 10

Here, the variable a is in the global namespace. Variable b is in the local namespace of outer_function() and c is in the nested local namespace of inner_function().

When we are in inner_function(), c is local to us, b is nonlocal and a is global. We can read as well as assign new values to c but can only read b and a from inner_function().

If we try to assign as a value to b, a new variable b is created in the local namespace which is different than the nonlocal b. The same thing happens when we assign a value to a.

However, if we declare a as global, all the reference and assignment go to the global a. Similarly, if we want to rebind the variable b, it must be declared as nonlocal. The following example will further clarify this.

def outer_function():
a = 20
def inner_function():
a = 30
print('a =', a)
inner_function()
print('a =', a)
a = 10
outer_function()
print('a =', a)

As you can see, the output of this program is

a = 30
a = 20
a = 10

In this program, three different variables a are defined in separate namespaces and accessed accordingly. While in the following program,

def outer_function():
global a
a = 20
def inner_function():
global a
a = 30
print('a =', a)
inner_function()
print('a =', a)
a = 10
outer_function()
print('a =', a)

The output of the program is.

a = 30
a = 30
a = 30

Here, all references and assignments are to the global a due to the use of keyword global.

6.Python Flow Control Statements

What are the Flow Control Statements?

A Flow Control Statement defines the flow of the execution of the Program.

There are 6 different types of flow control statements available in Python:

  1. if-else
  2. Nested if-else
  3. for
  4. while
  5. break
  6. Continue

Let’s learn about these all statements in detail.

6.1 if-else

If-else is used for decision making; when code statements satisfy the condition, then it will return non-zero values as true, or else zero or NONE value as false, by the Python interpreter.

Syntax

  1. if(<condition>):
  2. Statement 1
  3. else:
  4. Statement 2

6.2 Nested if-else

With if…elif…else, elif is a shortened form of else if. It works the same as ‘if’ statements, where the if block condition is false then it checks to elif blocks. If all blocks are false, then it executes an else statement. There are multiple elif blocks possible for a Nested if…else.

Syntax

  1. if (<condition 1>):
  2. Statement 1
  3. elif (<condition 2>):
  4. Statement 2
  5. else
  6. Statement 3

6.3 for Statement

The for loop statement has variable iteration in a sequence(list, tuple or string) and executes statements until the loop does not reach the false condition.

Syntax

  1. for value in sequence:
  2. …body statement of for

6.4 while loop

A while loop is used in python to iterate over the block of expression which matches to true. Non-zero values are True and zero and negative values are False, as interpreted in Python.

Syntax

  1. while(<condition>):
  2. statement 1..

6.5 Break statement

The Python Break statement is used to break a loop in a certain condition. It terminates the loop. Also, we can use it inside the loop then it will first terminate the innermost loop.

Syntax

I. break

II. with for loop

  1. for value in sequence:
  2. …body statement of for
  3. if(<condition>):
  4. break
  5. …body statement of for loop
  6. …body statement outside of for loop

II. with a while loop

  1. while(<condition>):
  2. statement 1…
  3. if(<condition>):
  4. break
  5. …Statement of while loop
  6. ….Statements outside while loop

6.6 Continue Statement

A continue statement won’t continue the loop, it executes statements until the condition matches True.

Syntax

I. continue

II. with for loop

  1. for value in sequence:
  2. …body statement of for
  3. if(<condition>):
  4. continue
  5. …body statement of for loop
  6. …body statement outside of for loop

III. with the while loop

  1. while(<condition>):
  2. statement 1…
  3. if(<condition>):
  4. continue
  5. …Statement of while loop
  6. …Statements outside while loop

--

--

No responses yet