Programming 2

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Take a look at the snippet - try to predict its result and then run it: print(14 % 4)

As you can see, the result is two. This is why: 14 // 4 gives 3 → this is the integer quotient; 3 * 4 gives 12 → as a result of quotient and divisor multiplication; 14 - 12 gives 2 → this is the remainder.

Leaving comments in code: why, how, and when

In Python, a comment is a piece of text that begins with a # (hash) sign and extends to the end of the line. If you want a comment that spans several lines, you have to put a hash in front of them all.

List of priorities

Priority 1+, - unary 2** 3*, /, % 4+, - binary

We've said previously that the print() function separates its outputted arguments with spaces. This behavior can be changed, too.

The keyword argument that can do this is named sep (like separator). The sep argument delivers the following results: My-name-is-Monty-Python. output The print() function now uses a dash, instead of a space, to separate the outputted arguments.

The way in which we are passing the arguments into the print() function is the most common in Python,

and is called the positional way (this name comes from the fact that the meaning of the argument is dictated by its position, e.g., the second argument will be outputted after the first, not the other way round).

Coding floats

A physical constant called Planck's constant (and denoted as h), according to the textbooks, has the value of: 6.62607 x 10-34. If you would like to use it in a program, you should write it this way: 6.62607E-34 Note: the fact that you've chosen one of the possible forms of coding float values doesn't mean that Python will present it the same way. Python always chooses the more economical form of the number's presentation, and you should take this into consideration when creating literals.

What are variables?

It offers special "boxes" (containers) for that purpose, and these boxes are called variables - the name itself suggests that the content of these containers can be varied in (almost) any way. What does every Python variable have? a name; a value (the content of the container) Let's start with the issues related to a variable's name. Variables do not appear in a program automatically

Operators and parentheses

Of course, you're always allowed to use parentheses, which can change the natural order of a calculation. In accordance with the arithmetic rules, subexpressions in parentheses are always calculated first. You can use as many parentheses as you need, and they're often used to improve the readability of an expression, even if they don't change the order of the operations.

Where do the functions come from?

They may come from Python itself 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 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).

Python's syntax is quite specific in this area.

Unlike most programming languages, Python requires that there cannot be more than one instruction in a line. A line can be empty (i.e., it may contain no instruction at all) but it must not contain two, three or more instructions. This is strictly prohibited.

Assigning a new value to an already existing variable How do you assign a new value to an already created variable? In the same way. Look at the code below: var = 1 print(var) var = var + 1 print(var) The code sends two lines to the console: 1 2 output The first line of the snippet creates a new variable named var and assigns 1 to it. The statement reads: assign a value of 1 to a variable named var. We can say it shorter: assign 1 to var. Some prefer to read such a statement as: var becomes 1. The third line assigns the same variable with the new value taken from the variable itself, summed with 1. Seeing a record like that, a mathematician would probably protest - no value may be equal to itself plus one. This is a contradiction. But Python treats the sign = not as equal to, but as assign a value. So how do you read such a record in the program? Take the current value of the variable var, add 1 to it and store the result in the variable var. In effect, the value of variable var has been incremented by one, which has nothing to do with comparing the variable with any value.

You just need to use the equal sign. The equal sign is in fact an assignment operator. Although this may sound strange, the operator has a simple syntax and unambiguous interpretation. It assigns the value of its right argument to the left, while the right argument may be an arbitrarily complex expression involving literals, operators and already defined variables.

As we said before, a function may have:

an effect; a result.There's also a third, very important, function component - the argument(s). Mathematical functions usually take one argument, e.g., sin(x) takes an x, which is the measure of an angle. Python functions, on the other hand, are more versatile. Depending on the individual needs, they may accept any number of arguments

the program invokes the print() function twice, and you can see two separate lines in the console (there are some exceptions to this rule, but you can ignore them for now)

- this means that print() begins its output from a new line each time it starts its execution; each print() invocation contains a different string, as its argument and the console content reflects it - this means that the instructions in the code are executed in the same order in which they have been placed in the source file; no next instruction is executed until the previous one is completed

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

1. What is the effect the print() function causes? 2. What arguments does print() expect? 3. What value does the print() function evaluate? None. Its effect is enough - print() does not evaluate anything.

The only argument delivered to the print() function in this example is a string: print("Hello, World!")

Almost anything you put inside the quotes will be taken literally, not as code, but as data. Try to play with this particular string - modify it, enter some new content, delete some of the existing content.

More about input() and type casting

Having a team consisting of the trio input()-int()-float() opens up lots of new possibilities.

Type conversion: str()

You already know how to use the int() and float() functions to convert a string into a number. This type of conversion is not a one-way street. You can also convert a number into a string, which is way easier and safer - this operation is always possible. A function capable of doing that is called str(): str(number)

You use

literals to encode data and to put them into your code.

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.

The result clearly shows that

the exponentiation operator uses right-sided binding.

Arithmetic operators: division

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.

The next operator is quite a peculiar one, because it has no equivalent among traditional arithmetic operators.

Its graphical representation in Python is the % (percent) sign, which may look a bit confusing. Try to think of it as of a slash (division operator) accompanied by two funny little circles. The result of the operator is a remainder left after the integer division. In other words, it's the value left over after dividing one value by another to produce an integer quotient. Note: the operator is sometimes called modulo in other programming languages.

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

Its left argument is the base, its right, the exponent. Classical mathematics prefers notation with superscripts, just like this: 23. Pure text editors don't accept that, so Python uses ** instead, e.g., 2 ** 3. 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. This is an important distinction to remember.

Correct and incorrect variable names

Note that the same restrictions apply to function names. Python does not impose restrictions on the length of variable names, but that doesn't mean that a long variable name is always better than a short one. Python lets you use not only Latin letters but also characters specific to languages that use other alphabets. These variable names are also correct: Adiós_Señora, sûr_la_mer, Einbahnstraße, переменная. And now for some incorrect names: 10t (does not begin with a letter), Exchange Rate (contains a space) NOTE The PEP 8 -- Style Guide for Python Code recommends the following naming convention for variables and functions in Python: variable names should be lowercase, with words separated by underscores to improve readability (e.g., var, my_variable) function names follow the same convention as variable names (e.g., fun, my_function) it's also possible to use mixed case (e.g., myVariable), but only in contexts where that's already the prevailing style, to retain backwards compatibility with the adopted convention.

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.

Type casting .

Python offers two simple functions to specify a type of data and solve this problem - here they are: int() and float(). Their names are self-commenting: the int() function takes one argument (e.g., a string: int(string)) and tries to convert it into an integer; if it fails, the whole program will fail too (there is a workaround for this situation, but we'll show you this a little later); the float() function takes one argument (e.g., a string: float(string))and tries to convert it into a float (the rest is the same).

Strings Note: you don't need to do any escaping here.

Strings are used when you need to process text (like names of all kinds, addresses, novels, etc.), not numbers. However, there is a catch. The catch is how to encode a quote inside a string which is already delimited by quotes. Let's assume that we want to print a very simple message saying: I like "Monty Python" How do we do it without generating an error? There are two possible solutions. The first is based on the concept we already know of the escape character, which you should remember is played by the backslash. The backslash can escape quotes too. A quote preceded by a backslash changes its meaning - it's not a delimiter, but just a quote. This will work as intended: print("I like \"Monty Python\"") Note: there are two escaped quotes inside the string - can you see them both? The second solution may be a bit surprising. Python can use an apostrophe instead of a quote. Either of these characters may delimit strings, but you must be consistent. If you open a string with a quote, you have to close it with a quote. If you start a string with an apostrophe, you have to end it with an apostrophe. This example will work too: print('I like "Monty Python"')

Replication

The * (asterisk) sign, when applied to a string and number (or a number and string, as it remains commutative in this position) becomes a replication operator:

Concatenation

The + (plus) sign, when applied to two strings, becomes a concatenation operator: string + string It simply concatenates (glues) two strings into one. Of course, like its arithmetic sibling, it can be used more than once in one expression, and in such a context it behaves according to left-sided binding. In contrast to its arithmetic sibling, the concatenation operator is not commutative, i.e., "ab" + "ba" is not the same as "ba" + "ab". Don't forget - if you want the + sign to be a concatenator, not an adder, you must ensure that both its arguments are strings. You cannot mix types here.

Operators: addition

The addition operator is the + (plus) sign, which is fully in line with mathematical standards. Again, take a look at the snippet of the program below: print(-4 + 4) print(-4. + 8) The subtraction operator, unary and binary operators The subtraction operator is obviously the - (minus) sign, although you should note that this operator also has another meaning - it can change the sign of a number.

Operators and their bindings

The binding of the operator determines the order of computations performed by some operators with equal priority, put side by side in one expression. Most of Python's operators have left-sided binding, which means that the calculation of the expression is conducted from left to right.

Ints vs. floats

The decimal point is essentially important in recognizing floating-point numbers in Python. Look at these two numbers: 4 4.0 You may think that they are exactly the same, but Python sees them in a completely different way. 4 is an integer number, whereas 4.0 is a floating-point number. The point is what makes a float. On the other hand, it's not only points that make a float. You can also use the letter e. 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.

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

The input() function with an argument

The input() function can do something else: it can prompt the user without any help from print(). We've modified our example a bit, look at the code: anything = input("Tell me anything...") print("Hmm...", anything, "...Really?") Note: the input() function is invoked with one argument - it's a string containing a message; the message will be displayed on the console before the user is given an opportunity to enter anything; input() will then do its job. This variant of the input() invocation simplifies the code and makes it clearer. The result of the input() function We've said it already, but it must be unambiguously stated once again: the result of the input() function is a string. This means that you mustn't use it as an argument of any arithmetic

The input() function

The meaning of the new function is to return a very usable result. The function is named input(). The name of the function says everything. The input() function is able to read data entered by the user and to return the same data to the running program. note: you need to assign the result to a variable; this is crucial - missing out this step will cause the entered data to be lost; then we use the print() function to output the data we get, with some additional remarks.

Python offers another mechanism for the passing of arguments, In the editor window you can see a very simple example of using a keyword argument. In order to use it, it is necessary to know some rules:

The mechanism is called keyword arguments. The name stems from the fact that the meaning of these arguments is taken not from its location (position) but from the special word (keyword) used to identify them. The print() function has two keyword arguments that you can use for your purposes. 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)

Operators and their priorities

The phenomenon that causes some operators to act before others is known as the hierarchy of priorities. Python precisely defines the priorities of all operators, and assumes that operators of a larger (higher) priority perform their operations before the operators of a lower priority. So, if you know that * has a higher priority than +, the computation of the final result should be obvious.

Keywords

They are called keywords or (more precisely) reserved keywords. They are reserved because you mustn't use them as names: neither for your variables, nor functions, nor any other named entities you want to create. The meaning of the reserved word is predefined, and mustn't be changed in any way. Fortunately, due to the fact that Python is case-sensitive, you can modify any of these words by changing the case of any letter, thus creating a new word, which is not reserved anymore. For example - you can't name your variable like this: import You mustn't have a variable named in such a way - it is prohibited. But you can do this instead: Import These words might be a mystery to you now, but you'll soon learn the meaning of them.

Floats Python will not accept that, or (in very rare but possible cases) may misunderstand your intentions, as the comma itself has its own reserved meaning in Python. If you want to use just a value of two and a half, you should write it as shown above. Note once again - there is a point between 2 and 5 - not a comma. As you can probably imagine, the value of zero point four could be written in Python as: 0.4 In essence, you can write the value 0.4 as: .4 For example: the value of 4.0 could be written as: 4. This will change neither its type nor its value.

They are the numbers that have (or may have) a fractional part after the decimal point, and although such a definition is very poor, it's certainly sufficient for what we wish to discuss. Whenever we use a term like two and a half or minus zero point four, we think of numbers which the computer considers floating-point numbers: 2.5 -0.4 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. But don't forget this simple rule - you can omit zero when it is the only digit in front of or after the decimal point.

unary and binary

This is a great opportunity to present a very important distinction between unary and binary operators. In subtracting applications, the minus operator expects two arguments: the left (a minuend in arithmetical terms) and right (a subtrahend). For this reason, the subtraction operator is considered to be one of the binary operators, just like the addition, multiplication and division operators.

The input() function - prohibited operations

This is prohibited. This should be obvious - can you predict the value of "to be or not to be" raised to the power of 2? We can't. Python can't either.

Shortcut operators

Very often, we want to use one and the same variable both to the right and left sides of the = operator. For example, if we need to calculate a series of successive values of powers of 2, we may use a piece like this: x = x * 2 You may use an expression like this if you can't fall asleep and you're trying to deal with it using some good, old-fashioned methods: sheep = sheep + 1 Python offers you a shortened way of writing operations like these, which can be coded as follows: x *= 2 sheep += 1

Creating variables

What can you put inside a variable? Anything. You can use a variable to store any value of any of the already presented kinds, and many more of the ones we haven't shown you yet. The value of a variable is what you have put into it. It can vary as often as you need or want. It can be an integer one moment, and a float a moment later, eventually becoming a string. Let's talk now about two important things - how variables are created, and how to put values inside them (or rather - how to give or pass values to them). REMEMBER A variable comes into existence as a result of assigning a value to it. Unlike in other languages, you don't need to declare it in any special way. If you assign any value to a nonexistent variable, the variable will be automatically created. You don't need to do anything else. The creation (or otherwise - its syntax) is extremely simple: just use the name of the desired variable, then the equal sign (=) and the value you want to put into the variable.

Using variables

You're allowed to use as many variable declarations as you need to achieve your goal, like this: var = 1 account_balance = 1000.0 client_name = 'John Doe' print(var, account_balance, client_name) print(var) You're not allowed to use a variable which doesn't exist, though (in other words, a variable that was not given a value). This example will cause an error: var = 1 print(Var) We've tried to use a variable named Var, which doesn't have any value (note: var and Var are different entities, and have nothing in common as far as Python's concerned). REMEMBER You can use the print() statement and combine text and variables using the + operator to output strings and variables, e.g.:

We've shown it already, but we want to emphasize this phenomenon once more -

a string can be empty - it may contain no characters at all. An empty string still remains a string:

Through this example, you encounter two different types of literals: .

a string, which you already know, and an integer number, something completely new. The print() function presents them in exactly the same way Internally, in the computer's memory, these two values are stored in completely different ways - the string exists as just a string - a series of letters. The number is converted into machine representation (a set of bits). The print() function is able to show them both in a form readable to humans.

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 or some values (e.g., the square root of a value or the length of a given text); this is what makes Python's functions the relatives of mathematical concepts.

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. 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. 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. NOTE Integer division can also be called floor division. You will definitely come across this term in the future.

Integers 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. Both of these kinds of numbers differ significantly in how they're stored in a computer memory and in the range of acceptable values. The characteristic of the numeric value which determines its kind, range, and application, is called the type.

If you want to give a name to a variable, you must follow some strict rules:

the name of the variable must be composed of upper-case or lower-case letters, digits, and the character _ (underscore) the name of the variable must begin with a letter; the underscore character is a letter; upper- and lower-case letters are treated as different (a little differently than in the real world - Alice and ALICE are the same first names, but in Python they are two different variable names, and consequently, two different variables); the name of the variable must not be any of Python's reserved words (the keywords - we'll explain more about this soon).

The backslash (\) has a very special meaning

when used inside strings - this is called the escape character. The word escape should be understood specifically - it means that the series of characters in the string escapes for the moment (a very short moment) to introduce a special inclusion. 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.

If you want to deliver one or more arguments to a function,

you place them inside the parentheses. If you're going to use a function which doesn't take any argument, you still have to have the parentheses. Note: to distinguish ordinary words from function names, place a pair of empty parentheses after their names, even if the corresponding function wants one or more arguments. This is a standard convention.


Set pelajaran terkait

Microbiologie de la maladie paradontale DMD part1 (p.1-38)

View Set

Alternative Modalities Chapter 5 MedSurg I

View Set