Python in 10 minutes
Tags: tutorial, beginners, python, codenewbie
Published: 2020-08-19 07:39:53

 It’s probably not so much a tutorial as it is a cross between a tutorial and a cheat-sheet, so it will just show you some basic concepts to start you off. Obviously, if you want to really learn a language you need to program in it for a while. I will assume that you are already familiar with programming and will, therefore, skip most of the non-language-specific stuff.

<!-- wp:heading -->
<h2>Properties</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Python is&nbsp;<strong>strongly typed</strong>&nbsp;(i.e. types are enforced),&nbsp;<strong>dynamically, implicitly typed</strong>&nbsp;(i.e. you don’t have to declare variables),&nbsp;<strong>case sensitive</strong>&nbsp;(i.e. var and VAR are two different variables) and&nbsp;<strong>object-oriented</strong>&nbsp;(i.e. everything is an object).</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Getting help</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Help in Python is always available right in the interpreter. If you want to know how an object works, all you have to do is call&nbsp;<code>help(&lt;object&gt;)</code>! Also useful are&nbsp;<code>dir()</code>, which shows you all the object’s methods, and&nbsp;<code>&lt;object&gt;.__doc__</code>, which shows you its documentation string:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted"><strong>&gt;&gt;&gt; </strong>help(5)
Help on int object:
(etc etc)

<strong>&gt;&gt;&gt; </strong>dir(5)
['__abs__', '__add__', ...]

<strong>&gt;&gt;&gt; </strong>abs.__doc__
'abs(number) -&gt; number

Return the absolute value of the argument.
</pre>
<!-- /wp:preformatted -->

<!-- wp:heading -->
<h2>Syntax</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Python has&nbsp;<strong>no mandatory statement termination characters</strong>&nbsp;and&nbsp;<strong>blocks are specified by indentation</strong>. Indent to begin a block, dedent to end one. Statements that expect an indentation level end in a colon (:).&nbsp;<strong>Comments</strong>&nbsp;start with the pound (#) sign and are single-line, multi-line strings are used for&nbsp;<strong>multi-line comments</strong>.&nbsp;<strong>Values are assigned</strong>&nbsp;(in fact, objects are&nbsp;<strong>bound</strong>&nbsp;to names) with the&nbsp;<em>equals</em>&nbsp;sign (“=”), and&nbsp;<strong>equality testing</strong>&nbsp;is done using two&nbsp;<em>equals</em>&nbsp;signs (“==”). You can increment/decrement values using the += and -= operators respectively by the right-hand amount. This works on many datatypes, strings included. You can also use multiple variables on one line. For example:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted"><strong>&gt;&gt;&gt; </strong>myvar = 3
<strong>&gt;&gt;&gt; </strong>myvar += 2
<strong>&gt;&gt;&gt; </strong>myvar
5
<strong>&gt;&gt;&gt; </strong>myvar -= 1
<strong>&gt;&gt;&gt; </strong>myvar
4
"""This is a multiline comment.
The following lines concatenate the two strings."""
<strong>&gt;&gt;&gt; </strong>mystring = "Hello"
<strong>&gt;&gt;&gt; </strong>mystring += " world."
<strong>&gt;&gt;&gt; </strong>print(mystring)
Hello world.
# This swaps the variables in one line(!).
# It doesn't violate strong typing because values aren't
# actually being assigned, but new objects are bound to
# the old names.
<strong>&gt;&gt;&gt; </strong>myvar, mystring = mystring, myvar
</pre>
<!-- /wp:preformatted -->

<!-- wp:heading -->
<h2>Data types</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>The data structures available in python are&nbsp;<strong>lists, tuples and dictionaries</strong>. Sets are available in the&nbsp;<code>sets</code>&nbsp;library (but are built-in in Python 2.5 and later). Lists are like one-dimensional arrays (but you can also have lists of other lists), dictionaries are associative arrays (a.k.a. hash tables) and tuples are immutable one-dimensional arrays (Python “arrays” can be of any type, so you can mix e.g. integers, strings, etc in lists/dictionaries/tuples). The index of the first item in all array types is 0. Negative numbers count from the end towards the beginning, -1 is the last item. Variables can point to functions. The usage is as follows:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted"><strong>&gt;&gt;&gt; </strong>sample = [1, ["another", "list"], ("a", "tuple")]
<strong>&gt;&gt;&gt; </strong>mylist = ["List item 1", 2, 3.14]
<strong>&gt;&gt;&gt; </strong>mylist[0] = "List item 1 again" # We're changing the item.
<strong>&gt;&gt;&gt; </strong>mylist[-1] = 3.21 # Here, we refer to the last item.
<strong>&gt;&gt;&gt; </strong>mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
<strong>&gt;&gt;&gt; </strong>mydict["pi"] = 3.15 # This is how you change dictionary values.
<strong>&gt;&gt;&gt; </strong>mytuple = (1, 2, 3)
<strong>&gt;&gt;&gt; </strong>myfunction = len
<strong>&gt;&gt;&gt; </strong>print(myfunction(mylist))
3
</pre>
<!-- /wp:preformatted -->

<!-- wp:paragraph -->
<p>You can access&nbsp;<strong>array ranges</strong>&nbsp;using a colon (:). Leaving the start index empty assumes the first item, leaving the end index assumes the last item. Indexing is inclusive-exclusive, so specifying&nbsp;<code>[2:10]</code>&nbsp;will return items&nbsp;<code>[2]</code>&nbsp;(the third item, because of 0-indexing) to&nbsp;<code>[9]</code>&nbsp;(the tenth item), inclusive (8 items). Negative indexes count from the last item backwards (thus -1 is the last item) like so:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted"><strong>&gt;&gt;&gt; </strong>mylist = ["List item 1", 2, 3.14]
<strong>&gt;&gt;&gt; </strong>print(mylist[:])
['List item 1', 2, 3.1400000000000001]
<strong>&gt;&gt;&gt; </strong>print(mylist[0:2])
['List item 1', 2]
<strong>&gt;&gt;&gt; </strong>print(mylist[-3:-1])
['List item 1', 2]
<strong>&gt;&gt;&gt; </strong>print(mylist[1:])
[2, 3.14]
# Adding a third parameter, "step" will have Python step in
# N item increments, rather than 1.
# E.g., this will return the first item, then go to the third and
# return that (so, items 0 and 2 in 0-indexing).
<strong>&gt;&gt;&gt; </strong>print(mylist[::2])
['List item 1', 3.14]
</pre>
<!-- /wp:preformatted -->

<!-- wp:heading -->
<h2>Strings</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Its strings can use either single or double quotation marks, and you can have quotation marks of one kind inside a string that uses the other kind (i.e. “He said ’hello’.” is valid). Multiline strings are enclosed in _triple double (or single) quotes_ (“”“). Python strings are always Unicode, but there is another string type that is pure bytes. Those are called&nbsp;<em>bytestrings</em>&nbsp;and are represented with the&nbsp;<code>b</code>&nbsp;prefix, for example&nbsp;<code>b'Hello \xce\xb1'</code>. . To fill a string with values, you use the % (modulo) operator and a tuple. Each %s gets replaced with an item from the tuple, left to right, and you can also use dictionary substitutions, like so:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted"><strong>&gt;&gt;&gt; </strong>print("Name: %s\
Number: %s\
String: %s" % (myclass.name, 3, 3 * "-"))
Name: Stavros
Number: 3
String: ---

strString = """This is
a multiline
string."""

# WARNING: Watch out for the trailing s in "%(key)s".
<strong>&gt;&gt;&gt; </strong>print("This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"})
This is a test.

<strong>&gt;&gt;&gt; </strong>name = "Stavros"
<strong>&gt;&gt;&gt; </strong>"Hello, {}!".format(name)
Hello, Stavros!
<strong>&gt;&gt;&gt; </strong>print(f"Hello, {name}!")
Hello, Stavros!
</pre>
<!-- /wp:preformatted -->

<!-- wp:heading -->
<h2>Flow control statements</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Flow control statements are&nbsp;<code>if</code>,&nbsp;<code>for</code>, and&nbsp;<code>while</code>. There is no&nbsp;<code>switch</code>; instead, use if. Use for to enumerate through members of a list. To obtain a sequence of numbers you can iterate over, use&nbsp;<code>range(&lt;number&gt;)</code>. These statements’ syntax is thus:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">&gt;&gt;&gt; print(range(10))
range(0, 10)
&gt;&gt;&gt; rangelist = list(range(10))
&gt;&gt;&gt; print(rangelist)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for number in range(10):
    # Check if number is one of
    # the numbers in the tuple.
    if number in (3, 4, 7, 9):
        # "Break" terminates a for without
        # executing the "else" clause.
        break
    else:
        # "Continue" starts the next iteration
        # of the loop. It's rather useless here,
        # as it's the last statement of the loop.
        continue
else:
    # The "else" clause is optional and is
    # executed only if the loop didn't "break".
    pass # Do nothing

if rangelist[1] == 2:
    print("The second item (lists are 0-based) is 2")
elif rangelist[1] == 3:
    print("The second item (lists are 0-based) is 3")
else:
    print("Dunno")

while rangelist[1] == 1:
    print("We are trapped in an infinite loop!")
</pre>
<!-- /wp:preformatted -->

<!-- wp:heading -->
<h2>Functions</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Functions are&nbsp;<strong>declared with the&nbsp;<code>def</code></strong>&nbsp;keyword.&nbsp;<strong>Optional arguments</strong>&nbsp;are set in the function declaration after the mandatory arguments by being assigned a default value. For&nbsp;<strong>named arguments</strong>, the name of the argument is assigned a value. Functions can return a tuple (and using tuple unpacking you can effectively return&nbsp;<strong>multiple values</strong>).&nbsp;<strong>Lambda functions</strong>&nbsp;are ad hoc functions that are comprised of a single statement. Parameters are passed&nbsp;<strong>by reference</strong>, but immutable types (tuples, ints, strings, etc)&nbsp;<em>cannot be changed in the caller by the callee</em>. This is because&nbsp;<strong>only the memory location of the item is passed</strong>, and&nbsp;<strong>binding another object to a variable discards the old one</strong>, so immutable types are replaced. For example:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted"># Same as def funcvar(x): return x + 1
funcvar = lambda x: x + 1
&gt;&gt;&gt; print(funcvar(1))
2

# an_int and a_string are optional, they have default values
# if one is not passed (2 and "A default string", respectively).
def passing_example(a_list, an_int=2, a_string="A default string"):
    a_list.append("A new item")
    an_int = 4
    return a_list, an_int, a_string

&gt;&gt;&gt; my_list = [1, 2, 3]
&gt;&gt;&gt; my_int = 10
&gt;&gt;&gt; print(passing_example(my_list, my_int))
([1, 2, 3, 'A new item'], 4, "A default string")
&gt;&gt;&gt; my_list
[1, 2, 3, 'A new item']
&gt;&gt;&gt; my_int
10
</pre>
<!-- /wp:preformatted -->

<!-- wp:heading -->
<h2>Classes</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Python supports a limited form of&nbsp;<strong>multiple inheritance</strong>&nbsp;in classes.&nbsp;<strong>Private variables and methods</strong>&nbsp;can be declared (by convention, this is not enforced by the language) by adding a leading underscore (e.g.&nbsp;<code>_spam</code>). We can also bind&nbsp;<strong>arbitrary names</strong>&nbsp;to class instances. An example follows:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">class MyClass(object):
    common = 10
    def __init__(self):
        self.myvariable = 3
    def myfunction(self, arg1, arg2):
        return self.myvariable

    # This is the class instantiation

&gt;&gt;&gt; classinstance = MyClass()
&gt;&gt;&gt; classinstance.myfunction(1, 2)
3
# This variable is shared by all instances.
&gt;&gt;&gt; classinstance2 = MyClass()
&gt;&gt;&gt; classinstance.common
10
&gt;&gt;&gt; classinstance2.common
10
# Note how we use the class name
# instead of the instance.
&gt;&gt;&gt; MyClass.common = 30
&gt;&gt;&gt; classinstance.common
30
&gt;&gt;&gt; classinstance2.common
30
# This will not update the variable on the class,
# instead it will bind a new object to the old
# variable name.
&gt;&gt;&gt; classinstance.common = 10
&gt;&gt;&gt; classinstance.common
10
&gt;&gt;&gt; classinstance2.common
30
&gt;&gt;&gt; MyClass.common = 50
# This has not changed, because "common" is
# now an instance variable.
&gt;&gt;&gt; classinstance.common
10
&gt;&gt;&gt; classinstance2.common
50

# This class inherits from MyClass. The example
# class above inherits from "object", which makes
# it what's called a "new-style class".
# Multiple inheritance is declared as:
# class OtherClass(MyClass1, MyClass2, MyClassN)
class OtherClass(MyClass):
    # The "self" argument is passed automatically
    # and refers to the class instance, so you can set
    # instance variables as above, but from inside the class.
    def __init__(self, arg1):
        self.myvariable = 3
        print(arg1)

&gt;&gt;&gt; classinstance = OtherClass("hello")
hello
&gt;&gt;&gt; classinstance.myfunction(1, 2)
3
# This class doesn't have a .test member, but
# we can add one to the instance anyway. Note
# that this will only be a member of classinstance.
&gt;&gt;&gt; classinstance.test = 10
&gt;&gt;&gt; classinstance.test
10
</pre>
<!-- /wp:preformatted -->

<!-- wp:heading -->
<h2>Exceptions</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Exceptions in Python are handled with&nbsp;<strong>try-except [exceptionname]</strong>&nbsp;blocks:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">def some_function():
    try:
        # Division by zero raises an exception
        10 / 0
    except ZeroDivisionError:
        print("Oops, invalid.")
    else:
        # Exception didn't occur, we're good.
        pass
    finally:
        # This is executed after the code block is run
        # and all exceptions have been handled, even
        # if a new exception is raised while handling.
        print("We're done with that.")

&gt;&gt;&gt; some_function()
Oops, invalid.
We're done with that.
</pre>
<!-- /wp:preformatted -->

<!-- wp:heading -->
<h2>Importing</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>External libraries are used with the&nbsp;<code>import [libname]</code>&nbsp;keyword. You can also use&nbsp;<code>from [libname] import [funcname]</code>&nbsp;for individual functions. Here is an example:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">import random
from time import clock

randomint = random.randint(1, 100)
&gt;&gt;&gt; print(randomint)
64
</pre>
<!-- /wp:preformatted -->

<!-- wp:heading -->
<h2>File I/O</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Python has a wide array of libraries built in. As an example, here is how&nbsp;<strong>serializing</strong>&nbsp;(converting data structures to strings using the&nbsp;<code>pickle</code>&nbsp;library) with file I/O is used:</p>
<!-- /wp:paragraph -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">import pickle
mylist = ["This", "is", 4, 13327]
# Open the file C:\\binary.dat for writing. The letter r before the
# filename string is used to prevent backslash escaping.
myfile = open(r"C:\\binary.dat", "wb")
pickle.dump(mylist, myfile)
myfile.close()

myfile = open(r"C:\\text.txt", "w")
myfile.write("This is a sample string")
myfile.close()

myfile = open(r"C:\\text.txt")
&gt;&gt;&gt; print(myfile.read())
'This is a sample string'
myfile.close()

# Open the file for reading.
myfile = open(r"C:\\binary.dat", "rb")
loadedlist = pickle.load(myfile)
myfile.close()
&gt;&gt;&gt; print(loadedlist)
['This', 'is', 4, 13327]
</pre>
<!-- /wp:preformatted -->

<!-- wp:heading -->
<h2>Miscellaneous</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong>Conditions can be chained</strong>:&nbsp;<code>1 &lt; a &lt; 3</code>&nbsp;checks that a is both less than 3 and greater than 1.</li><li>You can use&nbsp;<code>del</code>&nbsp;to&nbsp;<strong>delete variables or items in arrays</strong>.</li><li><strong>List comprehensions</strong>&nbsp;provide a powerful way to create and manipulate lists. They consist of an expression followed by a&nbsp;<code>for</code>&nbsp;clause followed by zero or more&nbsp;<code>if</code>&nbsp;or&nbsp;<code>for</code>&nbsp;clauses, like so:</li></ul>
<!-- /wp:list -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted"><strong>&gt;&gt;&gt; </strong>lst1 = [1, 2, 3]
<strong>&gt;&gt;&gt; </strong>lst2 = [3, 4, 5]
<strong>&gt;&gt;&gt; </strong>print([x * y for x in lst1 for y in lst2])
[3, 4, 5, 6, 8, 10, 9, 12, 15]
<strong>&gt;&gt;&gt; </strong>print([x for x in lst1 if 4 &gt; x &gt; 1])
[2, 3]
# Check if a condition is true for any items.
# "any" returns true if any item in the list is true.
<strong>&gt;&gt;&gt; </strong>any([i % 3 for i in [3, 3, 4, 4, 3]])
True
# This is because 4 % 3 = 1, and 1 is true, so any()
# returns True.

# Check for how many items a condition is true.
<strong>&gt;&gt;&gt; </strong>sum(1 for i in [3, 3, 4, 4, 3] if i == 4)
2
<strong>&gt;&gt;&gt; </strong>del lst1[0]
<strong>&gt;&gt;&gt; </strong>print(lst1)
[2, 3]
<strong>&gt;&gt;&gt; </strong>del lst1
</pre>
<!-- /wp:preformatted -->

<!-- wp:list -->
<ul><li><strong>Global variables</strong>&nbsp;are declared outside of functions and can be read without any special declarations, but if you want to write to them you must declare them at the beginning of the function with the&nbsp;<code>global</code>&nbsp;keyword, otherwise Python will bind that object to a new local variable (be careful of that, it’s a small catch that can get you if you don’t know it). For example:</li></ul>
<!-- /wp:list -->

<!-- wp:preformatted -->
<pre class="wp-block-preformatted">number = 5

def myfunc():
    # This will print 5.
    print(number)

def anotherfunc():
    # This raises an exception because the variable has not
    # been bound before printing. Python knows that it an
    # object will be bound to it later and creates a new, local
    # object instead of accessing the global one.
    print(number)
    number = 3

def yetanotherfunc():
    global number
    # This will correctly change the global.
    number = 3</pre>
<!-- /wp:preformatted -->