timestamp.tm_hour would read the hours from a timestamp.def ja return. Avainsanat ovat siis osa ohjelmointikielen kielioppia.True in Python) and false (False in Python). Things like comparison operators return booleans, and they are often used in conditional statements and while loops. In Python all values are equivalent to one of the boolean values. Generally all so called empty values (0, "", None etc.) are equal to False while the rest are equal to True.and, not, and or - all familiar from conditional statements. Out of these and is True if and only if both operands are True; or is True if at least one operand is True; and not is True is its sole operand is False.\n characters (newline) to indicate line breaks, Windows uses \r\n where the r is a carriage return character. It's a remnant from mechanical typewriters, and indicates the procedure of physically moving the typewriter head to the beginning of the line. In general this is just something that's good to know - Python treats both line breaks quite nicely.python code.py where code.py is the file's name. When you run a code file the return values of individual lines are not shown unless they have been specfically rpinted.python code.py, code.py is actually a command line argument. Command line arguments can be accessed in Python from the sys module's argv variable.THE_ANSWER = 42.print function calls in the code temporarily to either see how far the code gets or what kinds of values variables have. Debugging is such an important part of programming that there are even specific debugging tools that have been developed. We don't use them on this course however.def prompt_length(question, maximum=10): function definition, the maximum parameter has been made optional by giving it the default value of 10.'''document''' or """document""". If a docstring is placed immediately below a function's def statement (indented!), it becomes the function's documentation that is shown with the help function. Likewise a docstring placed at the very beginning of a code file becomes the module's documentation. A good doctstring describes what a function does, and explains its parameters and return values.5 < 4 ei pidä paikkansa, joten kyseinen operaatio evaluoituu epätodeksi. Pythonissa epätotta merkitään avainsanalla False."n" is just the letter n but "\n" is a newline character. In this example the backslash character \ causes the normal interpretation of the n character to be escaped and replaced by another interpretation. The backslash functions as an escape character. One typical use is including " in a string that's delimited with ": "donkey ear interval is 14\""Exception is the base class of most common exceptions. We also call it the Pokémon exception because if you use it in a try-except structure it will catch all the exceptions. In most cases this is not a good thing. It makes interpreting problem situations more difficult for both the user, and you, the developer. The latter is due to the fact that it will also catch any mistakes you made in your code, and you won't get any useful information when the program isn't behaving correctly.with open("donkey.txt", "r") as somefile: opens donkey.txt inside a with statement (where files usually should be opened), with somefile as the file handle.{:.2f}) for marking spots where the format method arguments will be placed. Example: "Interval between donkey's ears is {:.2f}".format(measurement).width with the value 15 the name width can later be used to retrieve the variable's value. So the identifier can be thought of as a contract between the programmer and the Python interpreter about the meaning of a certain word in the code. Identifiers always belong to a namespace.grades[0]. Subscription returns an item. Subscription outside the list causes an IndexError exception, and it's good to keep in mind that the last index of a list is its length - 1 (because indexing starts from zero). Index can also be negative - in this case counting starts from the end so that -1 is the last item of the list."Hello {name}".format(name="Hagrid"). Another common use case is with functions that have a whole lot of optional arguments and only some of them need to be given. Using keyword arguments can also make the code generally more readable, especially for arguments that are either True or False.5 + 5 ja "aasi" != "apina" ovat lausekkeita, jotka evaluoituvat arvoiksi 10 ja True. Lauseke yksin ei muuta ohjelman tilaa mitenkään, ellei sillä ole sivuvaikutuksia. Sen sijaan lauseke vaikuttaa osana lausetta.x = 5 and print("donkey"), 5 and "donkey" respectively are literals. The term is used primarily for simple types: numbers, boolean values and strings.for and while.for animal in animals: where animal is the loop variable. If the sequence contains tuples (or lists), a for loop can also have multiple loop variables: for student, grade in grading:. Loop variables are not inside their own scope and must therefore be distinct from other names inside the same function's scope.if __name__ == "__main__": statement. However do not use this statement in the earlier exercises because then the checker cannot execute your program's main program."aasi" tai 'aasi'). Suosimme ensimmäistä. Merkkijono voidaan merkitä myös kolmella merkillä jolloin se voi olla monirivinen – tätä käytetään erityisesti dokumenttimerkkijonojen (docstring) kanssa. Merkkijono on muuntumaton tietotyyppi – kaikki, mikä näennäisesti muokkaa merkkijonoa, tosiasiassa luo (ja palauttaa) siitä muutetun kopion.choice.lower(). Methods are occasionally called "member functions" as well.word.upper() is a method call that operates on the object referred to by the word variable.hogwarts.append("Hufflepuff") changes a list named hogwarts by adding a new value to it. Any references to this list later in the program will access the contents that now include "Hufflepuff".valinta = valinta.lower()"\n" character is a character that, when printed or written to a file produced a line break. If a string is inspected without printing it e.g. in the console, all line breaks are shown as "\n" characters.KeyboardInterrupt-poikkeuksen try-except-rakenteella.valinta.lower()-metodikutsussa valinta on objekti ja lower on ominaisuus."r". There are two writing modes:"w", write, which overwrites anything that may have been in the file previously with the new content."a", append, which writes the contents to the end of an existing file instead5 + 8 is an addition operation and its operands are 5 and 8. Operands can be thought of as the subjects of operations.def prompt_input(question, error_msg): question and error_msg would be parameters. Parameters can also have a default value that will be used as its value if the matching argument is not given in a function call - this makes the argument optional./. When forming path inside code, it's best to use the join function from the os.path module.f"Hi {name}"). Placeholders in strings can also contain additional formatting specifiers like setting the number of decimals to show (f"Donkeys have {average:.2f} legs on average"). When a placeholder is resolved, it is replaced by the value of the variable or statement inside the curly braces.try: että except: aloittavat omat lohkonsa; try-lohkon alle kirjoitetaan se koodi, joka mahdollisesti aiheuttaa jonkun tietyn poikkeuksen ja except-lohkon alle taas se koodi, joka suoritetaan siinä tapauksessa, että kyseinen poikkeus tapahtuu. Joissain muissa ohjelmointikielissä except-avainsanan sijaan käytetään avainsanaa catch, minkä takia yleisesti puhutaan poikkeusten kiinni ottamisesta.result = 10 + 2 * (2 + 3)
print(...) that prints its argument(s) to the terminal.return True there is one return value: the literal boolean value True.page = collection[5:10] - this would make a slice including indices 5...9. The number on the right side of the colon in a slice is the first index that is not included in the result! pass, an informative print, or returning some placeholder default value. In larger projects stub functions sometimes are set to raise a NotImplementedError exception which makes it easy to locate the function that's not ready yet.cd (change directory) and use ipython command to run code files and start the Python console.cmd to the start menu searchterminal to Finderterminal to the search5 > 4 pitää paikkansa, joten kyseinen operaatio evaluoituu todeksi. Pythonissa totta merkitään avainsanalla True."#!python3 (1, 2, 3) but actually this is a tuple even without them: 1, 2, 3. int("123") or float("3.14"). In some cases Python performs type conversion automatically, usually when mathing with floats and integers.input function calls are used to prompt things from the user and print calls can be used to display instructions and results.break keyword is a special instruction that is used in loops. It interrupts the loop's execution immediately, and code execution continues from the first line after the loop. If the loop had an else branch, it is not entered.continue is the other keyword related to loops (the first one being break). Unlike break which interrupts the entire loop, continue only interrupts the current iteration - execution continues from the next iteration. Note that this keyword is only needed in situations where part of the iteration is to be skipped. There's no need to put continue to the end of the loop iteration.enumerate is builtin function that produces a generator-like object in Python. Its primary use is in for loops when the code needs to access the items' indices in addition to the items themselves. The enumerate object produces tuples where the first item is the original item's index and the second item is the original item itself. Use example: for i, character in enumerate(moomin_valley):.f"Interval between donkey's ears is {measurement:.2f} inches" (assuming that a variable named measurement has been definied previously)for is one of the two loop types. It's designated for iterating through data structures. It is used especially with lists. In general, for loops are used when it's possible to determine in advance how many iterations the loop must do. In addition to iterating through structures, for loop is therefore used for doing a certain number of iterations (e.g. 10 iterations). For loop declarion looks like for item in collection: where item would be the name of the loop variable, and collection would be the data structure that is being iterated over.import math) the statement makes a new namespace accessible through the module name. Functions from the imported module can be accessed through its name. It's also possible to directly import some specific names from a module with a from-import statement: from math import ceil. Modules can also be renamed on import: import math as m.while summa < 21. While-silmukat soveltuvat parhaiten sellaisiin tilanteisiin, joissa ei voida etukäteen selvittää montako toistoa tarvitaan - erityisesti syötteiden kysyminen käyttäjältä on tällainen tilanne.with open("donkey.txt") as somefile:. All read or write operations on the file are carried out inside the with statement. When the with statement ends, Python automatically takes care of closing files opened in the with statement.