






















Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Prepara tus exámenes
Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Prepara tus exámenes con los documentos que comparten otros estudiantes como tú en Docsity
Encuentra los documentos específicos para los exámenes de tu universidad
Estudia con lecciones y exámenes resueltos basados en los programas académicos de las mejores universidades
Responde a preguntas de exámenes reales y pon a prueba tu preparación
Consigue puntos base para descargar
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Comunidad
Pide ayuda a la comunidad y resuelve tus dudas de estudio
Ebooks gratuitos
Descarga nuestras guías gratuitas sobre técnicas de estudio, métodos para controlar la ansiedad y consejos para la tesis preparadas por los tutores de Docsity
Una guía rápida para aprender a utilizar python, una popular lenguaje de programación. Contiene información sobre tipos de datos básicos, cadenas, operadores matemáticos, funciones y listas. Aprenderá a crear variables, imprimir resultados en la consola, concatenar cadenas, definir y llamar a funciones, y manejar listas.
Tipo: Apuntes
1 / 30
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!























Python 3 Cheat Sheet
©2012-2015 - Laurent Pointal License Creative Commons Attribution 4
Latest version on : https://perso.limsi.fr/pointal/python:memento
int 783 0 -
float 9.23 0.0 -1.7e- bool True False
str
× 10 -
escaped tab
escaped new line
Multiline string:
list [^1 ,^5 ,^9 ]^ ["x",^11 ,8.9]^ ["mot"]^ [] tuple (^1 ,^5 ,^9 )^11 ,"y",7.4^ ("mot",)^ ()
dict
set
Non modifiable values (immutables)
x=1.2+ 8 +sin(y)
y,z,r=9.2,-7.6, 0
☝ expression with only comas → tuple
dictionary
collection
☺ a toto x7 y_max BigOne ☹ 8y and for
x+= 3 x-= 2
int("15") → 15 int("3f", 16 ) → 63 can specify integer number base in 2nd^ parameter int(15.56) → 15 truncate decimal part float("-11.24e8") → -1124000000. round(15.56, 1 )→ 15.6 rounding to 1 decimal (0 decimal → integer number) bool(x) False for null x, empty container x , None or False x ; True for other x str(x)→ "…" representation string of x for display (cf. formatting on the back) chr( 64 )→'@' ord('@')→ 64 code ↔ char repr(x)→ "…" literal representation string of x bytes([ 72 , 9 , 64 ]) → b'H\t@' list("abc") → ['a','b','c'] dict([( 3 ,"three"),( 1 ,"one")]) → { 1 :'one', 3 :'three'} set(["one","two"]) → {'one','two'} separator str and sequence of str → assembled str ':'.join(['toto','12','pswd']) → 'toto:12:pswd' str splitted on whitespaces → list of str "words with spaces".split() → ['words','with','spaces'] str splitted on separator str → list of str "1,4,8,2".split(",") → ['1','4','8','2'] sequence of one type → list of another type (via list comprehension) [int(x) for x in ('1','29','-3')] → [ 1 , 29 ,-3]
type( expression )
lst=[10, 20, 30, 40, 50]
lst[ 1 ] → 20 lst[-2] → 40
positive index
negative index
positive slice
len(lst) → 5
lst[ 1 : 3 ]→[20,30]
lst[:: 2 ]→[10,30,50]
lst[-3:-1]→[30,40]
lst[:-1]→[10,20,30,40] lst[:^3 ]→[10,20,30] lst[ 1 :-1]→[20,30,40] lst[^3 :]→[40,50] lst[:]→[10,20,30,40,50]
if age<= 18 : state="Kid" elif age> 65 : state="Retired" else: state="Active"
parent statement : statement block 1… ⁝ parent statement : statement block2… ⁝
next statement after block 1
indentation!
a and b
a or b
not a
one or other or both
both simulta- -neously
if logical condition :
statements block
Can go with several elif , elif ... and only one final else. Only the block of first true condition is executed.
lst[-1] → 50
lst[ 0 ] → 10 ⇒ last one
⇒ first one
x=None « undefined » constant value
integer ÷ ÷ remainder
ab^
sin(pi/4)→0.707… cos(2pi/3)→-0.4999… sqrt(81)→9.0 √ log(e*2)→2. ceil(12.5)→ floor(12.5)→
escaped '
☝ floating numbers… approximated values angles in radians
for variables, functions, modules, classes… names
Mémento v2.0.
str (ordered sequences of chars / bytes)
(key/value associations)
☝ pitfall : and and or return value of a or of b (under shortcut evaluation). ⇒ ensure that a and b are booleans.
(boolean results)
a=b=c= 0 assignment to same value multiple assignments a,b=b,a values swap a,*b=seq *a,b=seq
unpacking of sequence in item and list
bytes
bytes
hexadecimal octal
binary octal hexa
empty
☝ keys=hashable values (base types, immutables…)
☝ configure editor to insert 4 spaces in place of an indentation tab.
lst[::-1]→[50,40,30,20,10] lst[::-2]→[50,30,10]
_1) evaluation of right side expression value
= ☝ assignment ⇔ binding of a name with a value
☝ immutables
frozenset immutable set
modules math, statistics, random, decimal, fractions, numpy, etc. (cf. doc)
module truc ⇔file truc.py
→direct access to names, renaming with as
☝ modules and packages searched in python path (cf sys.path)
?
yes no
shallow copy of sequence
?
yes no
and *= /= %= …
☝ with a var x : if bool(x)==True: ⇔ if x: if bool(x)==False: ⇔ if not x:
normal
processing
error processing error processing
raise X() raise
zero
☝ finally block for final processing in all cases.
◽ Selection : 2 nom 0.nom 4[key] 0[2]
print("v=", 3 ,"cm :",x,",",y+ 4 )^ Display
loop on dict/set ⇔ loop on keys sequences use slices to loop on a subset of a sequence
while logical condition : statements block
s = 0 i = 1
while i <= 100 : s = s + i** 2 i = i + 1 print("sum:",s)
initializations before the loop condition with a least one variable value (here i )
s = (^) ∑ i = 1
i = 100 i
2 ☝ make condition variable change!
for var in sequence : statements block
s = "Some text" cnt = 0
for c in s: if c == "e": cnt = cnt + 1 print("found",cnt,"'e'")
Algo: count number of e in the string.
lst = [11,18,9,12,23,4,17] lost = [] for idx in range(len(lst)): val = lst[idx] if val > 15 : lost.append(val) lst[idx] = 15 print("modif:",lst,"-lost:",lost)
Algo: limit values greater than 15, memorizing of lost values.
initializations before the loop
loop variable, assignment managed by for statement
formating directives values to format
s = input("Instructions:")
range( 5 )→ 0 1 2 3 4 range( 2 , 12 , 3 )→ 2 5 8 11 range( 3 , 8 )→ 3 4 5 6 7 range( 20 , 5 ,-5)→ 20 15 10 range(len( seq )) → sequence of index of values in seq ☝ range provides an immutable sequence of int constructed as needed
range( [start,] end [,step] )
f = open("file.txt","w",encoding="utf8")
storing data on disk, and reading it back
opening mode ◽ 'r' read ◽ 'w' write ◽ 'a' append ◽ …'+' 'x' 'b' 't'
encoding of chars for text files : utf8 ascii latin1 …
name of file on disk (+path…)
file variable for operations
f.write("coucou") f.writelines( list of lines )
if n not specified, read up to end! f.readlines( [n] ) → list of next lines f.readline() → next line
cf. modules os, os.path and pathlib
f.close() ☝ dont forget to close the file after use!
Very common: opening with a guarded block (automatic closing) and reading loop on lines of a text file:
def fct(x,y,z): """documentation""" # statements block, res computation, etc. return res
result value of the call, if no computed result to return: return None ☝ parameters and all variables of this block exist only in the block and during the function call (think of a “black box ” )
r = fct( 3 ,i+ 2 , 2 *i) Function Call
☝ read empty string if end of file
☝ modify original list
"{:+2.3f}".format(45.72793) →'+45.728' "{1:>10s}".format( 8 ,"toto") →' toto' "{x!r}".format(x="I'm") →'"I'm"'
☝ start default 0, end not included in sequence, step signed, default 1
◽ Conversion : s (readable text) or r (literal representation)
< > ^ = 0 at start for filling with 0 integer: b binary, c char, d decimal (default), o octal, x or X hexa… float: e or E exponential, f or F fixed point, g or G appropriate (default), string: s … % percent
◽ Formatting : fill char alignment sign mini width. precision~maxwidth type
Operators: | → union (vertical bar char) & → intersection
associations
Note: For dictionaries and sets, these operations use keys.
Specific to ordered sequences containers (lists, tuples, strings, bytes…)
keys/values/associations
Examples
d.setdefault( key[,default] ) →value
Advanced: def fct(x,y,z,args,a= 3 ,b= 5 ,kwargs): _args variable positional arguments (→_ tuple ), default values, **kwargs variable named arguments (→ dict )
one argument per parameter
storage/use of returned value
Algo:
reading/writing progress sequentially in the file, modifiable with:
Advanced: *sequence **dict
s.startswith( prefix[,start[,end]] ) s.endswith( suffix[,start[,end]] ) s.strip( [chars] ) s.count( sub[,start[,end]] ) s.partition( sep ) → (before,sep,after) s.index( sub[,start[,end]] ) s.find( sub[,start[,end]] ) s.is…() tests on chars categories (ex. s.isalpha() ) s.upper() s.lower() s.title() s.swapcase() s.casefold() s.capitalize() s.center( [width,fill] ) s.ljust( [width,fill] ) s.rjust( [width,fill] ) s.zfill( [width] ) s.encode( encoding ) s.split( [sep] ) s.join( seq )
?
yes no
next finish
…
import copy copy.copy(c)→ shallow copy of container copy.deepcopy(c)→ deep copy of container
☝ this is the use of function name with parentheses which does the call
fct()
fct
fct
☝ text mode t by default (read/write str ), possible binary mode b (read/write bytes ). Convert from/to required type!
☝ else block for normal loop exit.
by Dave Child (DaveChild) via cheatography.com/1/cs/19/
Python Time Methods Python Time Methods
replace() utcoffset()
isoformat() dst()
str() tzname()
strftime(format)
Python Date Formatting Python Date Formatting
%a Abbreviated weekday (Sun)
%A Weekday (Sunday)
%b Abbreviated month name (Jan)
%B Month name (January)
%c Date and time
%d Day (leading zeros) (01 to 31)
%H 24 hour (leading zeros) (00 to 23)
%I 12 hour (leading zeros) (01 to 12)
%j Day of year (001 to 366)
%m Month (01 to 12)
%M Minute (00 to 59)
%p AM or PM
%S Second (00 to 61⁴)
%U Week number¹ (00 to 53)
%w Weekday² (0 to 6)
%W Week number³ (00 to 53)
%x Date
%X Time
%y Year without century (00 to 99)
%Y Year (2008)
%Z Time zone (GMT)
%% A literal "%" character (%)
¹ Sunday as start of week. All days in a new year preceding the first Sunday are
considered to be in week 0. ² 0 is Sunday, 6 is Saturday.
³ Monday as start of week. All days in a new year preceding the first Monday are
considered to be in week 0. ⁴ This is not a mistake. Range takes
account of leap and double-leap seconds.
By Dave ChildDave Child (DaveChild) cheatography.com/davechild/
aloneonahill.com
Published 19th October, 2011. Last updated 3rd November, 2020.
Page 2 of 2.
Sponsored by ApolloPad.comApolloPad.com Everyone has a novel in them. Finish
Yours! https://apollopad.com
Selecting List Elements
Python For Data Science Cheat Sheet
Python Basics Learn More Python for Data Science Interactively at www.datacamp.com
Variable Assignment
Strings
7
3
10
25
1
Variables and Data Types
Lists
Subset
Slice
Subset Lists of Lists
Also see NumPy Arrays
Libraries
my_string.upper() my_string.lower() my_string.count('w') my_string.replace('e', 'i') my_string.strip()
'thisStringIsAwesome'
Numpy Arrays
my_list = [1, 2, 3, 4] my_array = np.array(my_list) my_2darray = np.array([[1,2,3],[4,5,6]])
Asking For Help
Subset
2 Slice
array([1, 2]) Subset 2D Numpy arrays
array([1, 4])
['my', 'list', 'is', 'nice', 'my', 'list', 'is', 'nice']
['my', 'list', 'is', 'nice', 'my', 'list', 'is', 'nice']
True
array([False, False, False, True], dtype=bool)
array([2, 4, 6, 8])
array([6, 8, 10, 12])
'thisStringIsAwesomethisStringIsAwesome'
'thisStringIsAwesomeInnit'
True DataCamp Learn Python for Data Science Interactively
Scientific computing
Data analysis
2D plotting
Machine learning
Also see Lists
Get the dimensions of the array Append items to an array Insert items in an array Delete items in an array Mean of the array Median of the array Correlation coefficient Standard deviation
String to uppercase String to lowercase Count String elements Replace String elements Strip whitespaces
Install Python
Calculations With Variables Leading open data science platform powered by Python
Free IDE that is included with Anaconda
Create and share documents with live code, visualizations, text, ...
Types and Type Conversion
String Operations
List Operations
List Methods
String Methods
String Operations
Selecting Numpy Array Elements Index starts at 0
Numpy Array Operations
Numpy Array Functions
Python Basics: Gettin Started
Main Python Data Types
How to Create a Strin in Python
Math Operators
How to Store Strins in Variables
Built-in Functions in Python
How to Define a Function
List
List Comprehensions
Tuples
Dictionaries
If Statements (Conditional Statements) in Python
Python Loops
Class
Dealin with Python Exceptions (Errors)
How to Troubleshoot the Errors
Conclusion
03
04
05
06
07
08
10
12
16
16
17
19
21
22
23
24
25
Table of Contents
Python Basics: Gettin Started
What is IDLE (Interated Development and Learnin)
Most Windows and Mac computers come with Python pre-installed. You can check
that via a Command Line search. The particular appeal of Python is that you can
write a proram in any text editor, save it in .py format and then run via a Command
Line. But as you learn to write more complex code or venture into data science, you
miht want to switch to an IDE or IDLE.
IDLE (Interated Development and Learnin Environment) comes with every
Python installation. Its advantae over other text editors is that it hihlihts
important keywords (e.. strin functions), makin it easier for you to interpret code.
Shell is the default mode of operation for Python IDLE. In essence, it’s a simple loop
that performs that followin four steps:
Python shell is a reat place to test various small code snippets.
WebsiteSetup.or - Python Cheat Sheet
How to Create a Strin in Python
Basic Python Strin
Strin Concatenation
You can create a strin in three ways usin sinle , double or triple quotes. Here’s an
example of every option:
IMP! Whichever option you choose, you should stick to it and use it consistently
within your proram.
As the next step, you can use the print() function to output your strin in the console
window. This lets you review your code and ensure that all functions well.
Here’s a snippet for that:
my_string = “Let’s Learn Python!”
another_string = ‘It may seem difficult first, but you
can do it!’
a_long_string = ‘’’Yes, you can even master multi-line
strings
that cover more than one line
with some practice’’’
The next thin you can master is concatenation — a way to add two strins
toether usin the “+” operator. Here’s how it’s done:
Note: You can’t apply + operator to two different data types e.. strin + inteer. If
you try to do that, you’ll et the followin Python error:
string_one = “I’m reading “
string_two = “a new great book!”
string_three = string_one + string_two
TypeError: Can’t convert ‘int’ object to str implicitly
print(“Let’s print out a string!”)
WebsiteSetup.or - Python Cheat Sheet
Strin Replication
Math Operators
As the name implies, this command lets you repeat the same strin several times.
This is done usin ***** operator. Mind that this operator acts as a replicator only with
strin data types. When applied to numbers, it acts as a multiplier.
Strin replication example:
For reference, here’s a list of other math operations you can apply towards numbers:
And with print ()
And your output will be Alice written five times in a row.
‘Alice’ * 5 ‘AliceAliceAliceAliceAlice’
print(“Alice” * 5 )
Operators Operation Example
**** Exponent 2 ** 3 = 8**
% Modulus/Remainder 22 % 8 = 6
// Integer division 22 // 8 = 2
/ Division 22 / 8 = 2.
*** Multiplication 3 * 3 = 9**
- (^) Subtraction 5 - 2 = 3
+ Addition 2 + 2 = 4
WebsiteSetup.or - Python Cheat Sheet
Built-in Functions in Python
Input() Function
len() Function
You already know the most popular function in Python — print(). Now let’s take a
look at its equally popular cousins that are in-built in the platform.
When you run this short proram, the results will look like this:
Output:
input() function is a simple way to prompt the user for some input (e.. provide their
name). All user input is stored as a strin.
Here’s a quick snippet to illustrate this:
len() function helps you find the lenth of any strin, list, tuple, dictionary, or another
data type. It’s a handy command to determine excessive values and trim them to
optimize the performance of your proram.
Here’s an input function example for a strin:
Hi! What’s your name? “Jim”
Nice to meet you, Jim!
How old are you? 25
So, you are already 25 years old, Jim!
The lenth of the strin is: 35
name = input(“Hi! What’s your name? “)
print(“Nice to meet you “ + name + “!”)
age = input(“How old are you “)
print(“So, you are already “ + str(age) + “ years old, “
+ name + “!”)
# testing len()
str1 = “Hope you are enjoying our tutorial!”
print(“The length of the string is :”, len(str1))
WebsiteSetup.or - Python Cheat Sheet
filter()
Use the Filter() function to exclude items in an iterable object (lists, tuples,
dictionaries, etc)
(Optional: The PDF version of the checklist can also include a full table of all the in-built
functions).
ages = [ 5 , 12 , 17 , 18 , 24 , 32 ]
def myFunc(x):
if x < 18 :
return False
else:
return True
adults = filter(myFunc, ages)
for x in adults:
print(x)
WebsiteSetup.or - Python Cheat Sheet
How to Pass Keyword Aruments to a Function
In this case, you pass the number 1 in for the x parameter, 2 in for the y parameter,
and 3 in for the z parameter. The proram will that do the simple math of addin up
the numbers:
Output:
A function can also accept keyword aruments. In this case, you can use
parameters in random order as the Python interpreter will use the provided
keywords to match the values to the parameters.
Here’s a simple example of how you pass a keyword arument to a function.
Output:
# Define function with parameters
def product_info(product name, price):
print(“productname: “ + product name)
print(“Price “ + str(dollars))
# Call function with parameters assigned as above
product_info(“White T-shirt”, 15 dollars)
# Call function with keyword arguments
product_info(productname=”jeans”, price= 45 )
Productname: White T-shirt
Price: 15
Productname: Jeans
Price: 45
a = 1 + 2
b = 1 + 3
c = 2 + 3
WebsiteSetup.or - Python Cheat Sheet
3
Product Name: White T-Shirt
Price: 15
Product Name: Jeans
Price: 45
4
def product_info (product name, price):
print(”Product Name: “ + product_name)
print(”Price: “ + str(price))
5
# Define function with parameters
product_info(”White T-Shirt: “, 15 )
# Call function with parameters assigned as above
product_info(productname=”Jeans“, price= 45 )
# Call function with keyword arguments
Lists
Example lists
How to Add Items to a List
Lists are another cornerstone data type in Python used to specify an ordered
sequence of elements. In short, they help you keep related data toether and
perform the same operations on several values at once. Unlike strins, lists are
mutable (=chaneable).
Each value inside a list is called an item and these are placed between square
brackets.
Alternatively, you can use list() function to do the same:
You have two ways to add new items to existin lists.
The first one is usin append() function:
The second option is to insert() function to add an item at the specified index:
my_list = [ 1 , 2 , 3 ]
my_list2 = [“a”, “b”, “c”]
my_list3 = [“4”, d, “book”, 5 ]
beta_list = [“apple”, “banana”, “orange”]
beta_list.append(“grape”)
print(beta_list)
beta_list = [“apple”, “banana”, “orange”]
beta_list.insert(“2 grape”)
print(beta_list)
alpha_list = list((“1”, “2”, “3”))
print(alpha_list)
WebsiteSetup.or - Python Cheat Sheet
2,“grape”
Sort a List
Slice a List
Chane Item Value on Your List
Loop Throuh the List
Use the sort() function to oranize all items in your list.
Now, if you want to call just a few elements from your list (e.. the first 4 items),
you need to specify a rane of index numbers separated by a colon [x:y]. Here’s an
example:
You can easily overwrite a value of one list items:
Usin for loop you can multiply the usae of certain items, similarly to what *
operator does. Here’s an example:
Output:
alpha_list = [ 34 , 23 , 67 , 100 , 88 , 2 ]
alpha_list.sort()
alpha_list
[ 2 , 23 , 34 , 67 , 88 , 100 ]
alpha_list[ 0 : 4 ]
[ 2 , 23 , 34 , 67 ]
beta_list = [“apple”, “banana”, “orange”]
beta_list[ 1 ] = “pear”
print(beta_list)
for x in range( 1 , 4 ):
beta_list += [‘fruit’]
print(beta_list)
[‘apple’, ‘pear’, ‘cherry’]
WebsiteSetup.or - Python Cheat Sheet
Copy a List
Use the built-in copy() function to replicate your data:
Alternatively, you can copy a list with the list() method:
beta_list = [“apple”, “banana”, “orange”]
beta_list = beta_list.copy()
print(beta_list)
beta_list = [“apple”, “banana”, “orange”]
beta_list = list (beta_list)
print(beta_list)
WebsiteSetup.or - Python Cheat Sheet