<jupyter_start><jupyter_text>Python Introduction  Python is a clear and powerful object-oriented programming language, comparable to Perl, Ruby and Java.- [python](https://www.python.org/)  ![cation](https://realpython.com/learn/python-first-steps/images/pythonlogo.jpg)- [Monty Python](https://en.wikipedia.org/wiki/Monty_Python)  ![mayavi](http://wfiles.brothersoft.com/m/monty_python_and_the_holy_grail_59205-1920x1200.jpg) In python we are using an elegant syntax with indentation instead of brackets for code structuring. This makes python easy to read and ideal for prototype development and scripting.A python interactive mode makes it easy to test short snippets of code, but there are also a bunch of editors like Sublime Text available as well as bundled development environments IDEs like PyCharm.  SoftwareWe will use:    - Python (https://www.python.org/)    - IPython (http://ipython.org/)    - IPython Notebook (http://ipython.org/notebook.html)    You could use:    - an editor of your choice like Sublime Text    - an IDE (PyCharm)    - Python debuggers (pdb)    - Code checkers (pylint)  We will discuss:- Variables- Objects- Strings- Lists- Dictionaries- Functions- Import of modules  Interactive modeStart the python command line interpreter by typing `python`, or the Python interactive shell by typing `ipython` into your terminal.You can use this a calculator:<jupyter_code>2 + 3<jupyter_output><empty_output><jupyter_text>or print this:<jupyter_code>print ("Hello World")<jupyter_output>Hello World<jupyter_text>Variables you can assign number to variables like:<jupyter_code>height = 1
width = 2
print (height)
print (width)<jupyter_output>1
2<jupyter_text>and you can reuse this variables<jupyter_code>add_height_width = height + width
print (add_height_width)<jupyter_output>3<jupyter_text>you can change variables<jupyter_code>width = 12
add_height_width = height + width
print (add_height_width)<jupyter_output>13<jupyter_text>Naming Rules- Variables can only contain letters, numbers, and underscores. - Variable names cannot start with a number but should start with a letter or an underscore.- Spaces are not allowed in variable names -> use underscores instead of spaces.- It should be avoided to use Python keywords as variable names like int, float, list, input- Variable names should be descriptive, without being too long. For example `n_dog_legs` is better than just `dog` or `number_of_legs_of_a_dog`.- Never use singe letters like a, b, c as variable names  Datatypes  int/floats<jupyter_code>height
height/2<jupyter_output><empty_output><jupyter_text>type conversion<jupyter_code>float(height)
2.<jupyter_output><empty_output><jupyter_text>String Strings are sets of characters and are contained either in single or double quotes.<jupyter_code>text = "this is a string"
print (text)<jupyter_output>this is a string<jupyter_text>Through this we are able to create strings which contains quotes.<jupyter_code>text = 'this is a string "containing a quote"'
print (text)<jupyter_output>this is a string "containing a quote"<jupyter_text>We can also use multiple line strings in triple quotes ''' or """<jupyter_code>text = """this is a string 
over
more 
than one line
"""
print (text)<jupyter_output>this is a string 
over
more 
than one line<jupyter_text>You can also concatenate strings with the + command<jupyter_code>first_part = "this is the first part ... "
second_part = "and this is the second part of the text"
concat = first_part + second_part
print(concat)<jupyter_output>this is the first part ... and this is the second part of the text<jupyter_text>If you want a specific number of repetitions of a text you can use the * command followed by a number.<jupyter_code>"example " * 3<jupyter_output><empty_output><jupyter_text>List An other data type is the list or array. you can initialise it like:<jupyter_code>list_var = []
print (list_var)<jupyter_output>[]<jupyter_text>but you can also fill it directly with entries.<jupyter_code>list_var = [1,2,3,4]
print (list_var)<jupyter_output>[1, 2, 3, 4]<jupyter_text>indexing and slicing Lists can be indexed or sliced. Important for indexing is, that the index of a list starts with 0. Indexing and slicing works for build-in sequence types like lists or strings.<jupyter_code>list_var[0]
list_var[-1]
print (list_var[0:2])
print (list_var[:2])
list_var[-2:-1]
list_var[0:-1:2]<jupyter_output><empty_output><jupyter_text>You can use indexing to change entries, but this works only for mutable object types like lists not for immutable like strings<jupyter_code>list_var[0] = [1,2,3]
print (list_var)
list_var[::-1]<jupyter_output><empty_output><jupyter_text>append/extend You can also append or extend your list<jupyter_code>list_var.append("wuff")
print (list_var)
list_extention = ["a","b","c"]
list_var.extend(list_extention)
print (list_var)<jupyter_output>[[1, 2, 3], 2, 3, 4, 'wuff', 'a', 'b', 'c']<jupyter_text>Occurrence testing<jupyter_code>'wuff' in list_var
'wiff' in list_var<jupyter_output><empty_output><jupyter_text>Dictionaries Dictionaries are an other data type object structure. A dictionary contains key / value pairs. Instead of the position you use the key to access the respective value.<jupyter_code>dictionary = {'one_key': 1, 'second_key': 2}
print (dictionary)
dictionary['one_key']
dictionary['one_key'] = 21
print (dictionary)
dictionary['third_key'] = 3
print (dictionary)
new_dict = {'one_key':12, 'third_key':14, 'fourth_key': 4}
dictionary.update(new_dict)
print (dictionary)<jupyter_output>{'one_key': 12, 'fourth_key': 4, 'third_key': 14, 'second_key': 2}<jupyter_text>Occurrence testing<jupyter_code>'one_key' in dictionary<jupyter_output><empty_output><jupyter_text>Control structure if/else/elif<jupyter_code>statement = True
if statement is True:
    do something
else:
    do something else
    
    
amount = 12
if amount > 10:
    print ('many')
else:
    print('few')<jupyter_output>many<jupyter_text>BoolValues: True, False    - []         False    - [a, b]     True    - 0          False    - all other  True NoneNone is used to present the absence of a value  Intendation<jupyter_code>test_list = [1,2,3,4,5]
if test_list:
    print ('test_list != []') # list is not empty
print ('always true')
if len(test_list) == 0:
    print ("length is 0")
elif len(test_list) >0 and len(test_list) <= 4:
    print ('length test_list is between 1 and 4')
else:
    print ('length test_List is larger then 4')<jupyter_output>length test_List is larger then 4<jupyter_text>For loop and while loop<jupyter_code>iter_list = ['a', 'b', 'c']
for i in iter_list:
    print (i)
iter_list = [1,2,3,4]
step = 0
while step != len(iter_list):
    print ("value: %i" % step )
    step += 1
step = 0
while step != len(iter_list):
    print (step, iter_list[step])
    step += 1<jupyter_output>0 1
1 2
2 3
3 4<jupyter_text>range and enumerate<jupyter_code>for i in range(3):
    print (i)
for i in range(len(iter_list)):
    print ("%i value:%i" % (i, iter_list[i]))
for i, value in enumerate(iter_list):
    print (i, value)<jupyter_output>0 1
1 2
2 3
3 4<jupyter_text>Dictionaries and For loops<jupyter_code>for key in dictionary:
    print (key, dictionary[key])
for key, value in dictionary.items():
    print (key, value)
for i, key in enumerate(dictionary):
    print (i, key)<jupyter_output>0 one_key
1 fourth_key
2 third_key
3 second_key<jupyter_text>break, continue, pass<jupyter_code>for i in iter_list:
    print (i)
    if i == 3:
        print ('i equal 3 - break')
        break
for i in iter_list:
    print (i)
    if i == 3:
        print ("i equal 3 - continue")
        continue
        print ("behind continue")
for i in iter_list:
    print (i)
    if i == 3:
        pass
        print ("behind pass")<jupyter_output>1
2
3
behind pass
4<jupyter_text>Functions<jupyter_code>def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n.""" # docstring
    a, b = 0, 1  # multiple assignement
    while a < n:
        print (a),  # prevents the newline
        a, b = b, a+b  # another multiple assignement
        
fib(500)<jupyter_output>0
1
1
2
3
5
8
13
21
34
55
89
144
233
377<jupyter_text>The keyword def initialized a function followed by the name and a list of parameters  Documentation stringsYou should put a triple quoted string into the first line after the function definition, containing a description of the function. This is called doc string, and can be used to automatically produce documentation.  return statement<jupyter_code>def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n.""" # docstring
    result = []
    a, b = 0, 1  # multiple assignement
    while a < n:
        result.append(a)
        a, b = b, a+b  # another multiple assignement
    return result
fib_result = fib(500)
print (fib_result)<jupyter_output>[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]<jupyter_text>The `return` statement returns a value from a function. `return` without an expression argument returns `None` as well as falling off the end of a function.  Default Arguments and Keyword Arguments<jupyter_code>def extended_fib(number, default=True, first_number=0, second_number=1):
    """Print a Fibonacci series up to n.""" # docstring
    if default:
        a, b = 0, 1
    else:
        a, b = first_number, second_number  # multiple assignement
    
    while a < number:
        print (a, end=' ')  # space instead of newline
        a, b = b, a+b  # another multiple assignement
extended_fib(500)
extended_fib(500, first_number=55, second_number=89)
extended_fib(500, default=False, first_number=55, second_number=89)<jupyter_output>55 89 144 233 377<jupyter_text>Import of Modules You can import other python packages/modules quite easy with the import function.<jupyter_code>import math<jupyter_output><empty_output><jupyter_text>Afterwards you can use specific functions of the modules.<jupyter_code>math.cos(1)
math.exp(1)<jupyter_output><empty_output><jupyter_text>Coding style***“The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly." - <NAME>, Selected Papers on Computer Science ***  PEP8Style guide for Python codeA style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is most important.  A few rules- never use tabs, always 4 spaces- try to limit lines to 79 characters- use whitespace to make your code more readable<jupyter_code>spam(ham[1], {eggs: 2})        # YES!
spam( ham[ 1 ], { eggs: 2 } )  # NO!!

x, y = y, x     # YES!
x , y = y , x   # NO!!

counter = counter + 1  # YES!
counter=counter+1      # NO!!

result = add(x+1, 3)   # YES!
result = add(x + 1, 3) # YES!


def complex(real, imag=0.0):         # YES!
    return magic(r=real, i=imag)

def complex(real, imag = 0.0):       # NO!!
    return magic(r = real, i = imag)<jupyter_output><empty_output><jupyter_text>- Follow these naming conventions:    - lower_case_under for variables and functions and methods    - WordCap for classes    - ALL_CAPS for constantsAnd of course, there is more: https://www.python.org/dev/peps/pep-0008/  The Zen of Python<jupyter_code>import this<jupyter_output>The Zen of Python, by <NAME>

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
{'fraction_non_alphanumeric': 0.09528907922912205, 'fraction_numerical': 0.02050732992917147, 'mean_word_length': 4.595852534562212, 'pattern_counts': {'":': 0, '<': 117, '<?xml version=': 0, '>': 116, 'https://': 5, 'lorem ipsum': 0, 'www.': 3, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '33', 'dir': 'jupyter-structured-clean-dedup', 'id': '102511', 'license': 'MIT', 'n_tokens_mistral': 4133, 'n_tokens_neox': 3858, 'n_words': 1418, 'path': 'basics/basics.ipynb', 'repo_name': 'wgiese/Fachkurs_Bachelor_WS1617', 'size': '12155'}