Python is a programming language created by Guido Van Rossum in 1989, to "correct the problems of other programming languages".
Characteristics of python:
10*13
a=1.25
b=3.14
a*b
import urllib.request
file = urllib.request.urlopen("http://www.fis.unical.it/astroplasmi/primavera/comp_phys/comp_phys.html")
data = file.read()
print( data )
import math
print( math.pi )
type(math.pi)
#dir( math )
#help( math.pi)
Ordinary programming languages generally use variables to store data of various kind: numbers, characters, strings, and so on...
In python, basic variables can be of type: integer, real, character, string.
In ordinary compiled languages the type of the variable MUST be declared BEFORE using the variable and it cannot be changed afterwards! In python (as it is common in interpreted languages) a variable does not need to be declared, the initialization is enough to define the type and it can be re-initialized everywhere by changing its type!
Example:
a=100
type(a)
a=1.2
type(a)
b=18.25
type(b)
s="Ciao!"
type(s)
# This is 2 to 10000!
2**10000
# Square root of 10 (quite close to pi!)
10.0**0.5
# Square root of 1+2I
a=1.0+2.0j
a**0.5
# Here a is re-defined with a boolean value
x=10
a=x>5
a
Examples:
a=12.2
s=str(a)
s
s="3.1415926"
float(s)
s=12345
int(s)
All computer languages define the so-called vectors or arrays.
In python, the same function is accomplished through the lists, that, however, at difference with vectors in other languages, may even contain eterogeneous elements, namely of different types.
Examples:
mylist=[1.2,3.45,7.36,8.55]
mylist
mylist=[1,2,3,"Hello world!"]
mylist
The single elements of the list can be indexed through their position inside the list with an index ranging from 0 to the number of elements minus one. The index has to be surrounded by square brackets:
mylist=[1,3,5,7,9]
mylist[3]
Any element in a list can be modified:
mylist[2]=101
mylist
One may apply the so-called "slicing" to a list, through which several elements can be extracted at the same time (notice that the slicing returns all the elements from the first index to the second minus one!):
mylist[0:3]
A negative index indicates an element, starting from the last one:
mylist[0:-2]
If you do not indicate the first or second element, python assumes the element 0 or the last one, respectively:
Example (prints the last two elements):
mylist[-2:]
mylist[:2]
To eliminate a series of elements from a list, you can assign them to the empty list:
mylist[2:4]=[]
mylist
The slicing may contain a third index, meaning that the elements must be returned from the first to the second index minus one, with a step given by the third index.
Example:
mylist=[1,2,3,4,5,6,7,8,9,10]
mylist[2:10:2]
Examples:
mylist=[1,2,3,4,5]
mylist
mylist.append(10)
mylist
mylist.insert(1,11)
mylist
mylist.extend([20,30,40,50])
mylist
mylist.remove(20)
mylist
mylist.pop()
mylist
mylist.append(1)
mylist.count(1)
mylist
mylist.index(1)
mylist.pop(0)
mylist.index(1)
mylist.reverse()
mylist
mylist.sort()
mylist
# Sorts in reverse order!
mylist.sort(reverse=True)
mylist
The operator "in" returns True or False according to the fact that the left term exists or not in the list
Example:
ll=[1,3,5,7,9,11]
3 in ll
4 in ll
The function len(list) returns the lenght of the list (number of elements). Warning! it is a function, NOT a method!
Example:
ll=[10,20,30,40,50]
print(len(ll))
In python one may create variables with 2 or more indices (like arrays in other languages!) by using lists of lists.
Example:
arr=[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
arr
arr[1]
arr[1][2]
Strings in python may be delimited with either single or double quotes.
Strings can be merged by using the operator "+":
s1="Hello"
s2="world!"
s1 + ' ' + s2
Strings may be repeated by using the operator "*":
s1="Python is "
s2="beautiful, "
s1 + s2 * 10 + "beautiful!"
Strings may contain escape sequences like in C.
s1="Remember to send an email to:\n"
s2="\t"
s3="leonardo.primavera\x40unical.it"
print(s1 + s2 + s3)
Strings may extend on several lines by inserting them between triple single or double quotes:
s="""
This is an example of a very long string...
reallt long...
"""
print(s)
The strings are similar to lists, and the slicing is supported:
s="abcdefghilmnopqrstuvz"
s[1:-1]
s[::4]
However, notice that, at difference with lists, the strings are immutable and cannot be changed!
Example:
s="aeiou"
s[2]="c"
Examples:
s=' abcde '
s.find("c")
s.strip()
s.replace(" ","<<")
s="This string contains some commas, to improve the readibility, however, sometimes, it's better to separate the sentences"
s.split(",")
'/'.join(["12","10","1492"])
Further methods for the strings (as well as for other entities!) may be obtained through the commands: dir(s) or help(s):
dir(s)
Tuple are similar to lists, but they are immutable, like the strings, therefore they cannot be modified!
However, we need them since they are pretty much used, for instance to shape arrays in numpy.
To define a tuple, we use ().
Example:
a=(1,2,3,4,'mha!')
a[1:-1]
a[1]
a[1]=18
Sets are a data type which is similar to sets in mathematics. Through sets, you can manage ensembles of data with no particular order and without duplicates.
To create a set one has to use the set keyword.
Example:
myset = set(["one", "two", "three"])
myset
The initializer of the set can be any sequence of values, like a list in the example above, but also a tuple or a string.
Example:
myset = set( "Hello World!" )
myset
Examples:
myset1=set( "albert einstein" )
myset2=set( "isaac newton" )
myset1, myset2
myset1 | myset2
myset1 - myset2
myset1 & myset2
myset1 ^ myset2
A dictionary in python is an associative array, namely it works like a list, but the values are indexed through a key, instead of a number!
To create a dictionary one has to initialize it with the construct "dict()", then add to it the key-value couples.
Example:
diet=dict()
diet["Pasta"]=125
diet["Meat"]=300
diet["Fruit"]=150
diet
Another way to initialize a dictionary is to put the keys-values couples in brackets {}, separated by a semicolon (:).
Example:
dd={"Meat": 300, "Fruit": 150, "Pasta": 125}
dd
Each value can be recovered through the respective key.
Example:
print(dd["Meat"])
New elements can be added to the dictionary by adding a new key and a new value. Analogously, each key-value couple can be removed with the instruction "del".
Example:
diet["Salad"]="How much as you like!"
diet
del diet["Meat"]
diet
Examples:
diet={"Pasta": 300, "Fruit": 200, "Meat": 200}
diet.keys()
diet.values()
diet.items()
The operator in can be used to check whether a key (or values, etc.) belongs to the dictionary.
Example:
"Meat" in diet.keys()
"Salad" in diet.values()
diet.clear()
diet
Note:
In python 2.7, the methods keys(), values(), etc. returned a list, instead of a set. If one wants to get a list with the keys (or values, etc.) it is possible to use the function list to convert the set to a list.
Example:
diet={1:10, 2:20, 3:30}
mylist=list(diet.keys())
mylist
if cond1: ... elif cond2: ... else: ...Notice that:
Example:
if 1==2:
print("False")
elif 1==3:
print("False")
else:
print("True!")
for var in sequence: ...
for var in "aeiou":
print(var)
Quite useful for the for construct is the function range(start,stop,jump), which returns a list of integers beginning from "start" up to "stop"-1, with jumps of "jump".
Example: computes and prints the sum of the first 20 even numbers...
mysum=0
for i in range(2,21,2):
mysum=mysum+i
print(mysum)
Remarkably, python can make a loop on two or more list at the same time, by taking the numbers as couples, triplets, and so on, through the function zip(list1, list2, etc.), which takes the elements of the various lists one by one and returns those as tuples.
Example:
for a,b in zip([1,2,3],['a','b','c']):
print(a, b)
We may obtain the same effect through the method items of dictionaries, which returns the tuple key-value.
Example:
diet={"Pasta": 350, "Meat": 200, "Eggs": 80, "Fruit": 250}
for food, calories in diet.items():
print("100 grams of ", food, "contains ", calories, " calories")
while (condition): ...
Example: adds up the odd numbers between 1 and 21...
x=1
sum=0
while ( x <= 21 ):
sum=sum+x
x=x+2
print(sum)
Example:
mylist=[0.5, 0.8, 0.3, 1.2, 0.2, 0.1]
print("Initial list: ", mylist)
list_len=len(mylist) # Computes the lenght of the list
num_elem=0
while ( num_elem < list_len ):
# Finds the minimum between the remaining elements in the list
xmin=mylist[num_elem]
xpos=num_elem
for i in range(num_elem,list_len):
if ( mylist[i] < xmin ):
xmin=mylist[i]
xpos=i
print("Minimum among the elements of the list between ", num_elem, " and ", list_len - 1, ": ", xmin, " at position: ", xpos)
# Swaps the current value in the list with the minimum
if ( num_elem != xpos ):
temp=mylist[num_elem]
mylist[num_elem]=xmin
mylist[xpos]=temp
# Prints the partially ordinated list
print("Partially ordered list: ", mylist)
num_elem=num_elem+1
print("Final, sorted, list: ", mylist)
print(elem1, elem2, elem3, ecc., sep=" ", end="\n")
prints an ensemble of values separated by commas, after converting them into strings!. The parameters sep and end are optional and indicates the separator to use when printing several values (default: a blank) and how to terminate the line (default: new-line!).
Example: (note how, though there is no blank between "for", a, "years", the blanks are inserted due to the default value of "sep"!)
a=100
print("Best wishes for", a, "years...")
print always produces a carriage-return unless we use end= something.
Example: prints the Pythagorean table...
for i in range(1,11):
for j in range(1,11):
print(i * j,end=" ")
print()
The operator % helps to build up a string by substituting suitable formats with the values of the variables.
Example:
mystring="I ate %d eggs and %d grams of pasta..." % (3, 100)
print(mystring)
One may use numerical values between "%" and the format ("f", "d", etc.) to delimit the width of the field to print!
Example:
var=100
print("Let the number stay in a fairly large space: %10d" % var)
A negative number aligns to the left.
Example: the Pythagorean table above, a little bit nicer...
for i in range(1,11):
for j in range(1,11):
print("%-4d" % (i * j),end=" ")
print()
*
in between "%" and the format indicates a variable width, which is to be specified among the variables.
Example:
mywidth=10
string1=">>>"
string2="<<<"
print("We are finally at %*sthis%-*s point!" % (mywidth, string1, mywidth, string2))
With this function you can read an input from the keyboard. Note that variable is always read as a string, therefore it must be converted to a different type, if we need it!
Example: solution of a second degree equation...
print("Solution of the equation: a*x^2 + b*x + c = 0")
a = input("Insert a: ")
b = input("Insert b: ")
c = input("Insert c: ")
aa=float(a)
bb=float(b)
cc=float(c)
print("Solutions:")
print("x1 = ", (-bb+((bb*bb-4*aa*cc)**0.5))/(2*aa))
print("x2 = ", (-bb-((bb*bb-4*aa*cc)**0.5))/(2*aa))
object = open( file_name, access_method )where:
When all the read/write operations are ended, the file can be closed with the method close().
After opening the file, the rows can be read with the method readline(), which returns a string (newline included!) from the file. Notice that when we get to the end of the file, an empty string "" is returned.
Example:
f=open("test.dat","r")
str=" "
while str != "":
str=f.readline()
print(str,end="")
f.close()
print(str,end="")
without which some additional newline would be printed, because it is read with the string from the file!
The method readlines() is often easier to use because it returns a list containing all the lists read from the lines of the file.
Example:
f=open("test.dat","r")
for linea in f.readlines():
print(linea,end="")
The method write(string) writes a string on a file (note that it is impossible to write numbers directly!).
Example:
f=open("test_output.dat","w")
for i in range(10):
f.write( "%d \t %f\n" % ( i+1, (i+1)**2.0 ) )
f.close()
How do we read the date just written in the file?
The best thing to do is to read the data as strings and then to convert them in numbers through the conversion functions. This is the most flexible way to read data from files. We will see as the numpy library has functions to read numerical data directly from the files, although this is not always efficient if the file has been written in a sofisticated way.
Example:
f=open("test_output.dat","r")
for stringa in f.readlines():
vals=stringa.split("\t")
i=int(vals[0])
i2=float(vals[1])
i3=i*i
print(i, "\t", i2, "\t", i3)
f.close()
def function_name( parameters ): ... return parameter
defines a function with a name, a list of arguments and returns one or more parameters!
Of course, returning a value is not mandatory
Example: defines a (recursive) function to compute the factorial if a integer number...
def fact(n):
if n == 1:
return 1
else:
return n * fact(n-1)
print(fact(4))
print(fact(100))
As we said, it is possible to return more than a single value, or no value at all.
Example:
# Function which prints a string n-times; it does NOT return any value
def print_string(mystring,n):
print(mystring * n,end="")
print()
print_string("Ciao!", 10)
# Function which returns two lists, one with the numbers from 1 to n, the other one with their squares
def double_list(n):
nums=range(n)
list1=[]
list2=[]
for i in nums:
list1.append(i+1)
list2.append((i+1)**2.0)
return list1, list2
l1, l2 = double_list(10)
print(l1, l2)
It is possible to define functions with optional parameters, namely values that, if not specified, assume some default values.
Example:
def print_string(mystring,n=1):
print(mystring * n,end="")
print()
print_string("ok!")
print_string("Ciao",10)
It is also possible to change the order of the parameters in the function call, if parameter=value is specified in the call.
Example:
print_string(n=5,mystring="Ok! ")