REPASO FINAL PYTHON
Python range() Function
❮ Built-in Functions
Example
Create a sequence of numbers from 0 to 5, and print each item in the sequence:
x = range(6)
for n in x:
print(n)
Try it Yourself »
Definition and Usage
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.
Syntax
range(start, stop, step)
Parameter Values
Parameter Description
start Optional. An integer number specifying at which position to start. Default is 0
stop Required. An integer number specifying at which position to stop (not included).
step Optional. An integer number specifying the incrementation. Default is 1
More Examples
Example
Create a sequence of numbers from 3 to 5, and print each item in the sequence:
x = range(3, 6)
for n in x:
print(n)
Example
Create a sequence of numbers from 3 to 19, but increment by 2 instead of 1:
x = range(3, 20, 2)
for n in x:
print(n)
LO MISMO:
for i in range (3,20,2):
print(i)
SALIDA:
11
13
15
17
19
11
13
15
17
19
BITWISE OPERATORS
The Operators:
x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are
zeros). This is the same as multiplying x by 2**y.
x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.
x&y
Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1,
otherwise it's 0.
x|y
Does a "bitwise or". Each bit of the output is 0 if the corresponding bit of x AND of y is 0,
otherwise it's 1.
~x
Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for
a 1. This is the same as -x - 1.
x^y
Does a "bitwise exclusive or". Each bit of the output is the same as the corresponding bit in x
if that bit in y is 0, and it's the complement of the bit in x if that bit in y is 1.
Expresiones logicas compuestas
Si no se está acostumbrado a evaluar expresiones lógicas compuestas, se
recomienda utilizar paréntesis para asegurar el orden de las operaciones.
Al componer expresiones más complejas hay que tener en cuenta que Python
evalúa primero los not, luego los and y por último los or, como puede
comprobarse en los ejemplos siguientes:
El operador not se evalúa antes que el operador and:
>>> not True and False
False
>>> (not True) and False
False
>>> not (True and False)
True
El operador not se evalúa antes que el operador or:
>>> not False or True
True
>>> (not False) or True
True
>>> not (False or True)
False
El operador and se evalúa antes que el operador or:
>>> False and True or True
True
>>> (False and True) or True
True
>>> False and (True or True)
False
>>> True or True and False
True
>>> (True or True) and False
False
>>> True or (True and False)
True
What value will be assigned to the x variable?
z = 10
y=0
x = y < z and z > y or y > z and z < y
0
1
True
False
Python Bitwise Operators
Bitwise operators are used to compare (binary) numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall
off
>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let
the rightmost bits fall off
What is the output of the following snippet?
a=1
b=0
c=a&b
d=a|b
e=a^b
print(c + d + e)
1
3
2
0
What is the output of the following snippet?
lst = [3, 1, -2]
print(lst[lst[-1]])
1
-2
3
-1
Lst [-1], significa el ultimo …es igual a -2, luego lst[-2] el penultimo y este es igual a 1
Python Lists
❮ PreviousNext ❯
Python Collections (Arrays)
There are four collection data types in the Python programming language:
List is a collection which is ordered and changeable. Allows duplicate
members.
Tuple is a collection which is ordered and unchangeable. Allows duplicate
members.
Set is a collection which is unordered and unindexed. No duplicate
members.
Dictionary is a collection which is unordered, changeable and indexed.
No duplicate members.
When choosing a collection type, it is useful to understand the properties of that
type. Choosing the right type for a particular data set could mean retention of
meaning, and, it could mean an increase in efficiency or security.
List
A list is a collection which is ordered and changeable. In Python lists are written
with square brackets.
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Try it Yourself »
Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
banana
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
cherry
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
When specifying a range, the return value will be a new list with the specified
items.
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
#This will return the items from position 2 to 5.
#Remember that the first item is position 0,
#and note that the item in position 5 is NOT included
CUANDO IMPRIMES UNA SECCION DE LA LISTA CON INDICES NEGATIVOS, EL -1 NO ES EL ULTIMO
ELEMENTO SINO EL PENULTIMO, ES DECIR EL ANTERIOR AL INDICADO
lst = [1,2,3,4]
print(lst[-3:-3])
OUTPUT []
RECORDAR EL PRIMER VALOR ES EL INICIO Y UN INDICE NEGATIVO SI CUENTA COMO ULTIMO, EL
SEGUNDO VALOR ES EL FINAL DE LOS QUE QUIERES MOSTRAR Y NO PUEDE SER UNA UBICACIÓN
ANTERIOR AL INICIO!!!!!!!!!! EN ESE CASO MOSTRARA VACIO!!!!!! [ ]
OJO PERO SI PUEDE INICIAR Y TERMINAL EN EL MISMO VALOR!!!!!
Example
This example returns the items from the beginning to "orange":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
OUTPUT: apple banana cherry orante
By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
OUTPUT: cherry orange kiwi melon mango
Range of Negative Indexes
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
#Negative indexing means starting from the end of the list.
#This example returns the items from index -4 (included) to index -1 (excluded)
#Remember that the last item has the index -1,
FUNCION DEL EN LISTAS
Take a look at the snippet, and choose the true statement:
nums = [1,2,3]
vals = nums
del vals[1:2]
del puede borrar un rango por ejemplo
del vals[1:2], el primer valor es el índice desde donde se empieza a
borrar, y el segundo valor es donde se termina de borrar SIN
INCLUIR, es decir en este ejemplo la posición 2 NO se borra SINO
la ANTERIOR.
nums is longer than vals
vals is longer than nums
nums and vals are of the same length
the snippet will cause a runtime error
What is the output of the following snippet?
l1 = [1,2,3]
l2 = []
for v in l1:
l2.insert(0,v)
print(l2)
[3,2,1]
[1,2,3]
[3,3,3]
[1,1,1]
RECUERDA QUE INSERT AGREGA AL INICIO Y MUEVE A LA DERECHA A LOS DEMAS
ELEMENTOS
How many elements does the L list contain?
L = [i for i in range(-1,2)]
one
four
three
two
range (inicio, final sin incluir)
Python Tuples
❮ PreviousNext ❯
Tuple
A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Try it Yourself »
Access Tuple Items
You can access tuple items by referring to the index number, inside square
brackets:
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Try it Yourself »
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -
2 refers to the second last item etc.
Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Try it Yourself »
Range of Indexes
You can specify a range of indexes by specifying where to start and where to
end the range.
When specifying a range, the return value will be a new tuple with the specified
items.
Example
Return the third, fourth, and fifth item:
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
Try it Yourself »
Note: The search will start at index 2 (included) and end at index 5 (not
included).
Remember that the first item has index 0.
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the
tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])
Try it Yourself »
Change Tuple Values
Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Try it Yourself »
Loop Through a Tuple
You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Try it Yourself »
You will learn more about for loops in our Python For Loops Chapter.
Check if Item Exists
To determine if a specified item is present in a tuple use the in keyword:
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Try it Yourself »
Tuple Length
To determine how many items a tuple has, use the len() method:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Try it Yourself »
Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example
You cannot add items to a tuple:
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
Try it Yourself »
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the item,
otherwise Python will not recognize it as a tuple.
Example
One item tuple, remember the commma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Try it Yourself »
Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can
delete the tuple completely:
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer
exists
Try it Yourself »
Join Two Tuples
To join two or more tuples you can use the + operator:
Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Try it Yourself »
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-
brackets
print(thistuple)
Try it Yourself »
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of wh
Python Strings
❮ PreviousNext ❯
String Literals
String literals in python are surrounded by either single quotation marks, or
double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')
Try it Yourself »
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an
equal sign and the string:
Example
a = "Hello"
print(a)
Try it Yourself »
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Try it Yourself »
Or three single quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Try it Yourself »
Note: in the result, the line breaks are inserted at the same position as in the
code.
Strings are Arrays
Like many other popular programming languages, strings in Python are arrays
of bytes representing unicode characters.
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Try it Yourself »
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part
of the string.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
Try it Yourself »
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters from position 5 to position 1 (not included), starting the
count from the end of the string:
b = "Hello, World!"
print(b[-5:-2])
Try it Yourself »
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Try it Yourself »
String Methods
Python has a set of built-in methods that you can use on strings.
Example
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Try it Yourself »
Example
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Try it Yourself »
Example
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Try it Yourself »
Example
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))
Try it Yourself »
Example
The split() method splits the string into substrings if it finds instances of the
separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
Try it Yourself »
Learn more about String Methods with our String Methods Reference
Check String
To check if a certain phrase or character is present in a string, we can use the
keywords in or not in.
Example
Check if the phrase "ain" is present in the following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
Try it Yourself »
Example
Check if the phrase "ain" is NOT present in the following text:
txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x)
Try it Yourself »
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c = a + b
print(c)
Try it Yourself »
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Try it Yourself »
String Format
As we learned in the Python Variables chapter, we cannot combine strings and
numbers like this:
Example
age = 36
txt = "My name is John, I am " + age
print(txt)
Try it Yourself »
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places
them in the string where the placeholders {} are:
Example
Use the format() method to insert numbers into strings:
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Try it Yourself »
The format() method takes unlimited number of arguments, and are placed into
the respective placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Try it Yourself »
You can use index numbers {0} to be sure the arguments are placed in the
correct placeholders:
Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
Try it Yourself »
Escape Character
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to
insert.
An example of an illegal character is a double quote inside a string that is
surrounded by double quotes:
Example
You will get an error if you use double quotes inside a string that is surrounded
by double quotes:
txt = "We are the so-called "Vikings" from the north."
Try it Yourself »
To fix this problem, use the escape character \":
Example
The escape character allows you to use double quotes when you normally would
not be allowed:
txt = "We are the so-called \"Vikings\" from the north."
Try it Yourself »
Other escape characters used in Python:
Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original
string.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of wh
rindex() Searches the string for a specified value and returns the last position of wh
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Python File Write
❮ PreviousNext ❯
Write to an Existing File
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
Run Example »
Example
Open the file "demofile3.txt" and overwrite the content:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())
Run Example »
Note: the "w" method will overwrite the entire file.
Create a New File
To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")
❮ PreviousNext ❯
Python ord() and chr() are built-in functions. They are used to convert a
character to an int and vice versa.
Python ord() and chr() functions are exactly opposite of each other.
PYC File Format
Top 20 File Extensions
.Edraw XML file
.BAI
.TD5
.CCS
.CCRF
.CCRF
.CCR
.CCR
.CCR
.CCR
.CCR
.CCPR
.CCP
.TJM
.TJL
.TJL
.TIX
.TIX
.TIX
.TIX
Word of the Day
Conway's law
Conway’s law is an observation that the design of any system is significantly affected by the
communications structure of the organization that develops it.
Subscribe to the Word of the Day
Python compiled script file
PYC files contain compiled source code written in the Python programming
language, a dynamic, object-oriented language used for creating a wide
variety of software. Python runs on Windows, Mac OS X, Linux/Unix, Palm
handhelds, and Nokia mobile phones, and it has been ported
to Java and .NET virtual machines. Older platforms it runs on include OS/2
and Amiga.
Python Lambda
❮ PreviousNext ❯
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have
one expression.
Syntax
lambda arguments : expression
The expression is executed and the result is returned:
Example
A lambda function that adds 10 to the number passed in as an argument, and
print the result:
x = lambda a : a + 10
print(x(5))
Try it Yourself »
Lambda functions can take any number of arguments:
Example
A lambda function that multiplies argument a with argument b and print the
result:
x = lambda a, b : a * b
print(x(5, 6))
Try it Yourself »
Example
A lambda function that sums argument a, b, and c and print the result:
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Try it Yourself »
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous
function inside another function.
Say you have a function definition that takes one argument, and that argument
will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the number
you send in:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Try it Yourself »
Or, use the same function definition to make a function that always triples the
number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Try it Yourself »
Or, use the same function definition to make both functions, in the same
program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Try it Yourself »
Use lambda functions when an anonymous function is required for a short
period of time.