Python
Python is an object-oriented programming language created by Guido Rossum in 1989. It is ideally designed for rapid prototyping of complex applications. It has interfaces to many OS system calls and libraries and is extensible to C or C++. Many large companies use the Python programming language include NASA, Google, YouTube, BitTorrent, etc.
Python is widely used in Artificial Intelligence, Natural Language Generation, Neural Networks and other advanced fields of Computer Science. Python had deep focus on code readability & this class will teach you python from basics.
- Portability
Python runs everywhere, and porting a program from Linux to Windows or Mac is usually just a matter of fixing paths and settings.
- Developer productivity
Python program is typically one-fifth to one-third the size of equivalent Java or C++ code. This means the job gets done faster.
- An extensive library
Python has an incredibly wide standard library
- Software quality
Python is heavily focused on readability, coherence, and quality. The language uniformity allows for high readability and this is crucial nowadays where code is more of a collective effort than a solo experience.
- Software integration
Another important aspect is that Python can be extended and integrated with many otherlanguages, which means that even when a company is using a different language as their mainstream tool, Python can come in and act as a glue agent between complex applications that need to talk to each other in some way.
Python is used in many different contexts, such as system programming, web programming, GUI applications, gaming and robotics, rapid prototyping, system integration, data science, database applications, and much more.
Python is used in many different contexts, such as system programming, web programming, GUI applications, gaming and robotics, rapid prototyping, system integration, data science, database applications, and much more.
What are the drawbacks?
Probably, the only drawback that one could find in Python, which is not due to personal preferences, is the execution speed. Typically, Python is slower than its compiled brothers. The standard implementation of Python produces, when you run an application, a compiled version of the source code called byte code (with the extension
.pyc
), which is then run by the Python interpreter. The advantage of this approach is portability, which we pay for with a slowdown due to the fact that Python is not compiled down to machine level as are other languages.Installing Python
Python is fully integrated and most likely already installed in basically almost every Linux distribution. If you have a Mac, it's likely that Python is already there as well (however, possibly only Python 2.7), whereas if you're using Windows, you probably need to install it.
The place you want to start is the official Python website: https://www.python.org. This website hosts the official Python documentation and many other resources that you will find very useful. Take the time to explore it.
Find the download section and choose the installer for your OS. If you are on Windows, make sure that when you run the installer, you check the option
install pip
To open the console in Windows, go to the Start menu, choose Run, and type cmd
.
Whatever console you open, type python
at the prompt, and make sure the Python interactive shell shows up. Type exit()
to quit.
Running a Python program
Python contains modules and packages. Modules are the functions and packages are built in functions.
In Python, to calculate the factorial of number 5, we just need the following code:
>>> from math import factorial >>> factorial(5) 120
Lets print integer, string and array
>>> n = 3 # integer number >>> address = "Bangalore, India" # S. Holmes >>> employee = {'age': 20,'Name': 'Python'}
To print, just type variables
>>> n
3
>>> address
A namespace is therefore a mapping from names to objects. Examples are the set of built-in names (containing functions that are always accessible for free in any Python program), the global names in a module, and the local names in a function. Even the set of attributes of an object can be considered a namespace.
A scope is a textual region of a Python program, where a namespace is directly accessible.
There are four different scopes that Python makes accessible (not necessarily all of them present at the same time, of course):
- The local scope, which is the innermost one and contains the local names.
- The enclosing scope, that is, the scope of any enclosing function. It contains non-local names and also non-global names.
- The global scope contains the global names.
- The built-in scope contains the built-in names. Python comes with a set of functions that you can use in a off-the-shelf fashion, such as
print
,all
,abs
, and so on. They live in the built-in scope.
Creating and running a simple scope program
scopes1.py
# Local versus Global # we define a function, called local def local(): m = 7 print(m) m = 5 print(m) # we call, or `execute` the function local local()
Running the program from your command prompt
python scopes1.py
We see two numbers printed on the console:
5
and 7
Object and classes
bike.py# let's define the class Bike class Bike: def __init__(self, colour, frame_material): self.colour = colour self.frame_material = frame_material def brake(self): print("Braking!") # let's create a couple of instances red_bike = Bike('Red', 'Carbon fiber') blue_bike = Bike('Blue', 'Steel') # let's inspect the objects we have, instances of the Bike class. print(red_bike.colour) # prints: Red print(red_bike.frame_material) # prints: Carbon fiber print(blue_bike.colour) # prints: Blue print(blue_bike.frame_material) # prints: Steel # let's brake! red_bike.brake() # prints: Braking!
The first method,
__init__
is an initializer. It uses some Python magic to set up the objects with the values we pass when we create it.Built in Datatypes
- int : Integer numbers
- bool : Boolean, true or false
- sys.float_info : floating point numbers
- fractions : Fractions hold a rational numerator and denominator in their lowest forms.
- decimal : Floating numbers with more precission
Tuples
A tuple is a sequence of arbitrary Python objects. In a tuple, items are separated by commas.
>>> one_element_tuple = (42, ) # you need the comma! >>> three_elements_tuple = (1, 3, 5) >>> a, b, c = 1, 2, 3 # tuple for multiple assignment >>> a, b, c # implicit tuple to print with one instruction (1, 2, 3) >>> 3 in three_elements_tuple # membership test True
Lists
Lists are commonly used to store collections of homogeneous objects, but there is nothing preventing you to store heterogeneous collections as well.
>>> list((1, 3, 5, 7, 9)) # list from a tuple [1, 3, 5, 7, 9] >>> list('hello') # list from a string ['h', 'e', 'l', 'l', 'o']
List have following functions append, count, extend, index, insert, pop, reverse, sort, clear, min, max, sum, len
>>> a = [1, 2, 1, 3]
>>> a.append(13) # we can append anything at the end >>> a
Set
Stored collection of objects
>>> small_primes = set() # empty set
>>> small_primes.add(2) # adding one element at a time
>>> small_primes.add(3)
>>> small_primes.add(5)
>>> small_primes
{2, 3, 5}
>>> small_pr
Dictionaries
A dictionary maps keys to values. Keys need to be hashable objects, while values can be of any arbitrary type.
>>> a = dict(A=1, Z=-1)
Iterations and Decisions making
If, Elif, Else
#ifelse.py income = 15000 if income < 10000: tax_coefficient = 0.0 #1 elif income < 30000: tax_coefficient = 0.2 #2 elif income < 100000: tax_coefficient = 0.35 #3 else: tax_coefficient = 0.45 #4 print('I will pay:', income * tax_coefficient, 'in taxes')
Output
$ python taxes.py
I will pay: 3000.0 in taxes
for loop
for number in [0, 1, 2, 3, 4]: print(number)
while loop
position = 10 while position < 0: position -= 1
Function
A function in Python is defined by using the
def
keyword, after which the name of the function follows, terminated by a pair of braces (which may or may not contain input parameters) and, finally, a colon (:
) signals the end of the function definition line. Immediately afterwards, indented by four spaces, we find the body of the function, which is the set of instructions that the function will execute when called.x = 3 def func(y): print(y) func(x) # prints: 3
Built-in functions
Python comes with a lot of built-in functions. They are available anywhere and you can get a list of them by inspecting the
builtin
module with dir(__builtin__)
, or by going to the official Python documentation. Unfortunately, I don't have the room to go through all of them here. Some of them we've already seen, such as any
, bin
, bool
, divmod
, filter
, float
, getattr
, id
, int
, len
, list
, min
, print
, set
, tuple
, type
, and zip
, but there are many more, which you should read at least once.
Adding comment or documenting the code
def square(n): """Return the square of a number n. """ return n ** 2 def get_username(userid): """Return the username of a user given their id. """ return db.get(user_id=userid).username
Importing objects
from lib.funcdef import square, cube print(square(10)) print(cube(10))
Class and Objects
Python is based on Object Oriented Programming (OOP), Python supports all OOPs conepts like Class, Object, polymorphism , Inheritance, static class and methods. The two main players in OOP are objects and classes. Classes are used to create objects (objects are instances of the classes with which they were created), so we could see them as instance factories. When objects are created by a class, they inherit the class attributes and methods. They represent concrete items in the program's domain.
class Square(): side = 8 def area(self): # self is a reference to an instance return self.side ** 2 sq = Square() print(sq.area()) # 64 (side is found on the class) print(Square.area(sq)) # 64 (equivalent to sq.area()) sq.side = 10 print(sq.area()) # 100 (side is found on the instance)