Nothing Special   »   [go: up one dir, main page]

Python - Modul

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Module 1

Computers have their own language, too, called machine language, which is very


rudimentary. A complete set of known commands is called an instruction list, sometimes
abbreviated to IL.

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.

A program written in a high-level programming language is called a source code (in contrast


to the machine code executed by computers). Similarly, the file containing the source code
is called the source file.

Of course, such a composition has to be correct in many senses:

 alphabetically - a program needs to be written in a recognizable script, such as


Roman, Cyrillic, etc.
 lexically - each programming language has its dictionary and you need to master it;
thankfully, it's much simpler and smaller than the dictionary of any natural language;
 syntactically - each language has its rules and they must be obeyed;
 semantically - the program has to make sense.

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.

What does this all mean for you?

 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.

Due to historical reasons, languages designed to be utilized in the interpretation manner


are often called scripting languages, while the source programs encoded using them are
called scripts.
What is Python?
Python is a widely-used, interpreted, object-oriented, and high-level programming language
with dynamic semantics, used for general-purpose programming.

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.

Who created Python?


One of the amazing features of Python is the fact that it is actually one person's work.
Usually, new programming languages are developed and published by large companies
employing lots of professionals, and due to copyright rules, it is very hard to name any of
the people involved in the project. Python is an exception.
There are not many languages whose authors are known by name. Python was created
by Guido van Rossum, born in 1956 in Haarlem, the Netherlands. Of course, Guido van
Rossum did not develop and evolve all the Python components himself.

Python goals
In 1999, Guido van Rossum defined his goals for Python:

 an easy and intuitive language just as powerful as those of the major competitors;


 open source, so anyone can contribute to its development;
 code that is as understandable as plain English;
 suitable for everyday tasks, allowing for short development times.

What makes Python special?


How does it happen that programmers, young and old, experienced and novice, want to use
it? How did it happen that large companies adopted Python and implemented their flagship
products using it?

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.

Of course, Python has its drawbacks, too:

 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.

To start your work, you need the following tools:

 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.

IDLE is an acronym: Integrated Development and Learning Environment.

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.

Where do the functions come from?

 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.

There's also a third, very important, function component - the argument(s).

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.

Three important questions have to be answered as soon as possible:

1. What is the effect the  print()  function causes?

The effect is very useful and very spectacular. The function:

 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.

2. What arguments does  print()  expect?

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() .

3. What value does the  print()  function return?

None. Its effect is enough.

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("The itsy bitsy spider\nclimbed up the waterspout.")

print()

print("Down came the rain\nand washed the spider out.")

print("The itsy bitsy spider" , "climbed up" , "the waterspout.") 

The itsy bitsy spider climbed up the waterspout.

There is one  print()  function invocation, but it contains three arguments. All of them are
strings.

The arguments are separated by commas.

Two conclusions emerge from this example:

 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 order to use it, it is necessary to know some rules:

 a keyword argument consists of three elements: a keyword identifying the


argument ( end  here); an equal sign ( = ); and a value assigned to that argument;
 any keyword arguments have to be put after the last positional argument (this is
very important)

In our example, we have made use of the  end  keyword argument, and set it to a string
containing one space.

n order to use it, it is necessary to know some rules:

 a keyword argument consists of three elements: a keyword identifying the


argument ( end  here); an equal sign ( = ); and a value assigned to that argument;
 any keyword arguments have to be put after the last positional argument (this is
very important)

The default behavior reflects the situation where the end keyword argument


is implicitly used in the following way: end="\n". If you look carefully, you'll see that we've
used the end argument, but the string assigned to it is empty (it contains no characters at
all).
The keyword argument that can do this is named sep (like separator).

print("My", "name", "is", "Monty", "Python.", sep="-") 

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.

3. To call a function (this process is known as function invocation or function call), you


need to use the function name followed by parentheses. You can pass arguments into a
function by placing them inside the parentheses. You must separate arguments with a
comma, e.g.,  print("Hello,", "world!") . An "empty"  print()  function outputs an
empty line to the screen.

4. Python strings are delimited with quotes, e.g.,  "I am a string"  (double quotes), or  'I
am a string, too'  (single quotes).

5. Computer programs are collections of instructions. An instruction is a command to


perform a specific task when executed, e.g., to print a certain message to the screen.

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 .

Integers: octal and hexadecimal numbers


There are two additional conventions in Python that are unknown to the world of mathematics. The first
allows us to use numbers in an octal representation.

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.

0o123  is an octal number with a (decimal) value equal to  83 .

The  print()  function does the conversion automatically. Try this:

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:

 the exponent (the value after the E) has to be an integer;


 the base (the value in front of the E) may be an integer.

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.").

2. The binary system is a system of numbers that employs 2 as the base. Therefore, a


binary number is made up of 0s and 1s only, e.g.,  1010  is 10 in decimal.

Octal and hexadecimal numeration systems, similarly, employ 8 and 16 as their bases


respectively. The hexadecimal system uses the decimal numbers and six extra letters.
3. Integers (or simply ints) are one of the numerical types supported by Python. They are
numbers written without a fractional component, e.g.,  256 , or  -1  (negative integers).

4. Floating-point numbers (or simply floats) are another one of the numerical types


supported by Python. They are numbers that contain (or are able to contain) a fractional
component, e.g.,  1.27 .

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 .

A ** (double asterisk) sign is an exponentiation (power) operator. Its left argument is


the base, its right, the exponent.

Remember: It's possible to formulate the following rules based on this result:

 when both  **  arguments are integers, the result is an integer, too;


 when at least one  **  argument is a float, the result is a float, too.

A  /  (slash) sign is a divisional operator.

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)

that we used  /  instead of  //  - could you predict the results?

Yes, it would be  1.5  in both cases. That's clear.

But what results should we expect with  //  division?

Run the code and see for yourself.

What we get is two ones - one integer and one float.

The result of integer division is always rounded to the nearest integer value that is less than
the real (not rounded) result.

This is very important: rounding always goes to the lesser integer.

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 .

hour = int(input("Starting time (hours): "))


mins = int(input("Starting time (minutes): "))
dura = int(input("Event duration (minutes): "))

# Write your code here.


newmins = mins + dura
newhour = newmins//60
hour = hour + newhour
if (hour < 24):
hour = hour
else:
hour = hour % 24
mins = newmins % 60
print(hour,mins, sep=":")

income = float(input("Enter the annual income: "))


if income <= 85528:
tax = (((18/100)*income)-556.2)
elif income >= 85528:
tax = (14839.2+((32/100)*(income-85528)))

# Write your code here.


#

tax = round(tax, 0)
print("The tax is:", tax, "thalers")

year = int(input("Enter a year: "))

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")

You might also like