Our easy to use python cheatsheet features all the commands in a unique and easy to read format. If you are an entrepreneur, student or looking for a new programming job, then you will love this cheatsheet.
- What is IDLE (Integrated Development and Learning)?
- Variables
- Data Types
- Comments
- Function docstring:
- The print() Function
- The input() Function
- The len() Function
- The str(), int(), and float() Functions
- filter()
- Receiving Input
- Strings
- Flow Control
- Comparison Operators
- Boolean evaluation
- Boolean Operators
- Mixing Boolean and Comparison Operators
- if Statements
- else Statements
- elif Statements
- while Loop Statements
- break Statements
- continue Statements
- for Loops and the range() Function
- For else statement
- Importing Modules
- Ending a Program Early with sys.exit()
- Lists
- Tuples
- Sets
- Dictionaries
Python 3 is a highly adaptable programming language that is preferred by a wide variety of developers, including software engineers, data scientists, and web developers. And there are many compelling reasons for that to be the case!
Python is a free and open-source programming language that has an active and helpful user community in addition to numerous support libraries.
It has data structures that are easy to navigate.
What is IDLE (Integrated Development and Learning)?
Every installation of Python includes a program known as IDLE, which stands for Integrated Development and Learning Environment.
It has a benefit over other text editors in that it highlights crucial terms, such as string functions, which makes it much simpler for you to understand the code.
Python’s Integrated Development Environment (IDLE) operates in the shell by default. In its most basic form, it is a loop that iteratively completes the following four tasks:
• Reads the Python statement
• Evaluates the results of it
• Prints the result on the screen
• And then loops back to read the next statement.
Python shell is a great place to test various small code snippets.
Variables
We use variables to temporarily store data in computer’s memory.
price = 10
rating = 4.9
course_name = ‘Python for Beginners’
is_published = True
In the above example,
• price is an integer (a whole number without a decimal point)
• rating is a float (a number with a decimal point)
• course_name is a string (a sequence of characters)
• is_published is a boolean. Boolean values can be True or False.
Data Types
Data Type | Examples |
---|---|
Integers | -2, -1, 0, 1, 2, 3, 4, 5 |
Floating-point numbers | -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25 |
Strings | 'a', 'aa', 'aaa', 'Hello!', '11 cats' |
Comments
Inline comment:
# This is a comment
Multiline comment:
# This is a # multiline comment
Code with a comment:
a = 1 # initialization
Please note the two spaces in front of the comment.
Function docstring:
def foo(): """ This is a function docstring You can also use: ''' Function Docstring ''' """
Also, Check out Data Structure Problem Solutions:
- Lily’s Homework in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]
- Fraudulent Activity Notifications in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]
- Insertion Sort Advanced Analysis in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]
- Find the Median in Algorithm | HackerRank Programming Solutions | HackerRank Problem Solving Solutions in Java [💯Correct]
The print() Function
>>> print('Hello world!') Hello world!
>>> a = 1 >>> print('Hello world!', a) Hello world! 1
The input() Function
Example Code:
>>> print('What is your name?') # ask for their name >>> myName = input() >>> print('It is good to meet you, {}'.format(myName)) What is your name? Al It is good to meet you, Al
The len() Function
Evaluates to the integer value of the number of characters in a string:
>>> len('hello') 5
Note: a test of the emptiness of strings, lists, dictionary, etc, should not use len, but prefer direct boolean evaluation.
>>> a = [1, 2, 3] >>> if a: >>> print("the list is not empty!")
The str(), int(), and float() Functions
Integer to String or Float:
>>> str(29) '29'
>>> print('I am {} years old.'.format(str(29))) I am 29 years old.
>>> str(-3.14) '-3.14'
Float to Integer:
>>> int(7.7) 7
>>> int(7.7) + 1 8
filter()
Use the Filter() function to exclude items in an iterable object (lists, tuples,
dictionaries, etc)
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)
Receiving Input
We can receive input from the user by calling the input() function.
birth_year = int(input(‘Birth year: ‘))
The input() function always returns data as a string. So, we’re converting the
result into an integer by calling the built-in int() function.
Strings
You can create a string in three ways using single, double, or triple quotes. Here’s an example of every option:
Basic Python String
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’’’
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:
string_one = “I’m reading “ string_two = “a new great book!” string_three = string_one + string_two
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
This command lets you repeat the same string several times, as the name suggests. The * operator is used to do this.
Keep in mind that this operator can only be used to copy string data types.
It acts as a multiplier when it is used with numbers.
Example of string replication:
‘Alice’ * 5 =‘AliceAliceAliceAliceAlice’ In Python
And with print ()
print(“Alice” * 5)
And your output will be Alice written five times in a row.
String Common Functions
We can use formatted strings to dynamically insert values into our strings:
name = ‘Mosh’ message = f’Hi, my name is {name}’ message.upper() # to convert to uppercase message.lower() # to convert to lowercase message.title() # to capitalize the first letter of every word message.find(‘p’) # returns the index of the first occurrence of p (or -1 if not found) message.replace(‘p’, ‘q’)
To check if a string contains a character (or a sequence of characters), we use the in operator:
contains = ‘Python’ in the course
Math Operators
For reference, here’s a list of other math operations you can apply to numbers:

Flow Control
Comparison Operators
Operator | Meaning |
---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater Than |
<= | Less than or Equal to |
>= | Greater than or Equal to |
These operators evaluate to True or False depending on the values you give them.
Examples:
>>> 42 == 42 True
>>> 40 == 42 False
>>> 'hello' == 'hello' True
>>> 'hello' == 'Hello' False
>>> 'dog' != 'cat' True
>>> 42 == 42.0 True
>>> 42 == '42' False
Boolean evaluation
Never use ==
or !=
operator to evaluate the boolean operation. Use the is
or is not
operators, or use implicit boolean evaluation.
NO (even if they are valid Python):
>>> True == True True
>>> True != False True
YES (even if they are valid Python):
>>> True is True True
>>> True is not False True
These statements are equivalent:
>>> if a is True: >>> pass >>> if a is not False: >>> pass >>> if a: >>> pass
And these as well:
>>> if a is False: >>> pass >>> if a is not True: >>> pass >>> if not a: >>> pass
Boolean Operators
There are three Boolean operators: and, or, and not.
The and Operator’s Truth Table:
Expression | Evaluates to |
---|---|
True and True | True |
True and False | False |
False and True | False |
False and False | False |
The or Operator’s Truth Table:
Expression | Evaluates to |
---|---|
True or True | True |
True or False | True |
False or True | True |
False or False | False |
The not Operator’s Truth Table:
Expression | Evaluates to |
---|---|
not True | False |
not False | True |
Mixing Boolean and Comparison Operators
>>> (4 < 5) and (5 < 6) True
>>> (4 < 5) and (9 < 6) False
>>> (1 == 2) or (2 == 2) True
You can also use multiple Boolean operators in an expression, along with the comparison operators:
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2 True
if Statements
if name == 'Alice': print('Hi, Alice.')
else Statements
name = 'Bob' if name == 'Alice': print('Hi, Alice.') else: print('Hello, stranger.')
elif Statements
name = 'Bob' age = 5 if name == 'Alice': print('Hi, Alice.') elif age < 12: print('You are not Alice, kiddo.')
name = 'Bob' age = 30 if name == 'Alice': print('Hi, Alice.') elif age < 12: print('You are not Alice, kiddo.') else: print('You are neither Alice nor a little kid.')
while Loop Statements
spam = 0 while spam < 5: print('Hello, world.') spam = spam + 1
break Statements
If the execution reaches a break statement, it immediately exits the while loop’s clause:
while True: print('Please type your name.') name = input() if name == 'your name': break print('Thank you!')
continue Statements
When the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop.
while True: print('Who are you?') name = input() if name != 'Joe': continue print('Hello, Joe. What is the password? (It is a fish.)') password = input() if password == 'swordfish': break print('Access granted.')
for Loops and the range() Function
>>> print('My name is') >>> for i in range(5): >>> print('Jimmy Five Times ({})'.format(str(i))) My name is Jimmy Five Times (0) Jimmy Five Times (1) Jimmy Five Times (2) Jimmy Five Times (3) Jimmy Five Times (4)
The range() function can also be called with three arguments. The first two arguments will be the start and stop values, and the third will be the step argument. The step is the amount that the variable is increased by after each iteration.
>>> for i in range(0, 10, 2): >>> print(i) 0 2 4 6 8
You can even use a negative number for the step argument to make the for loop count down instead of up.
>>> for i in range(5, -1, -1): >>> print(i) 5 4 3 2 1 0
For else statement
This allows to specify a statement to execute in case of the full loop has been executed. Only useful when a break the condition can occur in the loop:
>>> for i in [1, 2, 3, 4, 5]: >>> if i == 3: >>> break >>> else: >>> print("only executed when no item of the list is equal to 3")
Importing Modules
import random for i in range(5): print(random.randint(1, 10))
import random, sys, os, math
from random import *
Ending a Program Early with sys.exit()
import sys while True: print('Type exit to exit.') response = input() if response == 'exit': sys.exit() print('You typed {}.'.format(response))
Lists
A-List in Python represents a list of comma-separated values of any data type between square brackets.
var_name = [element1, element2, ...]
index method
Returns the index of the first element with the specified value
list.index(element)
append method
Adds an element at the end of the list
list.append(element)
extend method
Add the elements of a given list (or any iterable) to the end of the current list
list.extend(iterable)
insert method
Adds an element at the specified position
list.insert(position, element)
pop method
Removes the element at the specified position and returns it
list.pop(position)
remove method
The remove() method removes the first occurrence of a given item from the list
list.remove(element)
clear method
Removes all the elements from the list
list.clear()
count method
Returns the number of elements with the specified value
list.count(value)
reverse method
Reverses the order of the list
list.reverse()
sort method
Sorts the list
list.sort(reverse=True|False)
numbers = [1, 2, 3, 4, 5] numbers[0] # returns the first item numbers[1] # returns the second item numbers[-1] # returns the first item from the end numbers[-2] # returns the second item from the end numbers.append(6) # adds 6 to the end numbers.insert(0, 6) # adds 6 at index position of 0 numbers.remove(6) # removes 6 numbers.pop() # removes the last item numbers.clear() # removes all the items numbers.index(8) # returns the index of first occurrence of 8 numbers.sort() # sorts the list numbers.reverse() # reverses the list numbers.copy() # returns a copy of the list
Tuples
Tuples are represented as comma-separated-values of any data type within parentheses.
Tuple Creation
variable_name = (element1, element2, ...)
Let’s talk about some of the tuple methods:
count method
It returns the number of times a specified value occurs in a tuple
tuple.count(value)
index method
It searches the tuple for a specified value and returns the position.
tuple.index(value)
Sets
A set is a collection of multiple values which is both unordered and unindexed. It is written in curly brackets.
Set Creation: Way 1
var_name = {element1, element2, ...}
Set Creation: Way 2
var_name = set([element1, element2, ...])
Set Methods
Let’s talk about some of the methods of sets:
add() method
Adds an element to a set
set.add(element)
clear() method
Remove all elements from a set
set.clear()
discard() method
Removes the specified item from the set
set.discard(value)
intersection() method
Returns intersection of two or more sets
set.intersection(set1, set2 ... etc)
issubset() method
Checks if a set is a subset of another set
set.issubset(set)
pop() method
Removes an element from the set
set.pop()
remove() method
Removes the specified element from the set
set.remove(item)
union() method
Returns the union of two or more sets
set.union(set1, set2...)
Dictionaries
The dictionary is an unordered set of comma-separated key: value pairs, within {}, with the requirement that within a dictionary, no two keys can be the same.
Dictionary
<dictionary-name> = {<key>: value, <key>: value ...}
Adding Elements to a dictionary
By this method, one can add new elements to the dictionary
<dictionary>[<key>] = <value>
Updating Elements in a dictionary
If a specified key already exists, then its value will get updated
<dictionary>[<key>] = <value>
Deleting an element from a dictionary
del keyword is used to delete a specified key: value pair from the dictionary as follows:
del[ ]
Dictionary Functions & Methods
Below are some of the methods of dictionaries
len() method
It returns the length of the dictionary, i.e., the count of elements (key: value pairs) in the dictionary
len(dictionary)
clear() method
Removes all the elements from the dictionary
dictionary.clear()
get() method
Returns the value of the specified key
dictionary.get(keyname)
items() method
Returns a list containing a tuple for each key-value pair
dictionary.items()
keys() method
Returns a list containing the dictionary’s keys
dictionary.keys()
values() method
Returns a list of all the values in the dictionary
dictionary.values()
update() method
Updates the dictionary with the specified key-value pairs
dictionary.update(iterable)
Also Check out these Cheatsheets:
- CSS Cheatsheet 2022 | CSS Cheatsheet For Interview | CSS Interview Questions
- The Ultimate HTML Cheatsheet for Beginners | HTML Cheatsheet for Web Developers [Latest Update‼️]
- Best Python Cheatsheet: The Ultimate Guide to Learning Python (Updated 2022) | For Beginners and Experts Alike
- Learn C++ Programming Basic To Advanced | C++ Cheatsheet 2022
- Keyboard Shortcuts For VS Code | VS Code Shortcut Keys Cheatsheet 2022
Also Read these Articles:
Checkout IBM Data Science Professional Certificate Answers – IBM Data Science Professional Certificate All Courses Answers | Free Data Science Certification 2021
Checkout Semrush Course Quiz Answers – Free Quiz With Certificate | All Semrush Answers For Free | 100% Correct Answers
Checkout Google Course Answers – All Google Quiz Answers | 100% Correct Answers | Free Google Certification
Checkout Hubspot Course Certification Answers – All Hubspot Quiz Answers | 100% Correct Answers | Hubspot Certification 2021
Checkout Hackerrank SQL Programming Solutions –Hackerrank SQL Programming Solutions | All SQL Programming Solutions in Single Post
Checkout Hackerrank Python Programming Solutions – Hackerrank Python Programming Solutions | All Python Programming Solutions in Single Post
Checkout Hackerrank Java Programming Solutions – Hackerrank JAVA Programming Solutions | All JAVA Programming Solutions in Single Post
Checkout Hackerrank C++ Programming Solutions – Hackerrank C++ Programming Solutions | All C++ Programming Solutions in Single Post
Checkout Hackerrank C Programming Solutions Certification Answers –Hackerrank C Programming Solutions | All C Programming Solutions in Single Post
Checkout Hackerrank C Programming Solutions Certification Answers –Hackerrank C Programming Solutions | All C Programming Solutions in Single Post
Excellent post but I was wanting to know if you could write a litte more on this topic? I’d be very thankful if you could elaborate a little bit further. Appreciate it!
incrível este conteúdo. Gostei muito. Aproveitem e vejam este conteúdo. informações, novidades e muito mais. Não deixem de acessar para descobrir mais. Obrigado a todos e até a próxima. 🙂
I don’t usually comment but I gotta say regards for the post on this great one : D.
Someone essentially help to make seriously articles I would state. This is the first time I frequented your web page and thus far? I amazed with the research you made to create this particular publish incredible. Great job!
Great ?V I should definitely pronounce, impressed with your web site. I had no trouble navigating through all the tabs as well as related information ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or something, website theme . a tones way for your customer to communicate. Excellent task..
This design is steller! You definitely know how to keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Great job. I really enjoyed what you had to say, and more than that, how you presented it. Too cool!
You made some clear points there. I looked on the internet for the issue and found most guys will consent with your website.