Python
cheatsheet
Beginners
Indian servers WWW.INDIANSERVERS.COM
Main datatypes
Integers (int) - an integer number to represent an object
such as “3”.
float - we use them to represent floating-point numbers.
For example "0.5".
Complex Numbers – represented by complex class. It is
specified as (real part) + (imaginary part)j. For example –
"2+3j".
Strings - codify a sequence of characters using a string.
For example, the word “hello”.
Boolean - Data type with one of the two built-in values,
True or False.
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Main datatypes
List - Python Lists are similar to arrays in C. However, the
list can contain data of different types ex ["apple",
"banana", "cherry"]
Tuple - tuple is similar to the list, a read-only data
structure as we can't modify the size and value of the
items of a tuple, ex ("apple", "banana", "cherry")
Dictionary - an unordered set of a key-value pair of items.
Ex {"name" : "John", "age" : 36}
Set - Set is the unordered collection of the data type. It is
iterable, mutable, and has unique elements. Ex {"apple",
"banana", "cherry"}
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
how to create a String
IMP! Whichever option you choose, you should stick
to it and use it consistently within your program.
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
String Concatenation & pRinting
Output:- IndianServers
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
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
String Replication
'Indian Servers ' * 5 'Indian Servers Indian Servers
Example :- Indian Servers Indian Servers Indian Servers
Output:-
Indian Servers Indian Servers Indian Servers Indian
Servers Indian Servers
As the name implies, this command lets you repeat the same
string several times. This is done using * operator.
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Math operators
Operators Operation Example
** Exponent 2 ** 3 = 8
% Modulus 21 % 2 = 1
// Integer Division 22 / 8 = 2
/ Division 21 / 3 = 7
* Multiplication 3*3=9
- Subtraction 2-1=1
+ Addition 1+1=2
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Built-in Functions
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
Hi! What’s your name? “Indian Servers” Nice to meet
Output:- you, Indian Servers! How old are you? 13 So, you are
already 13 years old, Indian Servers!
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Define a Function
Apart from using in-built functions, Python also allows you to
define your own functions for your program.
Syntax:-
def function_name(aregument1, argument2,....):
statement 1
statement 2
.......
Example:-
Output:- What's your name?
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
if, else, elif - used for conditional branching or decision
making
from, import - used to import modules into the current
namespace
except, raise, try - used with exceptions in Python.
for - for is used for looping
finally - used with try…except block to close up
resources or file streams.
Indian Servers
@indianserverltd Indian Servers 2021
Indian servers WWW.INDIANSERVERS.COM
global - used to declare that a variable inside the
function is global
in - used to test if a sequence (list, tuple, string etc.)
contains a value.
is - used in Python for testing object identity
lambda - used to create an anonymous function
nonlocal - used to declare that a variable inside a
nested function
Indian Servers
@indianserverltd Indian Servers 2021
Indian servers WWW.INDIANSERVERS.COM
return - used inside a function to exit it and return a value
pass - pass is a null statement in Python
while - used for looping in Python.
with - used to wrap the execution of a block of code within
methods defined by the context manager.
yield - used inside a function like a return statement.
But it returns a generator.
Indian Servers
@indianserverltd Indian Servers 2021
Indian servers WWW.INDIANSERVERS.COM
Define a Function
True, False - True and False are truth values in Python.
assert - used for debugging purposes.
and, or , not - Logical operators in Python,
as - create an alias while importing a module.
None - Represents the absence of a value or a null value
Indian Servers
@indianserverltd Indian Servers 2021
Indian servers WWW.INDIANSERVERS.COM
async, await - used to write concurrent code in Python
del - del is used to delete the reference to an object.
class - used to define a new user-defined class in Python.
def - def is used to define a user-defined function.
break, continue - used inside for and while loops to alter
their normal behavior.
Indian Servers
@indianserverltd Indian Servers 2021
Indian servers WWW.INDIANSERVERS.COM
if, else, elif - used for conditional branching or decision
making
from, import - used to import modules into the current
namespace
except, raise, try - used with exceptions in Python.
for - for is used for looping
finally - used with try…except block to close up
resources or file streams.
Indian Servers
@indianserverltd Indian Servers 2021
Indian servers WWW.INDIANSERVERS.COM
global - used to declare that a variable inside the
function is global
in - used to test if a sequence (list, tuple, string etc.)
contains a value.
is - used in Python for testing object identity
lambda - used to create an anonymous function
nonlocal - used to declare that a variable inside a
nested function
Indian Servers
@indianserverltd Indian Servers 2021
Indian servers WWW.INDIANSERVERS.COM
return - used inside a function to exit it and return a value
pass - pass is a null statement in Python
while - used for looping in Python.
with - used to wrap the execution of a block of code within
methods defined by the context manager.
yield - used inside a function like a return statement.
But it returns a generator.
Indian Servers
@indianserverltd Indian Servers 2021
Indian servers WWW.INDIANSERVERS.COM
Pass Keyword Arguments
A function can also accept keyword arguments. In this case,
you can use parameters in random order as the Python
interpreter will match the values to the parameters
Product Name: White T-shirt:
Output:- Price 15
Product Name: jeans
Price 45
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Lists
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.
Example:- my_list = [1, 2, 3]
my_list2 = [“a”, “b”, “c”]
my_list3 = [“4”, d, “book”, 5]
Alternatively, you can use list() function to do the same
alpha_list = list((“1”, “2”, “3”))
print(alpha_list)
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Add Items to a List
The first one is using append() function:
The second option is to insert() function to add an item at the
specified index:
['apple', 'android', 'Indian Servers', 'python']
Output:-
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Remove an Item from a List
The first one is using remove() function:
The second option is to pop() function if no index is specified it
will remove the last item
Output - ['Indian Servers', 'python']
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
List Operations
Combine two lists - To mash up two lists use the + operator.
Output - combo_list = [1, 2, 3, 'a', 'b', 'c']
Create Nested list - You can also create a list of your lists
when you have plenty of them
Output - my_nested_list [[1, 2, 3], [‘a’, ‘b’, ‘c’]]
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Sort a list - Use the sort() function to organize all items in
your list.
Output - sorted list = [2, 23, 34, 67, 88, 100]
Slice a List - if you want to call just a few elements from
your list
Output - sliced list [2, 23, 34, 67]
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Change an item of list - You can easily overwrite a value of
one list items:
Output - ['Indian Servers', 'python', 'apple']
Loop through a List - Using for loop you can multiply the
usage of certain items
Output - ['Indian Servers', 'python', 'android', 'tech', 'tech', 'tech']
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Copy a List - Use the built-in copy() function to replicate
your data:
Alternatively, you can copy a list with the list() method:
Output - ['Indian Servers', 'python', 'android']
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
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.
How to Create a Tuple
Note: Once you create a tuple, you can’t add new items
to it or change it in any other way
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Slice a tuple - the process is similar to slicing lists.
Output - (1, 3, 5, 7, 9)
Tuple to a List - Since Tuples are immutable, you can’t
change them. What you can do though is convert a tuple
into a list, make an edit and then convert it back to a
tuple.
Output - ('Indian Servers', 'Python', 'iPhone')
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
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:
customer1= {
'username': 'sai-satish',
'online': 'false',
'friends':100
}
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Create Dictionary - Here’s a quick example showcasing how
to make an empty dictionary.
Option 1: new_dict = {}
Option 2: other_dict= dict()
And you can use the same two approaches to add values to
your dictionary:
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Access a Value in a Dictionary - You can access
any of the values in your dictionary the following
way:
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
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Change Item Value - To change one of the items, you
need to refer to it by its key name:
{'brand': 'Indian Servers', 'industry':
Output - 'education', 'year': 2021}
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Loop through a Dictionary - Again to implement
looping, use for loop command
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
If Statements in Python
Just like other programming languages, Python
supports the basic logical conditions from math:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
You can leverage these conditions in various ways.
But most likely, you’ll use them in “if statements” and
loops.
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
If Statement Example - The goal of a conditional statement
is to check if it’s True or False.
Output - That's True!
Nested If Statements - For more complex operations, you can
create nested if statements. Here’s how it looks:
Output - Above twenty,
and also above 30!
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Elif Statements - elif keyword prompts your program to try
another condition if the previous one(s) was not true. Here’s an
example
Output - 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:
Output -
Case I:- if age is less than
4 ticket_price = 0
Case II:- if age is greater
than 4 but less than 18
then ticket_price = 10
Case III:- if age is greater
than 18 ticket_price = 15
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
If-Not-Statements - Not keyword let’s you check for the
opposite meaning to verify whether the value is NOT True:
Output - That's True!
Pass Statements - If statements can’t be empty. But if that’s
your case, add the pass statement to avoid having an error:
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Python Loops
Python has two simple loop commands that are good
to know:
• for loops
• while loops
for loop - for loop is a handy way for iterating over a sequence
such as a list, tuple, dictionary, string, etc.
Output - Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
while loop - While loop enables you to execute a set of statements
as long as the condition for them is true.
Output - Indian Servers
Indian Servers
Indian Servers
Indian Servers
Indian Servers
Indian Servers
Indian Servers
Nested Loop - You can also stop the loop from running even if the
condition is met. For that, use the break statement both in while
and for loops:
Output -
2 is prime 3 is prime 5 is prime 7
is prime 11 is prime 13 is prime 17
is prime 19 is prime 23 is prime 29
is prime 31 is prime 37 is prime 41
is prime 43 is prime 47 is prime 53
is prime 59 is prime 61 is prime 67
is prime 71 is prime 73 is prime 79
is prime 83 is prime 89 is prime 97
Indian Servers is prime
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Break a loop - You can also stop the loop from running
even if the condition is met. For that, use the break
statement both in while and for loops:
1
Output - 2
3
4
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Python - Network Programming
Python provides two levels of access to network
services. At a low level, you can access the basic
socket support in the underlying operating system,
which allows you to implement clients and servers for
both connection-oriented and connectionless
protocols.
Python also has libraries that provide higher-level
access to specific application-level network
protocols, such as FTP, HTTP, and so on.
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Sockets
Sockets are interior endpoints built for sending and
receiving data. A single network will have two sockets, one
for each communicating device or program. These sockets
are a combination of an IP address and a Port. A single
device can have ‘n’ number of sockets based on the port
number that is being used. Different ports are available for
different types of protocols.
Protocol Port Functions
HTTP 80 Web Pages
FTP 20 File Transfers
NNTP 119 Unsent
SMTP 25 Sending Email
Telnet 23 Command Lines
POP3 110 Fetching Email
Gopher 70 Document Transfer
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Socket Types
SOCK_STREAM - For TCP protocols, Reliable transmission, Packet
sequence, Connection-oriented, Bi-directional
SOCK_DGRAM - For UDP protocols, Unreliable transmission, No
sequence of packets, Connectionless(UDP), Not Bidirectional
Socket Family - AF_UNIX of AF_INET
import socket #Imports the socket method
socket.socket() #Function that creates socket
sock = socket.socket(socket family, socket type, protocol=value)
Socket Methods :
Client socket method - connect()
Server socket methods - bind(), listen(backlog), accept()
TCP socket methods -
s.recv() #receive TCP packets
s.send() #send TCP packets
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Server
A server is either a program, a computer, or a device that is devoted to
managing network resources. Servers can either be on the same
device or computer or locally connected to other devices and
computers or even remote. There are various types of servers such as
database servers, network servers, print servers, etc.
Servers commonly make use of methods like socket.socket(),
socket.bind(), socket.listen(), etc to establish a connection and bind to
the clients.
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Client
A client is either a computer or software that receives information
or services from the server. In a client-server module, clients
requests for services from servers. The best example is a web
browser such as Google Chrome, Firefox, etc. These web browsers
request web servers for the required web pages and services as
directed by the user. Other examples include online games, online
chats, etc.
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Socket Errors/Exceptions
exception socket.error - A deprecated alias of OSError,
raised when a system function returns a system-related
error.
exception socket.herror - raised for address-related errors
exception socket.gaierror - raised for address-related errors
by getaddrinfo() and getnameinfo()
exception socket.timeout - raised when a timeout occurs
on a socket which has had timeouts enabled via a prior call
to settimeout() (or implicitly through setdefaulttimeout())
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Python Network programming libraries
Django - High-level Python Web framework for rapid development
and pragmatic
pycos - Python framework for asynchronous, concurrent, network,
distributed programming and distributed computing
Diesel - A clean API for writing network clients and servers. TCP and
UDP supported. Bundles client for HTTP, DNS, Redis, Riak, and MongoDB
Pulsar - Easy way to build scalable network programs
Twisted - Event-based framework for internet applications: HTTP
clients and servers, SSHv2 and Telnet, IRC, XMPP, IMAPv4, POP3, SMTP,
etc.
NAPALM - Network Automation and Programmability Abstraction
Layer with Multivendor support - For dealing with device vendors
gevent - A coroutine-based Python networking library that uses
greenlet to provide a high-level synchronous API on top of the libev or
libuv event loop.
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Python 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.
create a Class - Let’s create a class named TestClass, with one
property named z:
create an object - As a next step, you can create an object using
your class. Here’s how it’s done:
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
You can assign different attributes and methods to your object.
The example is below:
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Create a Subclass - Every object can be further sub-classified.
Here’s an example
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Python Exceptions (Errors)
Python has a list of in-built exceptions (errors) that will pop up
whenever you make a mistake in your code. As a newbie, it’s
good to know how to fix these.
The Most Common Python Exceptions
• AttributeError — pops up when an attribute reference or
assignment fails.
• IOError — emerges when some I/O operation (e.g. an open()
function) fails for an I/O-related reason, e.g., “file not found” or
“disk full”.
• ImportError — comes up when an import statement cannot
locate the module definition. Also, when a from… import can’t find
a name that must be imported.
• IndexError — emerges when a sequence subscript is out of
range.
• KeyError — raised when a dictionary key isn’t found in the set of
existing keys.
• KeyboardInterrupt — lights up when the user hits the interrupt
key (such as Control-C or Delete).
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Python Exceptions (Errors)
Python has a list of in-built exceptions (errors) that will pop up
whenever you make a mistake in your code. As a newbie, it’s
good to know how to fix these.
The Most Common Python Exceptions
• NameError — shows up when a local or global name can’t be
found
• OSError — indicated a system-related error.
• SyntaxError — pops up when a parser encounters a syntax error.
• TypeError — comes up when an operation or function is applied
to an object of inappropriate type.
• ValueError — raised when a built-in operation/function gets an
argument that has the right type but not an appropriate value,
and the situation is not described by a more precise exception
such as IndexError.
• ZeroDivisionError — emerges when the second argument of a
division or modulo operation is zero.
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
Troubleshoot the Errors
Python has a useful statement, design just for the purpose of
handling exceptions — try/except statement. Here’s a code
snippet showing how you can catch KeyErrors in a dictionary
using this statement:
You can also detect several exceptions at once with a single
statement. Here’s an example for that:
Indian Servers
@indianserverltd Indian Servers
Indian servers WWW.INDIANSERVERS.COM
try/except with else clause
Adding an else clause will help you confirm that no errors were
found:
Indian Servers
@indianserverltd Indian Servers