# Introduction to the Python language¶

The lectures (more or less) the official Python tutorials.

• Python is a general purpose, high level programmng languge.
• One of its principles is readability through a very clean syntax.
• It was created in 1991 by Guido Van Rossum.
• Its name was inspired by Monthy Python, not the reptile.

## Why Python?¶

### Pros¶

• Easy-to-learn, steep learning curve, interactive, good for beginners (Raspberry Pi)
• Well readable code, simple commands for high level functionality
• Runs ion almost every platforms, portable code
• Object Oriented (OOP)
• Good for web applications (Google, Yahoo, IBM, NASA, Disney, Dropbox, ...)
• Quick to write, concise code, suitable for great projects, too
• Great community, open source codebase
• Leading programming languge in data science
• Open source, free (as in free beer and free speech

### Cons¶

• Slow
• Not ideal for mobile apps
• Not suitable for graphical (3D) computing

# Run¶

• python is a so called interpreted language
• Ones code cannot run in its own, you need an other program to interpret it: an interpreter
• The interpreter is a binary executable (it was not written in binary code, rather it was compiled to a binary code)
• The python code is (more or less) OS independent, but the interpreter is not.

There are several ways to run a python code.

### Command line¶

For example, interactively:  $python  This opens a prompt, you can type commands here. One can run a given set of python commands from a file (a python script, .py extension): $ python hello.py  This runs all the commands in the .py file, the output (is any) is printed on the console.

The interpreted is the python(.exe) executable here.

### Jupyter (IPython) notebook¶

Jupyter is a browser based interface, which is in close resemblance to the Sage notebooks from last semester.

You can start your own web server, on leibniz:  $ipython notebook --port=##### --no-browser --ip=127.0.0.1  Where ##### is a port number ranging from 9000 to 20000. Then you can look your notebooks on the address localhost:##### in your web-browser. This starts a program which handles the interface in yout browser and this program starts other interpreters (kernels), depending on your usage. But ipython is an interpreter itself. In newer versions ipython notebook is replaces with jupyter notebook (it's easier from your own computer). Jupyter can run multiple kernels, not even with the same programming language, for example Python, Sage and there are several others. ### Spyder¶ Spyder is an graphical development environment for python, it is installed on leibniz, but you can install it on your own machine, for any operating system. This is not an interpreter, rather a graphical insterface to comfortably write and run your code, it has to use and interpreter though. ### At home¶ I advise to use Anaconda. It is available on all of the major desktop OSs (Linux, Mac, Windows) • choose your OS • choose version 2.7 (we use this because this is installed on leibniz, but there are newer versions) • Mind the 32/64 bits Anaconda contains command line (python, ipython), notebook (jupyter) and graphical (Spyder) environments, not to mention a lots of useful libraries, tools and packages. # Basic objects¶ The objects are the building blocks of the language. Every object has a type. Let's start with the following types: • int (integer): 2354, -12 • float (floating point): 1.0, -23.567, 2.3E4 • bool (boolean): True, False • str (string): "puppy", "once upon a time there was a puppy" The type can be acquired with the type command. In [1]: type(5.0)  Out[1]: float ## Operations, expressions¶ Operations operate on object, resulting an expression, the result can ha ve a different (but well specified) type. Integer and float operations: • a + b addition • a - b subtraction • a * b multiplication • a / b division (in Python2.7 int/int = int, but from Python3 int/int = float) • a // b integer division • a % b remainder, modulo • a ** b power (unlike Sage a ^ b !) • a == b, a < b, a > b, a <= b, a >= b, a != b, a <> b result bool Boolean operations on boolean objects: • a and b • a or b • not a String operations: • a + b, concatenation • a in b, inclusion (results bool) ### Example¶ In [2]: 5 + 11  Out[2]: 16 In [3]: 2 ** 251  Out[3]: 3618502788666131106986593281521497120414687020801267626233049500247285301248L In [4]: a = 54 b = a - 50 a * b  Out[4]: 216 In [5]: 54 > 12  Out[5]: True In [6]: b < 0  Out[6]: False In [7]: 54 > 12 or b < 0  Out[7]: True In [8]: s = "puppy" "pup" in s  Out[8]: True In [9]: s = "little " + s s  Out[9]: 'little puppy' # Variables¶ • A variable name can start either with underscore or letter: [_a-zA-Z] • it can be folowed by any number of letters, or numbers, or underscores: [_a-zA-Z0-9] • in theory, a name can be arbitrarily long • name cannot be reserver word (later) • Case sensitive: val1 and Val1 differ ## Strings¶ There are tree ways of constructing a string literal. In [10]: s = "puppy" type(s)  Out[10]: str In [11]: s = 'puppy' type(s)  Out[11]: str In [12]: s = """Once upon a time there was a puppy. Elment a vásárba fél pénzzel! """ type(s)  Out[12]: str In [13]: s  Out[13]: 'Once upon a time\nthere was a puppy.\nElment a v\xc3\xa1s\xc3\xa1rba f\xc3\xa9l p\xc3\xa9nzzel!\n' You can see the control characters (\n is new line) and UTF-8 byte codes (á=c3a1, \x is followed by a hexa code). The print command prints it in a readable format. In [14]: print s  Once upon a time there was a puppy. Elment a vásárba fél pénzzel!  The first two quotions are for using quotion marks in a string. You can use a quotion mark if it is not the one used to mark string literal. Example: In [15]: print "One 'quotion' mark, " + 'two "quotion" marks'  One 'quotion' mark, two "quotion" marks  If you want to use the same quotion mark as the string mark, then use escape characters: In [16]: 'there is this: \' and this: "'  Out[16]: 'there is this: \' and this: "' In [17]: print 'there is this: \' and this: "'  there is this: ' and this: "  In the third type you can use line breaks, in the others you have to use escape character for newlines (\n). Other special (escape) characters: \\\\ (\\), \' ('), \" ("), \n (new line), \t (tab) # Printing¶ In Jupyter notebooks, the last result is printed after every cell, but if you run a python program you have to use the print command. If you want to see more values in one cell, you have to use print, too. In [18]: 5 + 8 5 + 7  Out[18]: 12 In [19]: a = 5 print a a = 15 print a * 2 a  5 30  Out[19]: 15 In [20]: string = "puppy" "I had a " + string  Out[20]: 'I had a puppy' In [21]: print "Once upon a time there was a %s who liked to bark." % string  Once upon a time there was a puppy who liked to bark.  If a string contains %s and % after it, then the latter is substitued in the place of %s. You can do more substitutions: In [22]: print "%s upon a time there was a %s who liked to %s." % ("Once", "puppy", "bark")  Once upon a time there was a puppy who liked to bark.  You can substitute other types not just strings: In [23]: print """The %d is a decimal integer, the %f is a float number.""" % (23, 1.0/3)  The 23 is a decimal integer, the 0.333333 is a float number.  % type example result %s string "Once upon a time there was a %s" % "puppy" "Once upon a time there was a puppy" %d integer "%d upon a time there was a puppy" % 1 "1 upon a time there was a puppy" %f float "Once upon a time there were %f puppies" % math.pi "Once upon a time there were 3.141593 puppies" "There were %d %s and they had to share %f fl.oz. milk" % (3, 'puppies', math.pi) "There were 3 puppies and they had to share 3.141593 fl.oz. milk" You can print more thing in one line, just use a comma separated list, print will use a space separator. If you want to continue a line, end the print command with a comma. Empty print begins a new line. In [24]: print 1, 3.14, "puppy" print "cat", print "camel", print print "EOT"  1 3.14 puppy cat camel EOT  # Input¶ Since we know how to output things, we learn how to read input. In [25]: raw_input()  cat  Out[25]: 'cat' This is an annoyingly polite piece of code: In [26]: a = 5 nev = raw_input("Your name, please! ") print "Hi %s\nnice to meet you!" % nev  Your name, please! Gábor Hi Gábor nice to meet you!  In [27]: input() > 10  5  Out[27]: False In [28]: input() ** 10  5  Out[28]: 9765625 The difference between raw_input and input: In [29]: a = raw_input() a + " cats"  5  Out[29]: '5 cats' In [30]: b = input() b + " cats"  5  --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-30-e423ee0b3ce5> in <module>() 1 b = input() ----> 2 b + " cats" TypeError: unsupported operand type(s) for +: 'int' and 'str' raw_input always returns a string, input interprets the input: In [31]: type(input())  5.0  Out[31]: float It is worth mentioning that input itself is a security risk: python >>> intput() exit() # Control flows¶ ## Conditional¶ In [32]: x = input() if x < 0: print "this is negative" elif x == 0: print "this is zero" elif x == 1: print "this is one" else: print "this is many"  5 this is many  You can have more than one elif branches but neither elif nor else is mandatory. If the first condition is met (expression evaluates to True) then the first block (marked with an ident) is executed. If not then the first elif which evaluates to True. If neither of those, then the else branch (if there is such a branch). The ident is mandatory, that marks the block, one ident is usually 4 spaces deep. ## While loop¶ In [33]: n = 1000 a = 1 while a ** 3 <= n: print a ** 3, # comma continues the line a = a + 1 print "end"  1 8 27 64 125 216 343 512 729 1000 end  The while block is executed as while as the condition is evaluated to True. The former example increases the variable a as long as its cube is not greater than 1000. One can embed control flows into each other. The famous Collatz- or$3x+1\$-conjecture:

In [34]:
a = input()
while a != 1:
print a,  # comma continues the line
if a % 2 == 0:
a = a / 2
else:
a = a * 3 + 1

10
10 5 16 8 4 2


We need to go deeper!

In [35]:
a = input()
if type(a) == int:
while a != 1:
print a,  # comma continues the line
if a % 2 == 0:
a = a / 2
else:
a = a * 3 + 1
else:

10.1


The above code checks for integer input. Better to prepare for the worst. What if somebody gives a negative input?

In [36]:
a = input()
if type(a) == int:
if a < 0:
a = -1 * a
while a != 1:
print a,  # comma continues the line
if a % 2 == 0:
a = a / 2
else:
a = a * 3 + 1
else:

-5
5 16 8 4 2


Finaly, we have to exclude 0, because the conjecture doesn't work for that:

In [37]:
a = input()
if type(a) == int and a != 0:
if a < 0:
a = -1 * a
while a != 1:
print a,  # comma continues the line
if a % 2 == 0:
a = a / 2
else:
a = a * 3 + 1
else:

0


# Break¶

You can use break within loops, this command unconditionally and immediately escapes the given block and continues as if the loop would have ended.

In [38]:
n = input("Give a whole square under 10000! ")
a = 0
while a ** 2 < 10000:
if a ** 2 == n:
break
a = a + 1
if a ** 2 < 10000:
print "its square root is %d" % a
else:
print "You lied! :("

Give a whole square under 10000! 100
its square root is 10


In case of nested loops, break escapes the innermost loop.