python introduction
Sección: Programación
Creado: 17-11-24
Comments with #
f a variable is not “defined” (assigned a value), trying to use it will give you an error:
>>> n # try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
In interactive mode, the last printed expression is assigned to the variable _
. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
>>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06
Python supports other types of numbers, such asDecimal
andFraction
. Python also has built-in support for complex numbers, and uses thej
orJ
suffix to indicate the imaginary part (e.g.3+5j
).
Strings in single quotes ('...'
) or double quotes ("..."
). \
can be used to escape quotes.
The print()
function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:
>>> '"Isn\'t," she said.' '"Isn\'t," she said.' >>> print('"Isn\'t," she said.') "Isn't," she said. >>> s = 'First line.\nSecond line.' # \n means newline >>> s # without print(), \n is included in the output 'First line.\nSecond line.' >>> print(s) # with print(), \n produces a new line First line. Second line.
raw strings
>>> print('C:\some\name') # here \n means newline! C:\some ame >>> print(r'C:\some\name') # note the r before the quote C:\some\name
Strings can be concatenated (glued together) with the +
operator, and repeated with *
:
>>> # 3 times 'un', followed by 'ium' >>> 3 * 'un' + 'ium' 'unununium'
Strings can be 0 indexed:
>>> word = 'Python' >>> word[0] # character in position 0 'P' >>> word[-1] # last character (negative indices start from -1) 'n'
Slice
s[:i] + s[i:]
is always equal to s
>>> word[42] # the word only has 6 characters Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range
>>> word[42:] ''
If you need a different string, you should create a new one:
>>>
>>> 'J' + word[1:] 'Jython'
len()
returns the length of a string
Lists
>>> squares = [1, 4, 9, 16, 25]
>>> squares[0] # indexing returns the item 1 >>> squares[-1] 25 >>> squares[-3:] # slicing returns a new list [9, 16, 25]
>>> squares + [36, 49, 64, 81, 100]
lists are a mutable type
>>> cubes.append(216) # add the cube of 6
>>> letters[2:5] = ['C', 'D', 'E']
Remove elements in a list
>>> letters[2:5] = []
>>> letters[:] = []
>>> len(letters)
Nested Lists
>>> x = [['a', 'b', 'c'], [1, 2, 3]] >>> x[0] ['a', 'b', 'c'] >>> x[0][1] 'b'
Multiple assignment
a,b = 0,1
Firsts steps towards programming
>>> # Fibonacci series: ... # the sum of two elements defines the next ... a, b = 0, 1 >>> while b < 10: ... print(b) ... a, b = b, a+b ... 1 1 2 3 5 8