<jupyter_start><jupyter_text>*This notebook contains an excerpt from the [Whirlwind Tour of Python](http://www.oreilly.com/programming/free/a-whirlwind-tour-of-python.csp) by <NAME>; the content is available [on GitHub](https://github.com/jakevdp/WhirlwindTourOfPython).**The text and code are released under the [CC0](https://github.com/jakevdp/WhirlwindTourOfPython/blob/master/LICENSE) license; see also the companion project, the [Python Data Science Handbook](https://github.com/jakevdp/PythonDataScienceHandbook).* Introduction to Python Programming for Medical Researchers, 2021-09-06, University of Bern, <NAME>  Basic Python (60 min)This notebook is a systematic and very condenced overview of- Python Syntax- Python Semantics- Python Operators- Python Data Types (Built-In)- Python Data Structures (Built-In)The content is basic and belongs to necessary knowledge by any Python programmers. One does not learn it by heart, however, after some hours of practicing Python, it automatically becomes active knowledge.It corresponds to the first six chapters of the book referenced above. There you may get more detailed descriptions.  Python Language Syntax<jupyter_code># Comments start with a #. They can also come after the code on the same line

# Multiline commands can be written with backslash \ or ()

# One may write multiple statements on one line by separating with ;

# Codeblocks are indicated by intendation and :

# Parentheses () Are for Grouping or Calling<jupyter_output><empty_output><jupyter_text>Finishing Up on the Syntax and Learning MoreThis has been a very brief exploration of the essential features of Python syntax; its purpose is to give you a good frame of reference for when you're reading the code in later sections.Several times we've mentioned Python "style guides", which can help teams to write code in a consistent style.The most widely used style guide in Python is known as PEP8, and can be found at https://www.python.org/dev/peps/pep-0008/.As you begin to write more Python code, it would be useful to read through this!The style suggestions contain the wisdom of many Python gurus, and most suggestions go beyond simple pedantry: they are experience-based recommendations that can help avoid subtle mistakes and bugs in your code. Python Semantics - Variables and Objects In Python data type declaration on variables is not needed. It has dynamic typing.<jupyter_code># Assignment by =<jupyter_output><empty_output><jupyter_text>In Python variables are pointers, i.e. they point to the memory buckets with the actual values. In Python everything is an object, it contains not only the value, but also attributes and methods. Methods are invoked by the dot.<jupyter_code><jupyter_output><empty_output><jupyter_text>Since everything is an object and variables are pointers, Python becomes its beauty and slowness. Against slwoness there is the library NumPy.   Python Operators  Arithmetic operators<jupyter_code># Python arithmetic operators
# addition, subtraction, multiplication

# True division

# Floor division

# Modulus

# Exponentation<jupyter_output><empty_output><jupyter_text>There are also bitwise operators. These are rarely used and you can looked them up if you think you need them.  Assignment operators<jupyter_code><jupyter_output><empty_output><jupyter_text>Comparison operators<jupyter_code><jupyter_output><empty_output><jupyter_text>Boolean operatorsand, or, not, xor<jupyter_code><jupyter_output><empty_output><jupyter_text>Identity and Membership Operators is, is not, in, not in<jupyter_code><jupyter_output><empty_output><jupyter_text>Python Built-In Types A computer needs to now the data type, i.e. the representation, in order to do calculations. So every computer langueage has built-in types. In Python the simple, in contrast to compund types (data structures), are summarized in the following table:**Python Scalar Types**| Type        | Example        | Description                                                  ||-------------|----------------|--------------------------------------------------------------|| ``int``     | ``x = 1``      | integers (i.e., whole numbers)                               || ``float``   | ``x = 1.0``    | floating-point numbers (i.e., real numbers)                  || ``complex`` | ``x = 1 + 2j`` | Complex numbers (i.e., numbers with real and imaginary part) || ``bool``    | ``x = True``   | Boolean: True/False values                                   || ``str``     | ``x = 'abc'``  | String: characters or text                                   || ``NoneType``| ``x = None``   | Special object indicating nulls                              |<jupyter_code># Integer

# Float (real numbers)

         # Exponential notation - 6 times ten to the minus 4
# Complex

# String


# There are attributes and many methods for string objects. Some examples:<jupyter_output><empty_output><jupyter_text>There is also a None type which has the value 'None' and a Boolean type. If you should encounter then, look them up.  Built-In Data Structures Python also has several built-in compound types, which act as containers for other types.These compound types are:| Type Name | Example                   |Description                            ||-----------|---------------------------|---------------------------------------|| ``list``  | ``[1, 2, 3]``             | Ordered collection                    || ``tuple`` | ``(1, 2, 3)``             | Immutable ordered collection          || ``dict``  | ``{'a':1, 'b':2, 'c':3}`` | Unordered (key,value) mapping         || ``set``   | ``{1, 2, 3}``             | Unordered collection of unique values |As you can see, round, square, and curly brackets have distinct meanings when it comes to the type of collection produced.We'll take a quick tour of these data structures here.<jupyter_code># Lists with some built-in methods

# Indexing and slicing on lists

# Tuples are like lists, but cannot be changed once defined
     # t = 2,3,5,7,11 also works
 # Not allowed
# Dictionaries are like a normal language dictionaries, there is a key word (car) for look up and a value, e.g. what is it in German (Auto).<jupyter_output><empty_output><jupyter_text>The [python documentation](https://docs.python.org/3/library/stdtypes.html) has a complete list of the methods available for dictionaries.<jupyter_code># Sets are much like tuples and you can to set mathematics with them (not so often needed by medical researchers)

# Sometimes you need to start with an empty data structure. You create them like this:<jupyter_output><empty_output><jupyter_text>More Specialized Data StructuresPython contains several other data structures that you might find useful; these can generally be found in the built-in ``collections`` module.The collections module is fully-documented in [Python's online documentation](https://docs.python.org/3/library/collections.html), and you can read more about the various objects available there.In particular, I've found the following very useful on occasion:- ``collections.namedtuple``: Like a tuple, but each value has a name- ``collections.defaultdict``: Like a dictionary, but unspecified keys have a user-specified default value- ``collections.OrderedDict``: Like a dictionary, but the order of keys is maintainedOnce you've seen the standard built-in collection types, the use of these extended functionalities is very intuitive, and I'd suggest [reading about their use](https://docs.python.org/3/library/collections.html).  The ``del`` statementThe syntax of the ``del`` statement is:``del object_name``,where ``object_name`` can be variable(s), user-defined objects (also classes, attributes of classes), lists, items within lists, dictionaries etc. ``del`` removes variable names from the namespaceAs a result of using del one can free up for example some variable names from the namespace. This command doesn't necessarily affect the object associated to the variable name, it frees up just the pointer (so that it can be used for other purposes maybe). However in some memory intensive applications it might be also used to prepare the objects to be erased by the garbage collector of Python.  Creating custom data structuresMany times we would like to handle data of a specific structure, for example we want to keep track of students of a class or clients of a business. For this purpose one can create custom data structures, this can be achieved by the ``class`` statement. To see a short introduction into classes consult [this link](https://www.mikedane.com/programming-languages/python/classes-objects/). A handy use case for classes can be found [here](https://www.mikedane.com/programming-languages/python/building-a-quiz/).<jupyter_code><jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09774178832116788, 'fraction_numerical': 0.005018248175182482, 'mean_word_length': 3.783960720130933, 'pattern_counts': {'":': 0, '<': 51, '<?xml version=': 0, '>': 51, 'https://': 9, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '356997', 'license': 'CC-BY-4.0', 'n_tokens_mistral': 2270, 'n_tokens_neox': 2157, 'n_words': 1034, 'path': '03-Basic-Python-1.ipynb', 'repo_name': 'sigvehaug/Introduction-to-Python-Programming-For-Medical-Researchers', 'size': '8781'}