CoCalc Shared Filesfirst-steps / tuples.ipynb
Author: rieszbanach rieszbanach
Views : 7
#### A feature of the Python environment is its interactive console allowing you to both use Python as a desktop programmable calculator and also as an environment to write and test snippets of code. The read-evaluate-print loop of the console is a very convenient way to interact with a larger code base, such as to run functions and methods or to create instances of classes. This is one of the major advantages of Python over compiled languages such as C/C++ or Java, where the write-compile-test-recompile cycle can increase development time considerably compared to Python's read - evaluate - print loop. Being able to type in expressions and get an immediate response can greatly speed up data science tasks.

The standard way to execute Python code is to run the program directly through the Python interpreter. On most systems, the Python interpreter is invoked using the python command. When a Python source file is passed as an argument to this command, the Python code in the file is executed.

Here the file hello.py contains the single line:g

In addition to exectuting Python script files, a Python interpreter can also be used as an interactive console (also known as a REPL: Read – Evaluate – Print – Loop). Entering python at the command prompt (without any Python files as argument) launches the Python interpreter in an interactive mode. When doing so you are presented with a prompt:

Variables are labels attached to objects; they are not the object itself. They are not containers for objects either. A variable does not contain the object, rather it acts as a pointer or reference to an object. For example, consider the following code:

Python is a dynamically typed language. Variable names can be bound to different values and types during program execution. Each value is of a type, a string, or integer for example; however, the name that points to this value does not have a specific type

It is important to understand the scoping rules of variables inside functions. Each time a function executes, a new local namespace is created. This represents a local environment that contains the names of the parameters and variables that are assigned by the function. To resolve a namespace when a function is called, the Python interpreter first searches the local namespace (that is, the function itself) and if no match is found, it searches the global namespace. This global namespace is the module in which the function was defined. If the name is still not found, it searches the built-in namespace. Finally, if this fails then the interpreter raises a NameError exception. Consider the following code:

In [2]:
  a=10; b=20
def my_function():
global a
a=11; b=21
my_function()
print(a) #prints 11
print(b) #prints 20

 File "<ipython-input-2-ab0469751b29>", line 2 def my_function(): ^ IndentationError: unexpected indent 
Python programs consist of a sequence of statements. The interpreter executes each statement in order until there are no more statements. This is true if both files run as the main program as well as files that are loaded via import. All statements, including variable assignment, function definitions, class definitions, and module imports, have equal status. There are no special statements that have higher priority than any other and every statement can be placed anywhere in a program. There are two main ways of controlling the flow of program execution, conditional statements and loops.

Python contains 12 built-in data types. These include four numeric types (int, float, complex, bool), four sequence types (str, list, tuple, range), one mapping type (dict), and two set types. It is also possible to create user-defined objects such as functions or classes. We will look at the string and the list data types in this chapter and the remaining built-in types in the next chapter.

All data types in Python are objects. In fact, pretty much everything is an object in Python, including modules, classes, and functions, as well as literals such as strings and integers. Each object in Python has a type, a value, and an identity. When we write greet = "hello world" we are creating an instance of a string object with the value "hello world" and the identity of greet. The identity of an object acts as a pointer to the object's location in memory. The type of an object, also known as the object's class, describes the object's internal representation as well as the methods and operations it supports. Once an instance of an object is created, its identity and type cannot be changed.

We can get the identity of an object by using the built-in function id(). This returns an identifying integer and on most systems this refers to its memory location, although you should not rely on this in any of your code.

Strings, like all sequence types, support indexing and slicing.

When we are working with lists, and other container objects, it is important to understand the internal mechanism that Python uses to copy them. Python creates real copies only if it has to. When we assign the value of a variable to another variable, both of these variables point to the same memory location. A new slot in memory will only be allocated if one of the variables changes.

In [ ]:
def wordcount(fname):
try:
fhand=open(fname)
except:
print('File cannot be opened')
exit()

count= dict()
for line in fhand:
words = line.split()
for word in words:
if word not in count:
count[word] = 1
else:
count[word] += 1
return(count)

This will return a dictionary with an element for each unique word in the text file. A common task is to filter items such as these into subsets we are interested in.

In [ ]:
count=wordcount('alice.txt')
filtered = { key:value for key, value in count.items() if value  < 20 and value > 15 }

Unlike sequence types, set types do not provide any indexing or slicing operations. There are also no keys associated with values, as is the case with dictionaries. There are two types of set objects in Python, the mutable set object and the immutable frozenset object. Sets are created using comma-separated values within curly braces. By the way, we cannot create an empty set using a={}, because this will create a dictionary. To create an empty set, we write either a=set() or a=frozenset().


It is worth noting that most of the programming languages employ a logical statement defining the initialization, condition, and increment for running the code. Python programs employ a different strategy where an array is employing a condition and the loop simply iterates on each member of the array. This is important for Python programs since Python is an interpretive language and is inherently slower in operation. Spending time checking a condition each time the loop wishes to take a step is a computationally costly affair. Hence, Python devises the computation in such a way that once a list/array is formed as per the defined condition, the loop can then run a list/array members. In this way, the overall computation time can be reduced.

GARBAGE COLLECTION
What happened with the integer object 20, which was created at line 7? This object was dereferenced. Consequently, this memory location must be deallocated; its status should change from currently-in-use to available-for-reuse. This process is called garbage collection and is very important for efficient memory management. Python performs this automatically.
One of the most primitive methods is to maintain a reference count. For every object, a count of the total number of references to that object is maintained. If that count ever falls to 0, it is immediately deallocated. But more advanced algorithms [3, 4] are now used for the purpose of ruling out cases where this primitive idea may pose a problem. Unfortunately, discussing the ideas about Python’s way of garbage collection is beyond the scope of this book. If you are interested in this topic, the following references will help in this regard [5, 6, 7].

In fact, Python provides enough flexibility with functions that there are actually several different types of functions, reflecting the various forms of declaration and purposes

In [1]:
def sumaCuadrados(*nums):
return sum([num**2 for num in nums])

In [2]:
sumaCuadrados(1,3,5)

35
In [3]:
def sumaEnesimaPow(n,*nums):
return sum([num**n for num in nums])

In [4]:
sumaEnesimaPow(2,1,3,5)

35
In [5]:
def sumaEnesimaPowHastaM(n,m):
return sum([num**n for num in list(range(m+1))])

In [6]:
sumaEnesimaPowHastaM(1,9)

45
In [ ]:


In [ ]:
!ls


In [ ]:


In [ ]:
!virtualenv

In [ ]:
sum([5,7])


In [ ]:
y=[5,7]

In [ ]:
sum(y)

In [ ]:
sum(y[:])

In [ ]:


In [ ]:
sum(elem**2 for elem in y)

In [ ]:
C='cara';S='sello'
diccionario={(C,C):1/16, (C,S):3/16, (S,C):3/16, (S,S):9/16}
sum([diccionario[evento]*evento.__contains__(S) for evento in diccionario])


In [ ]:
#rso1,curso2,curso3
#objeto1,objeto2,
#cual es el indice del elemento de tal tipo

In [ ]:
import csv


In [ ]:
datos="1,2,3\n,4,5,6\n"
arxiv.write(datos)
arxiv.close()

In [ ]:
!ls


In [ ]:
archiv=open('datosSeparados.csv','r')