Today’s topic is Python Cheat Sheet. Python is an object-oriented, high-level programming language with a dynamic syntax. It is an interpreted language. Its high-level data structures, including dynamic typing and dynamic binding, make it highly attractive for use as a scripting language for rapid application development, machine learning, and linking existing components. In this reference guide, we will share some quick Python cheat sheet PDF code that can be helpful for Python programmers to get some insightful help.
Python Cheat Sheet
Python Programming Language Basics
Basic Mathematical Operations in Python
>>> 1 + 1 #addition 2 >>> 5 // 2 #integer division 2 >>> 5 / 2 #floating point division 2 >>> 5 * 2 #multiply two numbers 10 >>> 5 ** 2 #power of a number 2 >>> 5 % 2 #modulo operation 1
Print a message to the screen
>>> print("Hello")
HelloPrint Python’s ZEN to the screen
Zen of Python is a collection of 19 “guiding principles” for creating computer programs that influence the architecture of the Python programming language. Tim Peters, a software developer, wrote this set of principles in 1999.
>>> import it The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. The complex is more complex than the complex. A flat is better than a house. Spurs are better than thick. Readability counts. Special cases are not special enough to break the rules. Although practicality beats purity. Errors should never be passed in silence. if not expressly silent. In the face of ambiguity, resist the temptation to guess. There must be one - and preferably only one - obvious way to do this. Although that path may not be obvious at first if you're not Dutch. Now is better than ever. Never better than *right* now though. If the implementation is hard to explain, it's a bad idea. This might be a good idea if the implementation is easy to explain. Namespaces are a great idea - let's do more of them!
To assign a variable with some value
>>> a = 2 >>> print(a) 2 >>> a 2 >>> a = "Hello" >>> print(a) Hello >>> a 'Hello'
Data types in Python
Different types of assignments between variables
>>> a=2 #assigning an integer to a variable >>> print(a) 2 >>> a 2 >>> a = "Hello Learner" #assigning a string to a variable >>> print(a) Hello Learner >>> a 'Hello Learner' >>> a = 'a' #assigning a character to a variable >>> print(a) a >>> a 'a'
Printing type of the data contained in a variable
>>> a = "Hello Learner" #assigning a string to a variable >>> type(a) <class 'str'> >>> a=2 >>> type(a) <class 'int'>
Comments in Python
Single-line comments
# This is a comment
Docstrings
def fun(): """ This is a docstring """
Some commonly used functions
print()
>>> print('Hello!')
'Hello!'len()
>>> len('Hey')
3input()
>>> input('Enter some string')
Enter some stringTypecasting functions
>>> a='2' >>> a=int(a) >>> type(a) <class 'int'> >>> a=2 >>> a=str(a) >>> type(a) <class 'str'>
Flow control statements
>>> 1 == 1 True >>> 2 != 1 True >>> 1 == 1 True >>> 3 > 1 True >>> "one" == "two" False
Boolean operations
>>> True and True True >>> True or False False >>> not True False
Conditional statements
var = 'Python'
if var == 'Python':
print('Hi, Python')
else:
print('Hi, someone')
name = 'Python'
if name == 'Python':
print('Hi, Python')
elif name == 'Java':
print('You are Java')
else:
print('You are neither Java nor Python.')Loops in Python
idx = 0
while idx < 10: #loop runs from 0 to 9
print('Hello')
idx = idx + 1
for i in range(0,4,2): #start loop from 0, upto 4 with step size of 2
print('Hello')
Loop control statements
Break statement
while True:
print('What are you studying)
inp = input()
if inp == 'Nothing':
break
print('The end')Continue statement
while True:
print('What are you studying)
inp = input()
if inp == 'Nothing':
continue
else:
print("Good")
Functionsdef fun():
print('I am called')
fun()
def getValue(n):
if n == 2:
return 'It is 2'
else:
return 'It is not 2'
what = getValue(2)
print(what)Lists in Python
The most commonly used data structure in Python is a list, which is an ordered and mutable Python container. To create a list, put the elements inside square brackets [] and separate them with commas.
Creating arrays
>>> arr = ['A', 'B'] >>> arr ['A', 'B']
Indexing arrays
>>> arr = ['A', 'B'] >>> arr[0] 'A' >>> arr = ['A', 'B'] >>> arr[-1] 'B'
List slicing
>>> arr = ['A', 'B', 'C'] >>> arr[0:2] ['A', 'B']
Appending to a list
>>> arr = ['A', 'B']
>>> arr.remove('B')
Remove an element from the list
>>> arr = ['A', 'B']
>>> arr.remove('B')
Sorting a list
>>> arr = [2, 1] >>> arr.sort() >>> arr [1, 2]
Strings in Python
Python strings are arrays of bytes that represent Unicode characters. Python lacks character data types. Most functions that work with lists can be used with strings in Python as well.
Indexing
>>> string = 'Hello!' >>> string[0] 'H'
upper() and lower() methods
>>> string = 'Hello!' >>> string = spam.upper() >>> string 'HELLO!' >>> string = "HEY" >>> string = string.lower() >>> string 'hey'
join() and split()
>>> ', '.join(['A', 'B', 'C'])
'A, B, C'
>>> 'HeyKMan'.split('K')
['Hey', 'Man']
String Manipulation
>>> print("Hello!\nHow are you?\nI\'m great")
Hello!
How are you?
I'm great
Tuple in Python
Tuples are a Python data structure that stores an ordered series of values. Tuples are immutable. This indicates that the value of a tuple cannot be changed.
a = ('A', 1)
>>> a[0]
'A'
>>> tuple(['A', 'B'])
('A', 'B')
Dictionary in Python
In Python, a dictionary is an unordered collection of data values that is used to store data values, like a map. Unlike other data types that have only a single value as an element, a dictionary maintains a key, value pair.
Creating a dictionary
hash = {'key1': 'value1', 'key2': 'value2'}Indexing in dictionaries
>>> hash = {'key1': 'value1', 'key2': 'value2'}
>>> hash['key1']
'value1'Iterating dictionaries
>>> hash = {'key1': 'value1', 'key2': 'value2'}
>>>
>>> for k, v in hash.items():
>>> print('Key: {} Value: {}'.format(k, str(v)))
Key: key2 Value: value2
Key: key1 Value: value1
Sets in Python
A set is an unordered collection of items that have no duplicates SET can be used to eliminate duplicate entries. Set objects are capable of performing mathematical operations such as union, intersection, difference, and symmetric differentiation. The set cannot be indexed.
Initializing sets
>>> s = {1, 2, 3, 2, 3, 4}
>>> s
{1, 2, 3, 4}Adding to sets
>>> s = {1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}Removing from sets
>>> s = {1, 2, 3}
>>> s.remove(3)
>>> s
{1, 2}Sets Union
union() will create a new set that contains all the elements from the sets provided.
>>> s1 = {1, 2, 3}
>>> s2 = {3, 4, 5}
>>> s1.union(s2)
{1, 2, 3, 4, 5}Sets Intersection
The intersection will return a set containing only those elements that are common to all of them.
>>> s1 = {1, 2, 3}
>>> s2 = {2, 3, 4}
>>> s3 = {3, 4, 5}
>>> s1.intersection(s2, s3)
{3}
Lambda Functions
>>> sum = lambda x, y: x + y >>> sum(1, 2) 3
Comprehensions
List comprehension
>>> a = [1, 2, 3] >>> [i for i in a] [1, 2, 3]
Sets comprehension
>>> Set = {"a", "b"}
>>> {s.upper() for s in Set}
{"A", "B"}Exception handling
Try:
result = x // y
print("Answer is :", result);
Without zerodivision error:
print("not divisible by zero")
Try:
k = 5//0
Without zerodivision error:
print("not divisible by zero")
Finally:
print('This is always executed');
Python module
A module is a Python object that contains arbitrarily named properties that you can import and use in your code. Simply put, a module is a file containing some useful Python code.
You can import a module in your script using the syntax below.
import module_name
Below are some useful modules which can be helpful for you while coding.
itertools
re (Regular Expression)
logging
function tools
math
Conclusion
In this complete tutorial, We have prepared a list of necessary Python Cheat Sheet PDF reference guides for you from beginners to advanced levels. While various Python developers are looking for this kind of cheat sheet because remembering each code is too tough and very time-consuming for developers, So they want some sort of information like this cheat sheet. Read about the remote desktop black screen problem solution here. Buy RDP from here.



