What is Python and what makes it so great? Python, of course, is a popular and powerful, general-purpose programming language. Software developers that use Python often comment on the language’s expressive nature which makes it good for getting productive quickly. Python operates on a “batteries included” philosophy, meaning it ships with a very useful standard library that we will take a look at. Python is open source and has many third-party packages and libraries to help you build whatever you may like in the language. Python has gained huge popularity and the over 120 thousand subscribers at r/python are an attribute to this. In this tutorial, we will approach Python from the very beginning and lay a foundation for which we can learn more about this great open source programming language.

## Installing Python 3 on Windows

The best way to start learning Python is, of course, to install it, and take it for a spin yourself. To install Python on Windows, we will follow these steps.

Visit https://www.python.org and navigate to the latest version for Windows.

Run the `.exe`

file which will install Python.

Confirm the install was a success!

Open a command prompt, and type `python`

. You should see output similar to this.

`C:\>python`

Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>>

In older versions, you may have had to manually add Python to your path. Thankfully in the current version, you don’t even have to do this as long as you have the “Add Python 3.5 to Path” checked on the initial install page. This is what gives us the ability to launch Python from the command prompt straight away.

### Python Read-Eval-Print-Loop or REPL

We have Python installed and running – Congratulations! We can start using it immediately, so let’s give it a shot. We are beginning right at the command line, which is a Read – Eval – Print – Loop, also known as **REPL**. This simply means Python reads the input which is typed in, evaluates it, prints the result, and loops back around to the start. You’ll know the REPL is running when you have the familiar triple arrow `>>>`

prompt waiting for some input. Let’s try it out!

#### Simple Math

An easy way to start testing Python is with some simple math problems.

`>>> 3 + 4`

7

>>>

In this simple example, we just type out three plus four and hit enter. The REPL calculates this result to seven, prints it to the screen, and brings us right back to the command prompt. **Fantastic!** You just wrote your first piece of Python. Let’s try a few more.

`>>> 5 * 5`

25

>>> 35 / 5

7.0

>>> 100 % 9

1

>>> 25 % 5

0

>>> 81 - 72

9

>>>

We can see that multiplication, division, modulus, and subtraction are working well. Assigning a value to a variable works like you might expect. We make use of the assignment operator to do so.

`>>> myvalue = 25 * 25`

>>> myvalue

625

>>>

Here, we multiply 25 times 25 and assign it to a variable named `myvalue`

. When the REPL comes back and provides us with a prompt, we simply type out the name of the variable, hit enter, and it gives us the stored result of 625. Pretty cool!

#### Variables in expressions

In the prior example we assigned a value to our variable of `myvalue`

. We can also make use of variable names in expressions in the REPL. Let’s go ahead and complete myvalue modulus 600 and see the result.

`>>> myvalue % 600`

25

>>>

The remainder of 25 is correctly calculated.

#### The underscore variable

The `_`

in the Python REPL refers to the most recently printed value to the screen.

`>>> _`

25

>>>

The underscore variable can also be used in expressions. This little underscore trick only works in the REPL, so don’t try to make use of it in dedicated Python programs and scripts.

#### Printing Text

To print text in Python using the REPL, we can use the `print()`

function to do so. Let’s try it out.

`>>> print('Python is fun')`

Python is fun

>>> print("Python is fun")

Python is fun

>>> print(Python is fun)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

NameError: name 'Python' is not defined

>>>

Note that our string must be enclosed by either single quotes or double-quotes. If we do not include these, we get an error as you see above. In addition, as of Python 3, the opening and closing parentheses around the string are in fact required. In Python 2, they were not needed.

#### How to exit the Python REPL

After you have tried a few very Basic Python tasks in the REPL, you will need to know how to exit. To do so, you type ctrl + Z on a Windows platform like so.

`>>> ^Z`

```
```

`C:\>`

With that, we successfully exit out of the Python REPL.

## Whitespace in Python

If you have previous programming experience, you may be familiar with the idea that whitespace does not matter and has no meaning. JavaScript is one such language. Python is different however. Whitespace means something, in fact whitespace is extremely important in Python. This may be one of the biggest surprises to newcomers to the Python language.

In Python control structures like loops, while loops, and if statements are all introduced by statements which are terminated by a colon which means that the body of that construct is what comes next. We know that loops need a body to work. We will enter something like `number in range(10):`

and hit enter. Python reads this as if there will be a body to follow and will change the prompt to three dots like so.

`>>> for number in range(10):`

...

This introduces us to the concept of the missing curly braces. If you were thinking we are about to input some curly braces to define a body of a loop, you are forgiven! This is how it is done in most other languages. In Python, we make use of leading white space to determine where code blocks begin and end. It will bend your mind a little bit at first, but if you want to learn Python, you must grasp this concept. The convention is to use four spaces of indentation. We will now indent four spaces enter an expression, then hit return. We will add another line, again prefixed by four spaces and hit return again. Finally, to terminate our block, we simply hit enter on a blank line. Yes, a bit odd at first, but let’s test it out.

`>>> for number in range(10):`

... result = number * 2

... print(result)

...

0

2

4

6

8

10

12

14

16

18

>>>

As we can see Python executes the loop printing out the multiples of 2 less than 20. The same thing written in JavaScript would look something like this.

1 2 3 4 |
for(number = 0; number < 10; number++) { result = number * 2; console.log(result); } |

In looking at some Python code, such as this class that comes from the popular scrapy framework, we can see the complete absence of curly braces, and the importance of whitespace. It is pretty clear how indentation matches, and offers a visual structure to the code. Some people really like this, others not so much. Consider though that there are benefits to this approach. Developers will always use a single level of indentation in a code block, which is good. We also eliminate the need for any curly braces at all, which is often the source of heated debates as to where they should be placed in code. Without them, there is no argument! In Python, all code blocks are easy to identify because everyone needs to write them the same way. There is no room for personal preference with regard to this. Significant whitespace in Python mandates that a consistent interpretation is given to the structure of the code by the developer, the Python runtime itself, and developers who might need to read the code in the future.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
import six from w3lib.http import headers_dict_to_raw from scrapy.utils.datatypes import CaselessDict from scrapy.utils.python import to_unicode class Headers(CaselessDict): """Case insensitive http headers dictionary""" def __init__(self, seq=None, encoding='utf-8'): self.encoding = encoding super(Headers, self).__init__(seq) def normkey(self, key): """Normalize key to bytes""" return self._tobytes(key.title()) def normvalue(self, value): """Normalize values to bytes""" if value is None: value = [] elif isinstance(value, (six.text_type, bytes)): value = [value] elif not hasattr(value, '__iter__'): value = [value] return [self._tobytes(x) for x in value] def _tobytes(self, x): if isinstance(x, bytes): return x elif isinstance(x, six.text_type): return x.encode(self.encoding) elif isinstance(x, int): return six.text_type(x).encode(self.encoding) else: raise TypeError('Unsupported value type: {}'.format(type(x))) def __getitem__(self, key): try: return super(Headers, self).__getitem__(key)[-1] except IndexError: return None def get(self, key, def_val=None): try: return super(Headers, self).get(key, def_val)[-1] except IndexError: return None def getlist(self, key, def_val=None): try: return super(Headers, self).__getitem__(key) except KeyError: if def_val is not None: return self.normvalue(def_val) return [] def setlist(self, key, list_): self[key] = list_ def setlistdefault(self, key, default_list=()): return self.setdefault(key, default_list) def appendlist(self, key, value): lst = self.getlist(key) lst.extend(self.normvalue(value)) self[key] = lst def items(self): return list(self.iteritems()) def iteritems(self): return ((k, self.getlist(k)) for k in self.keys()) def values(self): return [self[k] for k in self.keys()] def to_string(self): return headers_dict_to_raw(self) def to_unicode_dict(self): """ Return headers as a CaselessDict with unicode keys and unicode values. Multiple values are joined with ','. """ return CaselessDict( (to_unicode(key, encoding=self.encoding), to_unicode(b','.join(value), encoding=self.encoding)) for key, value in self.items()) def __copy__(self): return self.__class__(self) copy = __copy__ |

#### Python Whitespace Guidelines

- 1. Prefer
**four spaces** - 2.
**Never**mix spaces and tabs - 3. Be
**consistent**on consecutive lines - 4. Only deviate to
**improve**readability

## The Zen of Python

The development of Python is managed through a series of documents called Python Enhancement Proposals or PEPs. They are numbered, and it is number 20 that outlines The Zen of Python. We include here as follows:

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!

As we read through these guidelines, we can see that they make perfect sense for not only Python, but software development in general.

## The Python Standard Library

As we mentioned, Python takes a batteries included approach and what is meant by this is that you can find tons of fantastic and useful software right in the Python Standard Library. You can make use of these modules by using the `import`

keyword, and we did notice the use of this keyword in the code snippet presented earlier. We can make use of the standard library right at the command line repl. Let’s try it out now.

`>>> import math`

>>> help(math)

Help on built-in module math:

```
```NAME

math

DESCRIPTION

This module is always available. It provides access to the

mathematical functions defined by the C standard.

FUNCTIONS

acos(...)

acos(x)

Return the arc cosine (measured in radians) of x.

acosh(...)

acosh(x)

Return the inverse hyperbolic cosine of x.

asin(...)

asin(x)

Return the arc sine (measured in radians) of x.

asinh(...)

asinh(x)

Return the inverse hyperbolic sine of x.

atan(...)

atan(x)

Return the arc tangent (measured in radians) of x.

atan2(...)

atan2(y, x)

Return the arc tangent (measured in radians) of y/x.

Unlike atan(y/x), the signs of both x and y are considered.

atanh(...)

atanh(x)

Return the inverse hyperbolic tangent of x.

ceil(...)

ceil(x)

Return the ceiling of x as an int.

This is the smallest integral value >= x.

copysign(...)

copysign(x, y)

Return a float with the magnitude (absolute value) of x but the sign

of y. On platforms that support signed zeros, copysign(1.0, -0.0)

returns -1.0.

cos(...)

cos(x)

Return the cosine of x (measured in radians).

cosh(...)

cosh(x)

Return the hyperbolic cosine of x.

degrees(...)

degrees(x)

Convert angle x from radians to degrees.

erf(...)

erf(x)

Error function at x.

erfc(...)

erfc(x)

Complementary error function at x.

exp(...)

exp(x)

Return e raised to the power of x.

expm1(...)

expm1(x)

Return exp(x)-1.

This function avoids the loss of precision involved in the direct evaluation of exp(x)-

fabs(...)

fabs(x)

Return the absolute value of the float x.

factorial(...)

factorial(x) -> Integral

Find x!. Raise a ValueError if x is negative or non-integral.

floor(...)

floor(x)

Return the floor of x as an int.

This is the largest integral value <= x.

fmod(...)

fmod(x, y)

Return fmod(x, y), according to platform C. x % y may differ.

frexp(...)

frexp(x)

Return the mantissa and exponent of x, as pair (m, e).

m is a float and e is an int, such that x = m * 2.**e.

If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.

fsum(...)

fsum(iterable)

Return an accurate floating-point sum of values in the iterable.

Assumes IEEE-754 floating-point arithmetic.

gamma(...)

gamma(x)

Gamma function at x.

gcd(...)

gcd(x, y) -> int

greatest common divisor of x and y

hypot(...)

hypot(x, y)

Return the Euclidean distance, sqrt(x*x + y*y).

isclose(...)

is_close(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool

Determine whether two floating-point numbers are close in value.

rel_tol

maximum difference for being considered "close", relative to the

magnitude of the input values

abs_tol

maximum difference for being considered "close", regardless of the

magnitude of the input values

Return True if a is close in value to b, and False otherwise.

For the values to be considered close, the difference between them

must be smaller than at least one of the tolerances.

-inf, inf and NaN behave similarly to the IEEE 754 Standard. That

is, NaN is not close to anything, even itself. inf and -inf are

only close to themselves.

isfinite(...)

isfinite(x) -> bool

Return True if x is neither an infinity nor a NaN, and False otherwise.

isinf(...)

isinf(x) -> bool

Return True if x is a positive or negative infinity, and False otherwise.

isnan(...)

isnan(x) -> bool

Return True if x is a NaN (not a number), and False otherwise.

ldexp(...)

ldexp(x, i)

Return x * (2**i).

lgamma(...)

lgamma(x)

Natural logarithm of absolute value of Gamma function at x.

log(...)

log(x[, base])

Return the logarithm of x to the given base.

If the base not specified, returns the natural logarithm (base e) of x.

log10(...)

log10(x)

Return the base 10 logarithm of x.

log1p(...)

log1p(x)

Return the natural logarithm of 1+x (base e).

The result is computed in a way that is accurate for x near zero.

log2(...)

log2(x)

Return the base 2 logarithm of x.

modf(...)

modf(x)

Return the fractional and integer parts of x. Both results carry the sign

of x and are floats.

pow(...)

pow(x, y)

Return x**y (x to the power of y).

radians(...)

radians(x)

Convert angle x from degrees to radians.

sin(...)

sin(x)

Return the sine of x (measured in radians).

sinh(...)

sinh(x)

Return the hyperbolic sine of x.

sqrt(...)

sqrt(x)

Return the square root of x.

tan(...)

tan(x)

Return the tangent of x (measured in radians).

tanh(...)

tanh(x)

Return the hyperbolic tangent of x.

trunc(...)

trunc(x:Real) -> Integral

Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.

DATA

e = 2.718281828459045

inf = inf

nan = nan

pi = 3.141592653589793

FILE

(built-in)

`>>>`

In the snippet above, we import the math module, then use the help utility to find out what functions are available to us in the math module. We make use of those functions like so:

`>>> math.sqrt(100)`

10.0

```
```>>> math.tan(50)

-0.27190061199763077

>>> math.trunc(1234.1234)

1234

>>> math.pow(4,3)

64.0

>>> math.pow(5,5)

3125.0

`>>>`

## Python Built-In Data Types

Like all programming languages, Python makes use of data types. Just like other programming languages, Python has support for integers, floating-point numbers, booleans, and strings. Python also has collection types such as dictionaries built-in. In Python, integers are specified in decimal – though you can write them in binary if needed by including a 0b prefix or hexadecimal with a 0x prefix. One thing that is different about Python is that a null value is represented by something called `None`

. This is used to denote the lack of any value. There is a fair amount of information about types which might be best covered by reading the documentation provided in the link above.

## Relational Operators in Python

Python makes use of some familiar relational operators just as many other programming languages do. `==`

is used to check equality or equivalence, `!=`

checks value inequality, `<`

is less than, `>`

is greater than, `<=`

is less than or equal to, and `>=`

is greater than or equal to. We can see these operators in action on the REPL here.

`>>> num = 20`

>>> num == 20

True

>>> num == 14

False

>>> num != 20

False

>>> num != 17

True

>>> num < 35

True

>>> num > 40

False

>>> num <= 20

True

>>> num >= 20

True

>>>

## Conditional Statements in Python

We need to be able to evaluate expressions and then take action based on whether that expression is true or false. We do this using conditional statements in Python. In Python we make use of `if`

, `else`

, and `elif`

to handle these situations.

An example of **conditional execution**:

1 2 |
if num > 0: print(num, "is positive") |

This is an example of **alternative execution**:

1 2 3 4 |
if num % 2 == 0: print(num, "is even") else: print(num, "is odd") |

You could make a function out of this example like so:

1 2 3 4 5 |
def even_odd(num): if num % 2 == 0: print(num, "is even") else: print(num, "is odd") |

Let’s try it out on the REPL:

`>>> def even_odd(num):`

... if num % 2 == 0:

... print(num, "is even")

... else:

... print(num, "is odd")

...

>>> even_odd(2)

2 is even

>>> even_odd(3)

3 is odd

>>>

Here is an example of a chained conditional:

1 2 3 4 5 6 |
if abc < xyz: print(abc, "is less than", xyz) elif abc > xyz: print(abc, "is greater than", xyz) else: print(abc, "and", xyz, "are equal") |

## While and For Loops in Python

We need a way to handle repetitive tasks in our programs in in Python we do this with the **while** and **for** loops. They operate just like you might expect, with the only difference, of course, being that we use whitespace and indentation instead of curly braces to handle our blocks.

This is an example of a while loop:

`>>> num = 1`

>>> while num < 10:

... print(num)

... num += 1

...

1

2

3

4

5

6

7

8

9

>>>

This is how you might run a for loop in Python:

`>>> languages = ['python', 'php', 'JavaScript', 'Ruby']`

>>> for char in languages:

... print(char, len(char))

...

python 6

php 3

JavaScript 10

Ruby 4

>>>

### Getting Started With Python 3 Summary

Great work! If you made it this far, you got through a lot of beginner level need to know information about working with the Python language. We’ll be covering a lot more Python in the coming articles, but let’s take a quick recap of what we covered here. First off we had a look at why Python is as popular as it is, and how to get it installed on your system. Once set up was successful, we jumped right into the REPL or Read-Eval-Print-Loop of the command line to test out some basic Python programs. We found that by working with the REPL, we can start small with Python before moving into bigger scripts and programs which may be useful for day to day work. Amazingly, whitespace has meaning in Python. This may be the biggest surprise if you’re new to the language, as most other programming languages simply ignore whitespace. Next up we had a look at The Zen of Python which gave us some good guidelines to live by when writing Python. Finally, we looked at a small amount of the Standard Library, data types, operators, conditional statements, and basic loops.