Python - Modul
Python - Modul
Python - Modul
No computer is currently capable of creating a new language. However, that may change
soon. Just as people use a number of very different languages, machines have many
different languages, too. The difference, though, is that human languages developed
naturally.
Moreover, they are still evolving, and new words are created every day as old words
disappear. These languages are called natural languages.
We can say that each language (machine or natural, it doesn't matter) consists of the
following elements:
an alphabet: a set of symbols used to build words of a certain language (e.g., the
Latin alphabet for English, the Cyrillic alphabet for Russian, Kanji for Japanese, and so
on)
a lexis: (aka a dictionary) a set of words the language offers its users (e.g., the word
"computer" comes from the English language dictionary, while "cmoptrue" doesn't;
the word "chat" is present both in English and French dictionaries, but their
meanings are different)
a syntax: a set of rules (formal or informal, written or felt intuitively) used to
determine if a certain string of words forms a valid sentence (e.g., "I am a python" is
a syntactically correct phrase, while "I a python am" isn't)
semantics: a set of rules determining if a certain phrase makes sense (e.g., "I ate a
doughnut" makes sense, but "A doughnut ate me" doesn't)
The IL is, in fact, the alphabet of a machine language. This is the simplest and most
primary set of symbols we can use to give commands to a computer. It's the computer's
mother tongue.
Such languages are often called high-level programming languages. They are at least
somewhat similar to natural ones in that they use symbols, words and conventions readable
to humans. These languages enable humans to express commands to computers that are
much more complex than those offered by ILs.
There are two different ways of transforming a program from a high-level programming
language into machine language:
COMPILATION - the source program is translated once (however, this act must be repeated
each time you modify the source code) by getting a file (e.g., an .exe file if the code is
intended to be run under MS Windows) containing the machine code; now you can
distribute the file worldwide; the program that performs this translation is called a compiler
or translator;
INTERPRETATION - you (or any user of the code) can translate the source program each
time it has to be run; the program performing this kind of transformation is called an
interpreter, as it interprets the code every time it is intended to be executed; it also means
that you cannot just distribute the source code as-is, because the end-user also needs the
interpreter to execute it.
Let's assume once more that you have written a program. Now, it exists as a computer file:
a computer program is actually a piece of text, so the source code is usually placed in text
files.
Note: it has to be pure text, without any decorations like different fonts, colors, embedded
images or other media. Now you have to invoke the interpreter and let it read your source
file.
First of all, the interpreter checks if all subsequent lines are correct (using the four aspects
covered earlier).
If the compiler finds an error, it finishes its work immediately. The only result in this case is
an error message.
Python is an interpreted language. This means that it inherits all the described
advantages and disadvantages. Of course, it adds some of its unique features to
both sets.
If you want to program in Python, you'll need the Python interpreter. You won't be
able to run your code without it. Fortunately, Python is free. This is one of its most
important advantages.
And while you may know the python as a large snake, the name of the Python programming
language comes from an old BBC television comedy sketch series called Monty Python's
Flying Circus.
At the height of its success, the Monty Python team were performing their sketches to live
audiences across the world, including at the Hollywood Bowl.
Since Monty Python is considered one of the two fundamental nutrients to a programmer
(the other being pizza), Python's creator named the language in honor of the TV show.
Python goals
In 1999, Guido van Rossum defined his goals for Python:
There are many reasons - we've listed some of them already, but let's enumerate them
again in a more practical manner:
it's easy to learn - the time needed to learn Python is shorter than for many other
languages; this means that it's possible to start the actual programming faster;
it's easy to teach - the teaching workload is smaller than that needed by other
languages; this means that the teacher can put more emphasis on general
(language-independent) programming techniques, not wasting energy on exotic
tricks, strange exceptions and incomprehensible rules;
it's easy to use for writing new software - it's often possible to write code faster
when using Python;
it's easy to understand - it's also often easier to understand someone else's code
faster if it is written in Python;
it's easy to obtain, install and deploy - Python is free, open and multiplatform; not
all languages can boast that.
it's not a speed demon - Python does not deliver exceptional performance;
in some cases it may be resistant to some simpler testing techniques - this may
mean that debugging Python's code can be more difficult than with other languages;
fortunately, making mistakes is always harder in Python.
an editor which will support you in writing the code (it should have some special
features, not available in simple tools); this dedicated editor will give you more than
the standard OS equipment;
a console in which you can launch your newly written code and stop it forcibly when
it gets out of control;
a tool named a debugger, able to launch your code step by step and allowing you to
inspect it at each moment of execution.
Besides its many useful components, the Python 3 standard installation contains a very
simple but extremely useful application named IDLE.
Module 2
The word print that you can see here is a function name.
A function (in this context) is a separate part of the computer code able to:
cause some effect (e.g., send text to the terminal, create a file, draw an image, play
a sound, etc.); this is something completely unheard of in the world of mathematics;
evaluate a value (e.g., the square root of a value or the length of a given text)
and return it as the function's result; this is what makes Python functions the
relatives of mathematical concepts.
They may come from Python itself; the print function is one of this kind; such a
function is an added value received together with Python and its environment (it
is built-in); you don't have to do anything special (e.g., ask anyone for anything) if
you want to make use of it;
they may come from one or more of Python's add-ons named modules; some of the
modules come with Python, others may require separate installation - whatever the
case, they all need to be explicitly connected with your code (we'll show you how to
do that soon);
you can write them yourself, placing as many functions as you want and need
inside your program to make it simpler, clearer and more elegant.
The name of the function should be significant (the name of the print function is self-
evident). As we said before, a function may have:
an effect;
a result.
As you can see, the string is delimited with quotes - in fact, the quotes make the string -
they cut out a part of the code and assign a different meaning to it.
The function name (print in this case) along with the parentheses and argument(s), forms
the function invocation.
Let's see:
First, Python checks if the name specified is legal (it browses its internal data in
order to find an existing function of the name; if this search fails, Python aborts the
code);
second, Python checks if the function's requirements for the number of
arguments allows you to invoke the function in this way (e.g., if a specific function
demands exactly two arguments, any invocation delivering only one argument will
be considered erroneous, and will abort the code's execution);
third, Python leaves your code for a moment and jumps into the function you want
to invoke; of course, it takes your argument(s) too and passes it/them to the
function;
fourth, the function executes its code, causes the desired effect (if any), evaluates
the desired result(s) (if any) and finishes its task;
finally, Python returns to your code (to the place just after the invocation) and
resumes its execution.
takes its arguments (it may accept more than one argument and may also accept less than one
argument)
converts them into human-readable form if needed (as you may suspect, strings don't require this
action, as the string is already readable)
and sends the resulting data to the output device (usually the console); in other words, anything
you put into the print() function will appear on your screen.
No wonder then, that from now on, you'll utilize print() very intensively to see the results of your
operations and evaluations.
Any. We'll show you soon that print() is able to operate with virtually all types of data offered by
Python. Strings, numbers, characters, logical values, objects - any of these may be successfully passed
to print() .
There are two very subtle changes - we've inserted a strange pair of characters inside the
rhyme. They look like this: \n . Interestingly, while you can see two characters, Python
sees one. The backslash ( \ ) has a very special meaning when used inside strings - this is
called the escape character.
In other words, the backslash doesn't mean anything in itself, but is only a kind of
announcement, that the next character after the backslash has a different meaning too.
The letter n placed after the backslash comes from the word newline.
Both the backslash and the n form a special symbol named a newline character, which
urges the console to start a new output line.
print()
There is one print() function invocation, but it contains three arguments. All of them are
strings.
a print() function invoked with more than one argument outputs them all on
one line;
the print() function puts a space between the outputted arguments on its own
initiative.
In our example, we have made use of the end keyword argument, and set it to a string
containing one space.
My-name-is-Monty-Python.
Note: the sep argument's value may be an empty string, too. Try it for yourself.
Key takeaways
1. The print() function is a built-in function. It prints/outputs a specified message to the
screen/consol window.
2. Built-in functions, contrary to user-defined functions, are always available and don't have
to be imported. Python 3.8 comes with 69 built-in functions. You can find their full list
provided in alphabetical order in the Python Standard Library.
4. Python strings are delimited with quotes, e.g., "I am a string" (double quotes), or 'I
am a string, too' (single quotes).
6. In Python strings the backslash ( \ ) is a special character which announces that the next
character has a different meaning, e.g., \n (the newline character) starts a new output line.
7. Positional arguments are the ones whose meaning is dictated by their position, e.g., the
second argument is outputted after the first, the third is outputted after the second, etc.
8. Keyword arguments are the ones whose meaning is not dictated by their location, but
by a special word (keyword) used to identify them.
9. The end and sep parameters can be used for formatting the output of
the print() function. The sep parameter specifies the separator between the outputted
arguments (e.g., print("H", "E", "L", "L", "O", sep="-") , whereas
the end parameter specifies what to print at the end of the print statement.
We won't explore the intricacies of positional numeral systems here, but we'll say that the
numbers handled by modern computers are of two types:
integers, that is, those which are devoid of the fractional part;
and floating-point numbers (or simply floats), that contain (or are able to contain)
the fractional part.
The characteristic of the numeric value which determines its kind, range, and
application, is called the type.
If you encode a literal and place it inside Python code, the form of the literal determines
the representation (type) Python will use to store it in the memory.
Take, for example, the number eleven million one hundred and eleven thousand one
hundred and eleven. If you took a pencil in your hand right now, you would write the
number like this: 11,111,111 , or like this: 11.111.111 , or even like this: 11 111 111 .
It's clear that this provision makes it easier to read, especially when the number consists
of many digits. However, Python doesn't accept things like these. It's prohibited. What
Python does allow, though, is the use of underscores in numeric literals.*
Therefore, you can write this number either like this: 11111111 , or like
that: 11_111_111 .
NOTE *Python 3.6 has introduced underscores in numeric literals, allowing for placing
single underscores between digits and after base specifiers for improved readability.
This feature is not available in older versions of Python.
And how do we code negative numbers in Python? As usual - by adding a minus. You can
write: -11111111 , or -11_111_111 .
Positive numbers do not need to be preceded by the plus sign, but it's permissible, if you
wish to do it. The following lines describe the same number: +11111111 and 11111111 .
If an integer number is preceded by an 0O or 0o prefix (zero-o), it will be treated as an octal value. This
means that the number must contain digits taken from the [0..7] range only.
print(0o123)
The second convention allows us to use hexadecimal numbers. Such numbers should be preceded by the
prefix 0x or 0X (zero-x).
0x123 is a hexadecimal number with a (decimal) value equal to 291 . The print() function can manage
these values too. Try this: print(0x123)
Floats
Now it's time to talk about another type, which is designed to represent and to store the
numbers that (as a mathematician would say) have a non-empty decimal fraction.
Note: two and a half looks normal when you write it in a program, although if your native
language prefers to use a comma instead of a point in the number, you should ensure that
your number doesn't contain any commas at all.
To avoid writing out so many zeros, physics textbooks use an abbreviated form, which you
have probably already seen: 3 x 108
3E8 The letter E (you can also use the lower-case letter e - it comes from the
word exponent) is a concise record of the phrase times ten to the power of.
Note:
Python always chooses the more economical form of the number's presentation, and
you should take this into consideration when creating literals.
Boolean values
They're not as obvious as any of the previous ones, as they're used to represent a very
abstract value - truthfulness.
Each time you ask Python if one number is greater than another, the question results in the
creation of some specific data - a Boolean value.
The name comes from George Boole (1815-1864), the author of the fundamental work, The
Laws of Thought, which contains the definition of Boolean algebra - a part of algebra which
makes use of only two distinct values: True and False , denoted as 1 and 0 .
Key takeaways
1. Literals are notations for representing some fixed values in code. Python has various
types of literals - for example, a literal can be a number (numeric literals, e.g., 123 ), or a
string (string literals, e.g., "I am a literal.").
5. To encode an apostrophe or a quote inside a string you can either use the escape
character, e.g., 'I\'m happy.' , or open and close the string using an opposite set of
symbols to the ones you wish to encode, e.g., "I'm happy." to encode an apostrophe,
and 'He said "Python", not "typhoon"' to encode a (double) quote.
6. Boolean values are the two constant objects True and False used to represent truth
values (in numeric contexts 1 is True , while 0 is False .
Remember: It's possible to formulate the following rules based on this result:
The value in front of the slash is a dividend, the value behind the slash, a divisor.
The result produced by the division operator is always a float, regardless of whether or not
the result seems to be a float at first glance: 1 / 2, or if it looks like a pure integer: 2 / 1.
A // (double slash) sign is an integer divisional operator. It differs from the
standard / operator in two details:
its result lacks the fractional part - it's absent (for integers), or is always equal to zero
(for floats); this means that the results are always rounded;
it conforms to the integer vs. float rule.
As you can see, integer by integer division gives an integer result. All other cases produce
floats.
Look at the following snippet:
print(6 // 4)
print(6. // 4)
The result of integer division is always rounded to the nearest integer value that is less than
the real (not rounded) result.
Look at the code below and try to predict the results once again:
print(-6 // 4)
print(6. // -4)
Note: some of the values are negative. This will obviously affect the result. But how?
The result is two negative twos. The real (not rounded) result is -1.5 in both cases.
However, the results are the subjects of rounding. The rounding goes toward the lesser
integer value, and the lesser integer value is -2 , hence: -2 and -2.0 .
tax = round(tax, 0)
print("The tax is:", tax, "thalers")
if (year%4!=0):
print("it's a common year")
elif (year%100!=0):
print("it's a leap year")
elif (year%400!=0) :
print("it's a common year")
else:
print("it's a leap year")