BOOK Python 3 Cheat Sheet
BOOK Python 3 Cheat Sheet
Strings — codify a sequence of characters using a string. For example, the word
“hello”. In Python 3, strings are immutable. If you already defined one, you cannot
change it later on.
While you can modify a string with commands such as replace() or join(), they will
create a copy of a string and apply modification to it, rather than rewrite the
original one.
Plus, another three types worth mentioning are lists, dictionaries, and tuples. All
of them are discussed in the next sections.
IMP! Whichever option you choose, you should stick to it and use it consistently
within your program.
As the next step, you can use the print() function to output your string in the
console window. This lets you review your code and ensure that all functions well.
Here’s a snippet for that:
String Concatenation
The next thing you can master is concatenation — a way to add two strings
together using the “+” operator. Here’s how it’s done:
Note: You can’t apply + operator to two different data types e.g. string +
integer. If you try to do that, you’ll get the following Python error:
TypeError: Can’t convert ‘int’ object to str implicitly
String Replication
As the name implies, this command lets you repeat the same string several times.
This is done using * operator. Mind that this operator acts as a replicator only
with string data types. When applied to numbers, it acts as a multiplier.
String replication example:
‘Alice’ * 5 ‘AliceAliceAliceAliceAlice’
print(“Alice” * 5)
Math Operators
For reference, here’s a list of other math operations you can apply towards
numbers:
% Modulus/Remainder 22 % 8 = 6
// Integer division 22 // 8 = 2
/ Division 22 / 8 = 2.75
* Multiplication 3*3=9
- Subtraction 5-2=3
+ Addition 2+2=4
Now when you print this out, you receive the string output.
print(my_str)
Hello World
See? By using variables, you save yourself heaps of effort as you don’t need to
retype the complete string every time you want to use it.
Input() Function
input() function is a simple way to prompt the user for some input (e.g. provide
their name). All user input is stored as a string.
Here’s a quick snippet to illustrate this:
name = input(“Hi! What’s your name? “)
print(“Nice to meet you “ + name + “!”)
When you run this short program, the results will look like this:
Hi! What’s your name? “Jim”
Nice to meet you, Jim!
How old are you? 25
So, you are already 25 years old, Jim!
len() Function
len() function helps you find the length of any string, 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 program. Here’s an input function
example for a string:
# testing len()
str1 = “Hope you are enjoying our tutorial!”
print(“The length of the string is :”, len(str1))
Output:
filter()
Use the filter() function to exclude items in an iterable object (lists, tuples,
dictionaries, etc)
def myFunc(x):
if x < 18:
return False
else:
return True
for x in adults:
print(x)
def name():
Next, you’ll need to add a second code line with a 4-space indent to specify what
this function should do.
def name():
print(“What’s your name?”)
name.py
def name():
print(“What’s your name?”)
name()
add_numbers(1, 2, 3)
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 program will that do the simple math
of adding up the numbers:
Output:
3
4
5
Output:
Lists
Lists are another cornerstone data type in Python used to specify an ordered
sequence of elements. In short, they help you keep related data together and
perform the same operations on several values at once. Unlike strings, lists are
mutable (=changeable).
Each value inside a list is called an item and these are placed between square
brackets.
Example lists
my_list = [1, 2, 3]
my_list2 = [“a”, “b”, “c”]
my_list3 = [“4”, d, “book”, 5]
The second option is to insert() function to add an item at the specified index:
Secondly, you can use the pop() function. If no index is specified, it will remove
the last item.
my_list = [1, 2, 3]
my_list2 = [“a”, “b”, “c”]
combo_list = my_list + my_list2
> combo_list
[1, 2, 3, ‘a’, ‘b’, ‘c’]
> my_nested_list
[[1, 2, 3], [‘a’, ‘b’, ‘c’]]
Sort a List
Use the sort() function to organize all items in your list.
> alpha_list
[2, 23, 34, 67, 88, 100]
Slice a List
Now, if you want to call just a few elements from your list (e.g. the first 4 items),
you need to specify a range of index numbers separated by a colon [x:y]. Here’s
an example:
alpha_list[0:4]
[2, 23, 34, 67]
Output:
[‘apple’, ‘pear’, ‘cherry’]
print(beta_list)
Copy a List
Use the built-in copy() function to replicate your data:
List Comprehensions
List comprehensions are a handy option for creating lists based on existing lists.
When using them you can build by using strings and tuples as well.
Here’s a more complex example that features math operators, integers, and the
range() function:
Tuples
Tuples are similar to lists — they allow you to display an ordered sequence of
elements. However, they are immutable and you can’t change the values stored
in a tuple.
The advantage of using tuples over lists is that the former are slightly faster. So
it’s a nice way to optimize your code.
(1, 2, 3)
Note: Once you create a tuple, you can’t add new items to it or change it in any other way!
Output:
(1, 3, 5, 7, 9)
Dictionaries
A dictionary holds indexes with keys that are mapped to certain values. These
key-value pairs offer a great way of organizing and storing data in Python. They
are mutable, meaning you can change the stored information.
A key value can be either a string, Boolean, or integer. Here’s an example
dictionary illustrating this:
And you can use the same two approaches to add values to your dictionary:
x = new_dict[“brand”]
You can also use the following methods to accomplish the same.
• dict.keys() isolates keys
• dict.values() isolates values
• dict.items() returns items in a list format of (key, value) tuple pairs
new_dict= {
“brand”: “Honda”,
“model”: “Civic”,
“year”: 1995
}
new_dict[“year”] = 2020
Note: In this case, the return values are the keys of the dictionary. But, you can also return
values using another method.
If Statement Example
The goal of a conditional statement is to check if it’s True or False.
if 5 > 1:
print(“That’s True!”)
Output:
That’s True!
Nested If Statements
For more complex operations, you can create nested if statements. Here’s how
it looks:
x = 35
if x > 20:
print(“Above twenty,”)
if x > 30:
print(“and also above 30!”)
Elif Statements
elif keyword prompts your program to try another condition if the previous one(s)
was not true. Here’s an example:
a = 45
b = 45
if b > a:
print(“b is greater than a”)
elif a == b:
print(“a and b are equal”)
If Else Statements
else keyword helps you add some additional filters to your condition clause.
Here’s how an if-elif-else combo looks:
if age < 4:
ticket_price = 0
elif age < 18:
ticket_price = 10
else:
ticket_price = 15
If-Not-Statements
Not keyword let’s you check for the opposite meaning to verify whether the value
is NOT True:
new_list = [1, 2, 3, 4]
x = 10
if x not in new_list:
print(“’x’ isn’t on the list, so this is True!”)
Pass Statements
If statements can’t be empty. But if that’s your case, add the pass statement to
avoid having an error:
a = 33
b = 200
if b > a:
pass
Python Loops
Python has two simple loop commands that are good to know:
• for loops
• while loops
For Loop
As already illustrated in the other sections of this Python checklist, for loop is a
handy way for iterating over a sequence such as a list, tuple, dictionary, string...
Here’s an example showing how to loop through a string:
for x in “apple”:
print(x)
Plus, you’ve already seen other examples for lists and dictionaries.
While Loops
While loop enables you to execute a set of statements as long as the condition
for them is true.
i = 1
while i < 8:
print(i)
if i == 4:
break
i += 1
Class
Since Python is an object-oriented programming language almost every element
of it is an object — with its methods and properties.
Class acts as a blueprint for creating different objects. Objects are an instance of
a class, where the class is manifested in some program.
class TestClass:
z = 5
p1 = TestClass()
print(p1.x)
Further, you can assign different attributes and methods to your object. The
example is below:
class car(object):
“””docstring”””
def brake(self):
“””
Stop the car
“””
return “Braking”
def drive(self):
“””
Drive the car
“””
return “I’m driving!”
class Car(Vehicle):
“””
The Car class
“””
def brake(self):
“””
Override brake method
“””
return “The car class is breaking slowly!”
if __name__ == “__main__”:
car = Car(“yellow”, 2, 4, “car”)
car.brake()
car.drive()
You can also detect several exceptions at once with a single statement. Here’s an
example for that:
try:
value = my_dict[“a”]
except KeyError:
print(“A KeyError occurred!”)
else:
print(“No error occurred!”)
Follow us
http://digital.academy.free.fr/
https://twitter.com/DigitalAcademyy
https://www.facebook.com/digitalacademyfr
https://www.instagram.com/digital_academy_fr/
https://www.youtube.com/c/DigitalAcademyOnline
Support us
http://digital.academy.free.fr/join
http://digital.academy.free.fr/donate
http://digital.academy.free.fr/subscribe
https://www.patreon.com/digital_academy
https://www.buymeacoffee.com/digital_academy