-
Notifications
You must be signed in to change notification settings - Fork 6
Beginner Hub
Welcome to the Python_tutorial wiki!
How to execute a simple python command?
Open your terminal and type python, it provides an interactive python environment. Start typing whatever you are familiar with. As an example, type print "Hello World". And this command work if you have python version < 3. For python version >= 3, you have to include parenthesis, such as, python ("Hello World"). Caveat: this tutorial will follow the syntax for python version 2.7.
Python from Anaconda
For this tutorial, I would strongly recommend you to install a different version of python using Anaconda. Here is how you can do it.
After an installation of anaconda, conda environment is accessible. Future part of tutorial would require more packages to install. So, it is better to create an environment and work on that. How to create environment is available here.
It is worthwhile to read the major difference of python with other programming language. Below links provide some ideas about this.
- https://www.educba.com/python-vs-c-plus-plus/
- https://www.geeksforgeeks.org/difference-between-c-and-python/
- https://www.python.org/doc/essays/comparisons/
The main difference can also be seen in the variables definition. As an example, for c++, the variables required to define before it's implementation. On the other hand, in python, it is not necessary to define variables beforehand.
In python mostly there are two types of numerical variables, int and float. They are defined as,
#integer
a = 8
print a
# float
b = 8.7
print b
# different way float definition
c = (float) 9
print c
String variables are defined using single quote or double quote, such as,
first_name = 'jack'
last_name = "rancher"
print first_name +" " + last_name
Check variable type
type(variable name)
Just like other programming language, python use same athematic operators such as +,-,*,/, %, **, //. Some of these act over numeric variable, some act over both numeric and string, and some act on both string and numeric together.
# Try this out
sum_mul = 1+9*15/3
# module
remainder = 17%2
print (remainder)
# string with numeric, try and find error.
print ("my name is " + "jack")
print ("Jack is " + 12 + "years old.")
print ("Jack"*3)
print (3**5)
print ("Jack age is " + "12 years.")
# integer division; gives integer only by truncating the remainder part
print ("integer is ", 5//2)
% operator can be use as formatting operator in the string. For example,
TH1F *h = new TH1F("h","histogram of energy higher than %f energy" %(3.5), 100, 2, 5)
# add multiple variable
e1 = 3
e2 = 5
TH1F *h = new TH1F("h","histogram of energy between %d and %d" %(e1,e2), 100, 2, 5)
# add name of histogram in string
name = histogram
e1 = 3
e2 = 5
TH1F *h = new TH1F("h","%s of energy between %d and %d" %(name,e1,e2), 100, 2, 5)
%f -> floating point numbers
%d -> integers
%s -> String or any object with a string representation
Iteration in python can be done with several options, such as for, while. A for loop can be used to iterate over list or dictionary (these are python data structure; more details will be included later). In contrast to other programming language, such as c++, a for loop does not require the initialization of a variable. A variable i is initialized and incremented in c++ but the looping in python act as for-each, no need to any initialization and incrementation. For example,
# ex:1, for loop
name_list = ['Jack', 'Narvig', 'Katy', 'Honey']
for name in name_list:
print name
# ex:2, for loop
roll_no= [7,9,13,45,34]
for ii in range(len(roll_no)):
print roll_no[ii]
"** range **: is a python function, that acts as (a,b,1). Take values from a to b with increment 1. "
A while loop is another way to iterate in python.
# example
j = 0
while (j < 10):
print j
j += 1 # increment is very important in while loop. Without this it will run forever.
Conditional statement mostly use boolean login, true or false to help guide our decision process. The statement are structure using comparison operators like, >, <, >=, <=, ==. And the conditional statement in control flow is accomplished using keywords such as if, elif, else in python. How to use these, presented in the following examples.
num = 5
if num<5:
print "the number is smaller than 5"
elif num == 5: # elif is short for else if, that is used in `c++`
print "the number is equal to 5."
else:
print "the number is greater than 5"
# if statement are more than two use `elif`, rather in general use `if` and `else`.
Boolean data type in python are True and False. Boolean data type comes with boolean operator(logical), or, and, not in addition to relational operator (above).
name = false
if (name is True):
print ("true statement")
else:
print ("false statement")
Be careful python is case sensitive programming language as like c++ or java
Writing a function in python requires a declaration as def, that take one or more arguments and a return, that returns one or more values. Not like in other programming language, in python it is not necessary to provide data type of the return values.
def name(first, last):
return (first + last)
print name("Johnny", " Wright")
def twoNumber(a,b):
return a,b
print twoNumber(5,6)
Lambda function is often called anonymous function, because this function are defined without any name of the function. The general syntax of lambda function is
lambda argument: expression
Lambda function can have any number of arguments, but it should have only one expression. An example of lambda function,
square = lambda x: x*x
print (square(7))
In python lambda function are used when we need function for short period of time. For instance, lambda function are used to pass argument to the function. Lets implement this statement.
def functionTest(y):
return (lambda x: x*y)
result = function(4)
print (result(3))
In python there a number of powerful built-in collection classes. Some of those are ordered such as List, tuple and strings. Whereas some are unordered such as sets and dictionaries.
In python list are written as square brackets []. All the items within list are delimited with commas. For python, list can be created using any data type together or separately. For example, a python list is [4, 5.5, True, "jack"], is possible. Some basic operation that can be done in python are listed below.
dataList = ["jack", "freezy", "romeo", 6.5, 5.2, 6, True, False, True]
# indexing
dataList[3]
# concatenate
list1 = ["jack", "freezy", "romeo"]
list2 = [6.5, 5.2, 6, True, False, True]
dataList = list1 + list2
# length
len(dataList)
# looping
for item in dataList:
print item
# slicing
dataList[1:4], this gives all items from index 1 to 3 excluding 4.
# range
list(range(4))
list(range(5,20))
list(range(0,35,5))
Beside these there are other methods that list also supports. Such as,
append, insert, pop, sort, reverse, del, index, count, remove
Strings are collection of characters. In python string are assigned using quotation mark (either double or single).
my_string = "MyName"
print (my_string[2])
Since string is a sequence of character, all the basic method that used for list can also be applied to this.
print len(my_string)
Some other important method acts on strings are,
split, upper, lower, find
# some application
my_statement = " I am proud to be a "
my_statement = my_statement.split(); if we are not giving splitting point, the method split from space.
print (len(my_statement))
Strings are similar in some sense with list, but the main difference is, these are immutable while list are mutable. Mutable means, any item of list can be changed while processing. But in string we can not do that. That's why method like append can not be used.
Do we have array in python? The answer is yes, and the initialization of array in python require to be declared. For example,
from numpy import array
a = [1,2,5,8] # list
b = array(a) # array
So, in contrast to list which came out of nowhere in python (inbuilt method), array need to be called from package named numpy. Here are some similarity and difference between list and array.
Similarity;
- Data stored in the similar way within square bracket, and the iteration process is same.
- Indexing is similar as well as slicing.
- Both data types are mutable.
Difference;
- Array stored data in more compact way than list.
- I would say the main difference is, in array we can use athematic operation but not in list. For example,
# Try It Yourself
a = [2,4,6]
b = array(a)
print (b/2)
print (a/2)
The output of array is another array with divided result whereas list spit out an error. In more detail, we will cover during the numpy discussion.
In python tuple is similar to list, the only difference is tuple are immutable, while list are mutable. In general, the tuples are created using parenthesis ( ), where the elements in it are separated by commas. The following examples shows other possible representation of tuples.
my_tuple1 = (3, "double", 8.5, "wrong")
#packing method
my_tuple2 = "right", 3, 6.7, "?"
#unpack
a , b ,c, d = my_tuple2
# single element
my_tuple3 = (4,)
# more definition
my_tuple4 = ([1,2,3], "crazy",("nuts", 3, 5.6))
# indexing +ve and -ve
print (my_tuple4[0][1])
print (my_tuple4[-1][0])
Possible function that is applicable for tuple as of list are count, find. At the end, the question is why tuple, since we have list? The greater strength of tuple is immutable. Think how you can explain advantages of tuple over list, based on this property.
As naming, the python dictionary is arrange in the key, value structure. Where a unique key could have same or different values. The key must be immutable datatype whereas value does not care. Example of definition,
my_dict = {key: value}
# with data
my_dict1 = {'ram':2, 'shyam':3}
# another initialization
my_dict2 = dict([(2,"hero"), (3,6)])
# how to get value; require key
print (my_dict1['ram'])
print (my_dict1.get('ram'))
# want to add element in previously existed dictionary
my_dict1['hari'] = 4
# another way to look the key in dictionary is get function
my_dict1.get('hari')
# lets do a for looping to create dictionary
my_dict3 = {}
for ii in range(2,12,2):
my_dict3[ii]=ii*ii
Lets make more complicated dictionary
animal = {'dog':
{'type':'pet','leg':4,'size':'middle'},
'frog':
{'type':'amphi','leg':4,'size':'small'},
'bird':
{'type':'fly','leg':2,'size':'small'}}
print (animal['dog'][1])
# add another property in dictionary
animal['dog']['height']='medium'
animal['bird']['height']='tiny'
A set is a data type for mutable unordered collections of unique elements. One application of a set is to quickly remove duplicates from a list. For example,
list1 = [1,7,3,2,4,2,9,2]
print (set(list1))
As like list, new element can be added to list, but the method is not append but is add.
list1.add(99)
Since set is mutable, we can use pop method. Due to unordered structure of set, pop gives a random value rather than the last item as in the case of list.
Set can be used to operate the mathematical operation done such as union, intersection and so on.
To read and write a file, python has a builtin function open(), which returns a file object as,
file_object = open("fileName.txt")
We can specify the mode to open a file. For example if we want to read a text file, give r as an argument in the open function. So what are the different modes?
- r -> read
- w -> write
- a -> append
- x -> open a file with exclusive creation, means if file already exist, the opening process will fail.
- t -> open in text mode (default)
- b -> open in binary mode
-
- -> open a file for updating.
Sometimes encoding is necessary to open text files, that need to provide as an argument in the open function as,
file = open("fileName.txt",'r', encoding= 'utf-8')
After file is opened and everything has been completed, don't forget to close file in order to free the memory. File closing is done as file.close().
The safest way to open file is using with command.
with open("fileName.txt",'r',enconding='utf-8') as file:
# use file object to perform further operation
First open file in write mode, w, or a or x. The w mode will overwrite the existing file, whereas a mode allow us to append line in the existing file.
# also can be done using +, to check if file not exist then creat as
with open("writeFile.txt",'w+') as output:
Class are blueprint from which object can be made. A class could have multiple object. In python we define class using the syntax class. And the objects are creating by calling the class.
Defining class,
class TH1F:
# constructor
def __init__(self, name): // self, is inbuilt python namespace is needed
self.name = name
def histogramName(self):
return "Histogram name " + self.name
What is Self?
Parameter self provided in the method is an object, that is used to reference new object of class whenever it create.
Create an object of the class TH1F
h1 = TH1F("my_mom")
print (h1.histogramName())
Any variable or datatype define in class without __ is public. Private datatype includes __. Such as,
class BankAccount:
Previous we discussed in more details about the list and its functionality. In this subsection, we will cover very briefly about what is the list comprehension and how to handle. The list comprehension in python is referred to making a list out of another list by writing a concise form of script. For example;
# I have a list of my expenses of last month, and I want expenses greater than 100 /day.
expenses = [34,67,127,98,101,79]
new_list = []
for item in expenses:
if (item > 100):
new_list.append(item)
# now in concise form
new_list = [item for item in expenses if item > 100]
Awesome!!
dir(__builtins__)
In python, the compound data types such as list, dictionary or tuple are copied in three difference ways. By assignment, using deep copy and using shallow copy. In this section, I will cover explanation of these method using an example. These copying process follow what c++ has pass by value or pass by reference.
Assigning a different name to the preexisting list does not make a copy rather makes two variables point to a list in the memory.
# example of assignment method for copying
score_1 = [32,45,65,89]
score_2 = score_1
print (score_1, "\t", id(score_1))
print (score_2,"\t",id(score_1))
score_1.append(88)
print (score_1)
print (score_2)
A deep copy makes a new and separate copy of an entire object or list with its own unique memory address. This means any change in the original one does not reflect to its copy. The deep copy is done by recursively copying the element to the new list from original list.
A shallow copy makes new address by copying the address of original one rather than copying all the element in the from the original list. This means, when we change some items in the original one, the change reflect to the copied list as well. Both the copy and the original list are dependent of each other. This is similar what we do in c++, pass by references.
# example for deep copy
import copy
score_1 = [33, 67, 54, 87]
score_2 = copy.deepcopy(score_1)
print (score_1, "\t", id(score_1))
print (score_2,"\t", id(score_2))
# shallow copy
score_1 = [33, 67, 54, 87]
score_2 = copy.copy(score_1)
print (score_1, "\t", id(score_1))
print (score_2,"\t", id(score_2))
# difference
score_1 = [33, 67, 54, 87]
score_2 = copy.deepcopy(score_1)
score_1[1] = 45
print (score_1, "\t", id(score_1))
print (score_2,"\t", id(score_2))
# shallow copy
score_1 = [33, 67, 54, 87]
score_2 = copy.copy(score_1)
score_1[1] = 45
print (score_1, "\t", id(score_1))
print (score_2,"\t", id(score_2))
The shallow copy can also be done for list as,
score_1 = [33, 67, 54, 87]
score_2 = score_1[:]
In common language, the shallow copy is the process of making new object of compound data type and inserting the reference of the original data members into it. One caveat about shallow copy can be seen in the following example.
# make shallow copy and append element in it
score_1 = [33, 67, 54, 87]
score_2 = score_1[:]
score_2.append(56)
print (score_1,"\t", score_2)
score_1 = [33, 67, 54, 87]
score_2 = score_1[:]
score_2[0] = 22
print (score_1,"\t", score_2)
It shows the changes is not reflecting in the original list, this is because two list have different pointers. But if we change an element, the individual elements on the copied list has same reference as of original list.
If you need index with item while iterating over python data type (list, tuple,string), then enumerate is a good choice. Lets take a look.
fruits = ['orange', 'apple', 'banana', 'mango']
for ind,fruit in enumerate(fruits):
print ("My best fruits ordered as %d is %s" %(ind, fruit))
While enumerate iterates, it starts from 0. In case we want a different starting point, then that should be given in the enumerate function. Such as,
fruits = ['orange', 'apple', 'banana', 'mango']
for ind,fruit in enumerate(fruits, start=10):
print ("My best fruits ordered as %d is %s" %(ind, fruit))
Here __name__ is simply a builtin variable of python which evaluates the name of current modules. In order to run current module, __name__ variable set the module to the main. One important application of it is seen when the module is imported to another one, then the inside implementation will not be seen while calling that module. Lets make more clear by using an application.
# a module with name hello.py
def hello(name):
print ("Hello ,%s" %name)
if __name__ == '__main__':
hello("Jack Rancher")
# now import this module to another one, hello2.py
from hello import hello
hello("Katy Perry")
While running hello.py, it satisfies name='main', then it gives "Hello , Jack Rancher". But if we run hello2.py, then it only print "Hello , Katy Perry". What happen if we do not include name='main' in the hello.py, run it and give answer.