Core Python Cheatsheet - W - Java119
Core Python Cheatsheet - W - Java119
Core Python
TABLE OF CONTENTS
Preface 2
Introduction 2
Modules and Packages 2
Data Manipulation and Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Data Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Machine Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Web Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Game Development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Installing New Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Data Types and Variables 4
Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Operators 4
Sequence Unpacking 5
Conditional Statements 5
if statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
if-else statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
if-elif-else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Loops 5
for loop. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
while loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Functions 6
Function Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Function Call. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Optional Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Variable-Length Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Keyword Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Default Argument Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Anonymous Functions (Lambda Functions) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Variable Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Lists 6
List methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Dictionaries 7
Dictionary methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Tuples 7
Sets 7
Set methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Manually
GAME DEVELOPMENT
You can download the source code of a library from
Pygame its website or GitHub repository and install it
manually by following the installation instructions
Pygame is a set of Python modules for creating provided by the library’s documentation.
video games and multimedia applications. It
provides support for graphics, sound, input, and Once you have installed a new library, you can
networking, making it easy to create games and import it into your Python code using the import
interactive applications in Python. statement. For example, to import the numpy
# Repeating a string
x = 5 # x is an integer repeat_string = my_string * 3 #
x = "hello" # x is now a string Output: "hello worldhello worldhello
x = 3.14 # x is now a float world"
• Integers: whole numbers without decimal Strings in Python are immutable, which means that
points. e.g. 1, 2, 3, 4, 5 once you create a string, you cannot change its
contents. However, you can create a new string that
• Floats: numbers with decimal points. e.g. 3.14, contains the modified content.
4.5, 6.0
• Strings: sequences of characters. e.g. "hello", String formatting is another important feature in
'world' Python, which allows you to insert values into a
string in a specific format.
• Booleans: True or False values.
Here are some basic operations that can be • Arithmetic operators: +, -, , /, % (modulus),*
performed on strings: (exponentiation)
if condition:
my_tuple = (1, 2, 3) # code to execute if condition
a, b, c = my_tuple is true
print(a) # Output: 1 else:
print(b) # Output: 2 # code to execute if condition
print(c) # Output: 3 is false
a = 1
FOR LOOP
b = 2
a, b = b, a Iterates over a sequence of values.
print(a) # Output: 2
print(b) # Output: 1
for value in sequence:
# code to execute for each value
CONDITIONAL STATEMENTS in sequence
IF STATEMENT
WHILE LOOP
Executes a block of code if a condition is true.
Executes a block of code as long as a condition is
true.
if condition:
KEYWORD ARGUMENTS
while condition:
# code to execute while
condition is true def function_name(parameter1,
parameter2, ..., keyword1=value1,
keyword2=value2, ...):
FUNCTIONS # function body
return value
FUNCTION DEFINITION
def function_name():
OPTIONAL ARGUMENTS # Local variable
variable_name = value
result = def
function_name(parameter1,
LISTS
parameter2=default_value, ...):
# function body Ordered collections of items.
return value
LIST METHODS
def function_name(*args):
# function body
return value my_list.append(item) # adds an item
to the end of the list
my_list.insert(index, item) #
inserts an item at a specific index
my_list.pop() # removes and returns
the last item in the list returns a new set with items that
my_list.remove(item) # removes the are common to both sets
first occurrence of an item
DICTIONARY METHODS
OUTPUT
SET METHODS
WRITING TO A FILE
my_set.add(item) # adds an item to
the set file.write("Hello, world!") #
my_set.remove(item) # removes an writes string to file
item from the set
my_set.union(other_set) # returns a
new set with all unique items from
both sets
my_set.intersection(other_set) #
CLOSING A FILE
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
file.close() # closes file
person1.say_hello()
person2.say_hello()
EXCEPTION HANDLING
CLASSES @classmethod
def class_method(cls):
In Python, a class is a blueprint for creating objects. print(cls.class_var)
It defines a set of attributes and methods that the
objects will have. When you create an instance of a
MyClass.class_method()
class, you create a new object that has the same
attributes and methods as the class.
To define a class method, we use the @classmethod
decorator before the method definition. The first
class Person: parameter of a class method is always cls, which
def __init__(self, name, age): refers to the class itself. You can use the cls
self.name = name parameter to access class variables and methods.
self.age = age
INHERITANCE
def say_hello(self):
print("Hello, my name is", Classes can also inherit attributes and methods
self.name, "and I'm", self.age, from other classes.
"years old.")
class Student(Person):
def __init__(self, name, age,
OBJECTS
grade):
Instances of a class with specific values for their super().__init__(name, age)
attributes. To create an instance of the Person class, self.grade = grade
we use the constructor method `init` which
initializes the object’s attributes. We then call the def say_hello(self):
say_hello method on each object to print the print(f"Hello, my name is
greeting message.
{self.name}, I am {self.age} years
import my_package.my_module
DECORATORS
my_package.my_module.my_function()
Functions that modify the behavior of other
# calls a function from the module
functions.
in the package
def my_decorator(func):
LAMBDA FUNCTIONS def wrapper(*args, **kwargs):
# code to execute before the
Anonymous functions that can be defined in a
original function
single line of code.
result = func(*args,
**kwargs) # call the original
my_lambda = lambda x: x**2 # function
defines a lambda function that # code to execute after the
squares its input original function
return result
result = my_lambda(3) # calls the return wrapper
lambda function with input 3
@my_decorator
def my_function():
LIST COMPREHENSIONS # code to execute
METACHARACTERS
from functools import reduce
• . (dot): Matches any character except a newline
character.
def my_function(x, y):
return x + y • ^ (caret): Matches the start of a string.
import re
JCG delivers over 1 million pages each month to more than 700K software
developers, architects and decision makers. JCG offers something for everyone,
including news, tutorials, cheat sheets, research guides, feature articles, source code
and more.
CHEATSHEET FEEDBACK
WELCOME
support@javacodegeeks.com
Copyright © 2014 Exelixis Media P.C. All rights reserved. No part of this publication may be SPONSORSHIP
reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, OPPORTUNITIES
mechanical, photocopying, or otherwise, without prior written permission of the publisher. sales@javacodegeeks.com