






Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!







In Python, there are two type conversion functions for this purpose, called int (for integers) and float (for floating- point numbers).
a variable holds a value
type()
and not or Use them to write more complex logical tests
An if statement tests for a condition, and then responds to that condition. Every if statement evaluates to True or False. If the condition is true, then the code listed next gets executed. You can test for multiple conditions at the same time, and respond appropriately to each condition.
ALGORITHM Informally, an algorithm is like a recipe. It provides a set of instructions that tells us how to do something. More precisely, an algorithm describes a process that ends with a solution to a problem. An algorithm has the following features:
interactions among program components also decreases. The use of cooperating subprograms to solve problems is called procedural programming. Although procedural programming takes a step in the direction of controlling program complexity, it simply masks and ultimately recapitulates the problems of imperative programming at a higher level of abstraction. When many subprograms share and modify a common data pool, it becomes difficult once again for the programmer to keep track of all of the interactions among the subprograms during verification and maintenance. One cause of this problem is the use of the assignment statement to modify data. Some computer scientists have developed a style of programming that dispenses with assignment altogether. This radically different approach, called functional programming, views a program as a set of cooperating functions. A function in this sense is a highly restricted subprogram. Its sole purpose is to transform the data in its arguments into other data, its returned value. Because assignment does not exist, functions perform computations by either evaluating expressions or calling other functions. Selection is handled by a conditional expression, which is like an if-else statement that returns a value, and iteration is implemented by recursion. By restricting how functions can use data, this very simple model of computation dramatically reduces the conceptual complexity of programs. However, some argue that this style of programming does not conveniently model situations where data objects must change their state. Object-oriented programming attempts to control the complexity of a program while still modeling data that change their state. This style divides up the data into relatively small units called objects. Each object is then responsible for managing its own data. If an object needs help with its own tasks, it can call upon another object or relies on methods defined in its superclass. The main goal is to divide responsibilities among small, relatively independent or loosely coupled components. Cooperating objects, when they are well designed, decrease the likelihood that a system will break when changes are made within a component. Although object-oriented programming has become quite popular, it can be overused and abused. Many small and medium-sized problems can still be solved effectively, simply, and— most important—quickly using any of the other three styles of programming mentioned here, either individually or in combination. The solutions of problems, such as numerical computations, often seem contrived when they are cast in terms of objects and classes. For other problems, the use of objects is easy to grasp, but their implementation in the form of classes reflects a complex model of computation with daunting syntax and semantics. Finally, hidden and unpleasant interactions can lurk in poorly designed inheritance hierarchies that resemble those afflicting the most brittle procedural programs.
we are supposing to program a machine according to a structured approach and by using an "imperative" language as Python. How can we describe an algorithm to solve a simple or complex problem according to structured programming paradigm?
In programming, a data type consists of a set of values and a set of operations that can be performed on those values. A literal is the way a value of a data type looks to a programmer. int and float data types, are called numeric data types, because they represent numbers.
STRING LITERALS In Python, a string literal is a sequence of characters enclosed in single or double quotation marks. The two string literals ('' and "") represent the empty string. Although it contains no characters, the empty string is a string nonetheless. Note that the empty string is different from a string that contains a single blank space character, " ". Double-quoted strings are handy for composing strings that contain single quotation marks or apostrophes. Note that the print function displays the nested quotation mark but not the enclosing quotation marks. A double quotation mark can also be included in a string literal if one uses the single quotation marks to enclose the literal. If you want to output the string as a single line, you have to include the entire string literal (including its opening and closing quotation marks) in the same line of code. To output a paragraph of text that contains several lines, you could use a separate print function call for each line. However, it is more convenient to enclose the entire string literal, line breaks and all, within three consecutive quotation marks (either single or double) for printing. When you evaluate a string in the Python shell without the print function, you can see the literal for the newline character, \n, embedded in the result. The newline character \n is called an escape sequence. You can join two or more strings to form a new string using the concatenation operator +. The * operator allows you to build a string by repeating another string a given number of times. The left operand is a string, and the right operand is an integer. VARIABLES AND THE ASSIGNMENT STATEMENT a variable associates a name with a value, making it easy to remember and use the value later in a program. In general, a variable name must begin with either a letter or an underscore (_), and can contain any number of letters, digits, or other underscores. Variables receive their initial values and can be reset to new values with an assignment statement. The simplest form of an assignment statement is the following: ** = ** The Python interpreter first evaluates the expression on the right side of the assignment symbol and then binds the variable name on the left side to this value. When this happens to the variable name for the first time, it is called defining or initializing the variable. Note that the = symbol means assignment, not equality. After you initialize a variable, subsequent uses of the variable name in expressions are known as variable references. Variables serve two important purposes in a program. They help the programmer keep track of data that change over time. They also allow the programmer to refer to a complex piece of information with a simple name. Such a process of simplification is called abstraction, and it is one of the fundamental ideas of computer science. PROGRAM COMMENTS AND DOCSTRINGS A comment is a piece of program text that the computer ignores but that provides useful documentation to programmers. mentation to programmers. At the very least, the author of a program can include his or her name and a brief statement about the program’s purpose at the beginning of the program file. This type of comment, called a docstring, is a multi-line string of the form discussed earlier in this section. addition to docstrings, end-of-line comments can document a program. These comments begin with the # symbol and extend to the end of a line. An end-of- line comment might explain the purpose of a variable or the strategy used by a piece of code, if it is not already obvious. INTEGERS the integers include 0, the positive whole numbers, and the negative whole numbers. Integer literals in a Python program are written without commas, and a leading negative sign indicates a negative value. The most common implementation of the int data type. FLOATING-POINT NUMBERS Real numbers have infinite precision, which means that the digits in the fractional part can continue forever. Like the integers, real numbers also have an infinite range. However, because a computer’s memory is not infinitely large, a computer’s memory limits not only the range but also the precision that can be represented for real numbers. Python uses floating-point numbers to represent real numbers. Values of the most common implementation of Python’s float type range from approximately 210308 to 10308 and have 16 digits of precision. A floating-point number can be written using either ordinary decimal notation or scientific notation. BOOLEAN DATA TYPE The Boolean data type consists of only two data values—true and false. In Python, Boolean literals can be written in several ways, but most programmers prefer to use the standard values True and False. BOOLEAN LOGICAL OPERATOR
**if : ** Occasionally, a program is faced with testing several conditions that entail more than two alternative courses of action. Occasionally, a program is faced with testing several conditions that entail more than two alternative courses of action. The multi-way if statement considers each condition until one evaluates to True or they all evaluate to False. When a condition evaluates to True, the corresponding action is performed and control skips to the end of the entire selection statement. If no condition evaluates to True, then the action after the trailing else is performed. The syntax of the multi-way if statement is the following: **if :
elif :
else: ** Once again, indentation helps the human reader and the Python interpreter to see the logical structure of this control statement. THE WHILE LOOP Many situations, however, the number of iterations in a loop is unpredictable. The loop eventually completes its work, but only when a condition changes. This type of process is called conditional iteration, meaning that the process continues to repeat as long as a condition remains. the while loop to describe conditional iteration. Conditional iteration requires that a condition be tested within the loop to determine whether the loop should continue. Such a condition is called the loop’s continuation condition. If the continuation condition is false, the loop ends. If the continuation condition is true, the statements within the loop are executed again. The syntax of while control loop is: **while : ** The form of this statement is almost identical to that of the one-way selection statement. However, the use of the reserved word while instead of if indicates that the sequence of statements might be executed many times, as long as the condition remains true. Clearly, something eventually has to happen within the body of the loop to make the loop’s continuation condition become false. Otherwise, the loop will continue forever, an error known as an infinite loop. At least one statement in the body of the loop must update a variable that affects the value of the condition. The while loop is also called an entry-control loop, because its condition is tested at the top of the loop. This implies that the statements within the loop can execute zero or more times. Although the while loop can be complicated to write correctly, it is possible to simplify its structure and thus improve its readability. The first example script of this section, which contained two input statements, is a good candidate for such improvement. This loop’s structure can be simplified if we receive the first input inside the loop and break out of the loop if a test shows that the continuation condition is false. This implies postponing the actual test until the middle of the loop. Python includes a break statement that will allow us to make this change in the program.
Unlike an integer, which cannot be decomposed into more primitive parts, a string is a data structure. A data structure is a compound unit that consists of several other pieces of data. A string is a sequence of zero or more characters. Recall that you can mention a Python string using either single quote marks or double quote marks. Note that the shell prints a string using single quotes, even when you enter it using double quotes. The string is an immutable data structure. This means that its internal data elements, the characters, can be accessed, but cannot be replaced, inserted, or removed. though a simple for loop can access any of the characters in a string, sometimes you just want to inspect one character at a given position without visiting them all. The subscript operator [] makes this possible. The simplest form of the subscript operation is the following: [] The first part of this operation is the string you want to inspect. The integer expression in brackets indicates the position of a particular character in that string. The integer expression is also called an index. Note that attempting to access a character using a position that equals the string’s
length results in an error. The positions usually range from 0 to the length minus 1. However, Python allows negative subscript values to access characters at or near the end of a string. The programmer counts backward from –1 to access characters from the right end of the string. Some applications extract portions of strings called substrings. You can use Python’s subscript operator to obtain a substring through a process called slicing. To extract a substring, the programmer places a colon (:) in the subscript. An integer value can appear on either side of the colon. Generally, when two integer positions are included in the slice, the range of characters in the substring extends from the first position up to but not including the second position. When the integer is omitted on either side of the colon, all of the characters extending to the end or the beginning are included in the substring. Example: name = "myfile.txt" name[0:] 'myfile.txt' name[0:1] 'm' name[0:2] 'my' we use the string method split to obtain a list of the words contained in an input string. Example: sentence = input("Enter a sentence: ") listOfWords = sentence.split() A method behaves like a function but has a slightly different syntax. Unlike a function, a method is always called with a given data value called an object, which is placed before the method name in the call. The syntax of a method call is the following: .(,..., )ù STRING METHODS s.center(width) - Returns a copy of s centered within the given number of columns. s.count(sub [, start [, end]]) - Returns the number of non-overlapping occurrences of substring sub in s. Optional arguments start and end are interpreted as in slice notation. s.endswith(sub ) - Returns True if s ends with sub or False otherwise. s.find(sub [, start [, end]]) - Returns the lowest index in s where substring sub is found. Optional arguments start and end are interpreted as in slice notation. s.isalpha() - Returns True if s contains only letters or False otherwise. s.isdigit() - Returns True if s contains only digits or False otherwise. s.join(sequence) - Returns a string that is the concatenation of the strings in the sequence. The separator between elements is s. s.lower() - Returns a copy of s converted to lowercase. s.replace(old, new [, count]) - Returns a copy of s with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. s.split([sep]) - Returns a list of the words in s , using sep as the delimiter string. If sep is not specified, any whitespace string is a separator. s. startswith(sub) - Returns True if s starts with sub or False otherwise. s.strip([aString]) - Returns a copy of s with leading and trailing whitespace (tabs, spaces, newlines) removed. If aString is given, remove characters in aString instead. s.upper() - Returns a copy of s converted to uppercase. TEXT FILE METHODS AND FUNCTIONS open(filename, mode) - Opens a file at the given filename and returns a file object. The mode can be 'r', 'w', 'rw', or 'a'. The last two values, 'rw' and 'a', mean read/write and append, respectively. f.close() - Closes an output file. Not needed for input files. f.write(aString) - Outputs aString to a file. f.read() - Inputs the contents of a file and returns them as a single string. Returns "" if the end of file is reached. f.readline() - Inputs a line of text and returns it as a string, including the newline. Returns "" if the end of file is reached.
>>> fruits = ("apple", "banana") >>> fruits ('apple', 'banana') >>> meats = ("fish", "poultry") >>> meats ('fish', 'poultry') >>> food = meats + fruits >>> food ('fish', 'poultry', 'apple', 'banana') >>> veggies = ["celery", "beans"] >> > tuple(veggies) ('celery', 'beans') Collection of values that are relates (like coordinates) we can use the TUPLE. We can access tuple and list in the same way:through indexes (from 0 to (length of the collection - 1)). The differences between list and tuple stay in the semantic area because list is a collection of area in which the data could be of different types (strings, numbers, …) but they are not related one to another; a tuple represents micro-objects that are all associated to one “variable”. The list is a of collection of independent objects. Example: if I want represent the students that are in a class, first creates n tuples (where n is the number of students: so, each tuple for each student) and, then, create a list to group all the n tuples. MAP, OR DICTIONARY, OR VOCABULARY; SET; BAG When we have a collection of data, we provide different names to the collection just according to the kind of data that are into collection. A map is a set of data with no repetition, where all the values are distinguish from one to another. A bag is a collection in which we could, also, have duplicates: a collection of values in which values can be repeated. The bag can complemented in python as a list. If we have a bag and we put the condition in which repetition of data are not allowed, bag becomes a SET If we have two collections of data, the correspondence (the relations) between the two collections, we’re creating a map: that, is, nothingness a list of correspondence. A map is a function that should have some particular properties, like for the first set, which is called the domain, we can relate one and only one object of the second set. Map is implemented in Python with DICTIONARY, in which every data is just a couple. The x in the domain, which has to be unique, is called, in python, the Key: the key information used find the values, that is the correspondence object in the second set. A key should be unique and not undefined: so, we don’t have duplicates. Keys are made of sets of information (because they are unique), while values can be repeated: we have list of values Atomic data type stays fro that a key could not be of any data type besides strings, (I don’t remember)…. In dictionary we have feature that say when we want access to data, we don’t use index, but key.
Defining our own functions allows us to organize our code in existing scripts more effectively. Most of the functions used thus far expect one or more arguments and return a value. The definition of a function consists of a header and a body. The header includes the keyword def as well as the function name and list of parameters. The function’s body contains one or more statements. Here is the syntax: **def (, ..., ): ** The function’s body contains the statements that execute when the function is called. Our function contains a single return statement, which simply returns the result of multiply- ing its argument, named x, by itself. Note that the argument name, also called a parameter, behaves just
like a variable in the body of the function. This variable does not receive an initial value until the function is called. PARAMETERS AND ARGUMENTS A parameter is the name used in the function definition for an argument that is passed to the function when it is called. For now, the number and positions of the arguments of a function call should match the number and positions of the parameters in that function’s definition. Some functions expect no arguments, so they are defined with no parameters. THE RETURN STATEMENT The programmer places a return statement at each exit point of a function when that function should explicitly return a value. The syntax of the return statement for these cases is the following: **return ** Upon encountering a return statement, Python evaluates the expression and immediately transfers control back to the caller of the function. The value of the expression is also sent back to the caller. If a function contains no return statement, Python transfers control to the caller after the last statement in the function’s body is executed, and the special value None is automatically returned.
In scripts that include the definitions of several cooperating functions, it is often useful to define a special function named main that serves as the entry point for the script. This function usually expects no arguments and returns no value. Its purpose might be to take inputs, process them by calling other functions, and print the results. The definition of the main function and the other function definitions need appear in no particular order in the script, as long as main is called at the very end of the script.
Lists organize their elements by position. This mode of organization is useful when you want to locate the first element, the last element, or visit each element in a sequence. How- ever, in some situations, the position of a datum in a structure is irrelevant; we’re interested in its association with some other element in the structure. A dictionary organizes information by association, not position. In computer science, data structures organized by association are also called tables or association lists. In Python, a dictionary associates a set of keys with values. Python dictionary is written as a sequence of key/value pairs separated by commas. These pairs are sometimes called entries. The entire sequence of entries is enclosed in curly braces ({ and }). A colon (:) separates a key and its value. You can even create an empty dictionary—that is, a dictionary that contains no entries. Here is an example of an empty dictionary: {} The keys in a dictionary can be data of any immutable types, including tuples, although keys normally are strings or integers. The associated values can be of any types. ADDING KEYS AND REPLACING VALUES
operation is the following: **[] = ** Example: >>> info = {} >>> info["name"] = "Sandy" >>> info["occupation"] = "hacker" >>> info {'name':'Sandy', 'occupation':'hacker'} The subscript is also used to replace a value at an existing key, as follow: >>> info["occupation"] = "manager" >>> info {'name':'Sandy', 'occupation':'manager'} ACCESSING VALUES You can also use the subscript to obtain the value associated with a key. However, if the key is not
dictionary: >>> info["name"] 'Sandy'