Browse by Domains

Python Cheat Sheet

Introduction

The rapid adoption of technology and emergence of data science has led to increased use of Python for data development in the IT industry. However, it can be difficult to remember all the syntax involved in this language. Python is a unique language that follows a simplified syntax. Many famous applications like YouTube and BitTorrent rely on Python to achieve a number of operations and smooth functionality. Even if you are an ace developer, it is impossible to remember every syntax of Python. This is where the Python cheat sheet will come in handy.

The cheat sheet will include the main aspects of Python that are very straightforward to use whenever you need them, and it will help beginners as well as advanced programmers. Let us refresh several Python tips and tricks with this cheat sheet.  

Basics rules to write a Python Syntax 

Python is a high-level debug programming language that comes with a set of codes that are easy to learn and remember. Python syntax is the set of basic rules used to write its code. They also find similarities with Perl, Java, and C programming languages. The right syntax is important to get executable code. 

Python syntax follows the same standards internationally. Before we begin to talk about various examples of syntax in Python, let us see some rules that every programmer needs to follow while using the syntax –

  • English names are used in programming as per the standard.
  • All variables start with lowercase letters.
  • Python is case-sensitive.
  • Classes always start with an uppercase letter.
  • Names do not include special characters.
  • Some reserved words, such as if, else, etc., are not allowed in the naming.

Example –

Python Variable Syntax 

Let us create a variable code in Python. It goes like this:

# Creating variable

a = 5

Terminate statement in Python – optional semicolon

The semicolon is used to terminate program statements in various programming languages such as Java and C. However, it is optional in Python. 

Either you write:

# No Semicolon

print(“Hello, javaexercise.com”)

Or you write:

# Using Semicolon

print(“Hello, javaexercise.com”);

The output will remain the same in both cases, which is:

Hello, javaexercise.com

Data Types

Data types are classes that are built into Python. Since everything in Python is an object, the variables are objects of the classes. 

Various data types in Python are enlisted below –

  • Integers: Some examples include -2, -1, 0, 1, 2, 3.
  • Strings: In Python, String is denoted as str. Examples include ‘Hello’, ‘abc’.
  • Floating point numbers: Examples include -0.5, 0.0, 0.004.
  • Complex numbers: These are specified as <real part>+<imaginary part>j

Examples include (4+2j)

  • Sets: Example include a={4,5,6,7}
  • Tuple: Example include b= 1,3,5

Operators

In Python, operators are used for performing mathematical functions or logical computations. They can be used to manipulate the value of the operand. For example, in operation 2+4=6, 2 and 4 are operands, and + is the operator. 

  • Arithematic operators: carry out functions like addition, subtraction, multiplication, division, etc. For example – a+b = 2, a-b = 0, and so on.
  • Comparison operators: These are also called rational operators and are used to compare values. For example – x>y, y<z, x=y.
  • Logical operators: These are used to perform LogicalOR, LogicalAND, and LogicalNOT operations. For example – The syntax for LogicalOR is x or y, and it implies that the statement is true if either of the operands is true.

Operations

Based on different data types, Python also has some built-in operations. 

  • List operations: 

List=[]: to define an empty list

append(val): Adds an item at the end

pop([i]): Removes and returns item at index i

  • String operations:

String[i]: Used to retrieve the character at the ith position

String[i:j]: Used to retrieve characters in the range i to j

  • Dictionary Operations”

dict={} : Tp define an empty dictionary

Values: to give all the values

Key: to give all the key items 

Flow Control Methods

  • If statement

If name == ‘Marie’:

print(‘Hi, Marie.’)

  • Else statement

name = ‘Bill’

if name == ‘Marie’:

    print(‘Hi, Marie.’)

else:

    print(‘Hello, stranger.’)

  • Else-if statement 

name = ‘Bill’

age = 2

if name == ‘Marie’:

    print(‘Hi, Marie.’)

elif age < 12:

print(‘You are not Marie, kiddo.’)

  • White loop statement

spam = 1

while spam < 5:

    print(‘Hello, world.’)

    spam = spam + 2

Functions

Functions are a group of statements that perform a specific task when called. It contains data as parameters and can return data as well.

Here is an example of creating a function in Python:

def my_function():

  print(“Hello from a function”)

Here is another example of calling a function:

def my_new fuction():

  print(“Hello!! This the output from the function you called”)

my_newfunction()

Lambda Functions

Lambda functions in Python are anonymous functions. It means that it does not have a name and can have only one expression regardless of the number of arguments. To learn more about the concept and be introduced to the concept of Serverless Computing, you can check out the AWS Lambda Tutorial.

The syntax for the lambda function is:

lambda arguments : expression

Where it can have any number of arguments, and only one expression is returned. 

An example includes:

Multiply argument ‘x’ with argument ‘y’ to return the result –

 A= lambda x, y : x*y

Print (A(4,5) )

Generic Operations

Some examples of built-in functions in Python are:

  • Min(x) – Gives the minimum value of x
  • Max(x): Gives maximum value in x
  • X=input(“Enter:”)
  • sum(a): Adds up items to returns sum
  • range(5): 0,1,2,3,4
  • sorted(x): Sorted list copy of x 

File Operations

File operations refer to functions in Python that are used to create, delete, update and manage files. Both the binary and text files are taken differently. You can set the file function mode as well. For instance, ‘t’ is for text mode and ‘r’ is for read mode. Most commonly performed functions include opening the file, closing, reading, writing, removing, and detaching, among others.

Opening a file in Python

The syntax for opening a file is – file = open (“abc.txt”)

Opening a file in Python consists of four methods –

  • ‘r’ – This mode opens the file for reading.
  • ‘a’ – In this mode, the file opens in append mode.
  • ‘w’ – The file opens in write mode.
  • ‘x’ – Creates a specified file.

Closing a file in Python

To close the file, the close() method is used. Even though it is not required to close the file in Python but it is considered a good practice.

The syntax is file.close() 

Try & Except Block

In Python, we encounter two types of errors – syntax errors and exceptions. Both Try and Except blocks are used to handle these types of errors in Python. 

Try Block checks for errors in the code. This means that the code inside the Try block will only execute in the absence of errors within the program. On the other hand, Except block helps in handling the error. This means that the code within Except block will execute if the program encounters an error in the Try block earlier. 

Here is the syntax –

try:

    # Some Code

except:

    # Executed if an error in the

    # try block 

Here is an example of a Try block –

When ‘x’ is not defined, the try block will generate an exception. 

try:

  print(x)

except:

  print(“An exception occurred”)

Oops Concepts

The concept of Oops in Python stems from solving a problem using objects. This is called object-oriented programming (OOPs), which is a programming paradigm. The main idea behind it is to combine the data and functions so that they work together as a single unit. The main concepts of Oops include –

  • Class – It is a collection or blueprint of the object. The syntax for a class definition is:

class ClassName:

   # Statement-1

   .

   .

   .

   # Statement-N

  • Objects – An object can be any entity that has a defined state, identity, and behavior. It can be real-world as well. Some examples of objects include integers, floating objects, strings, arrays, and so on. An example of creating an object includes –

obj = Dog()

  • Inheritance – It entails the creation of a new class using an existing class without modifying it. The existing class is called the parent class, and the new class is called the child class.
  • Polymorphism – It is a concept that involves using multiple forms of data within a common interface. 
  • Encapsulation – It involves restricting the variables and methods of one class from other objects so that one does not accidentally modify the data. 

Class/Objects

A class is a user-defined constructor that is used for creating objects. Each class has specific attributes associated with it. These attributes are variables and are always public. 

Here is how to create a class named MyWorld using a property named ‘y’ :

class MyWorld:

  Y = 5

Comments

Comments are used to explain the code in Python and make it readable. Single line comments always start with ‘#’. 

For example:

#This is a comment

print(“Hello, World!”)

If the comment is at the end of the line, Python will ignore it. For multi-line comments, you can use “triple quotes.”

Exception Handling

Exceptions are the type of errors that are raised when the program encounters an issue in the code. When exceptions happen, the program will crash if it is not handled. If exceptions are not handled, the program will not execute, and an error message will be displayed. 

Exceptions can be caught using try and except statements. Statements that led to exceptions are placed inside the try clause. In the except clause, the statements that handle exceptions are written.

When there’s a specific exception, it can be caught using specific handlers within the try clause. For instance, IndexError can be used in the code to tackle specific exceptions. Here’s the general syntax for that –

try:

    # statement(s)

except IndexError:

    # statement(s)

except ValueError:

    # statement(s)

Lists

Lists are used to store multiple items within a single variable. In Python, lists are properly ordered, and their elements are indexed. Additionally, lists can be altered even after they are created. Lists are highly important in Python and are used in preserving data.

Square brackets are used to create lists in Python. An example includes:

thislist = [“banana”, “melon”, “cherry”]

print(thislist) 

The items in the list are indexed, which means that the first item is indexed [0], and the second item is indexed [1]. 

Some things to remember about lists –

  • The items in the list are ordered, and their specific order remains unchanged.
  • It is easy to change or modify the list after its creation. 
  • Some lists allow for duplicates as they are indexed.

Debugging

You can start a debugger using this command –

Debugging in Python is done using a debugger program which is interactive source code. It is facilitated by a Python debugger, also known as the pdb module. It usually comes built-in and utilizes basic bdb(basic debugger functions) and cmd(support for line-oriented command interpreters) modules. 

import pdb, pdb.set_trace()

Reading and Writing Files

Python has built-in functions that help in reading and writing files. Two types of files are handled in Python – text files and binary files. 

Read Only or ‘r’ mode – This mode helps to open text files for reading. 

Read and write or ‘r+’ mode – This mode opens the files for reading as well as writing. 

Write only or ‘w’ mode – This mode is used to open the file for writing.

Write and read ‘w+’ mode – This mode helps to open the file for writing and reading. 

Append and read or ‘a+’ mode – This mode allows the file to open for reading and writing. If the file does not exist, it gets created. 

Data Classes 

Data classes are implemented in Python to store data using structured classes. These classes have specific attributes associated with the data and their representatives. Using decorators, data classes can be implemented. 

Attributes are indicated using Type Hints which refers to the specific data type for variables. Data classes are one of the newest features of Python 3.7.

String Formatting

As the name suggests, it corresponds to the formatting of strings in Python. The process involves the dynamic infusing of things in strings. It can be done using the format() method and putting them within the string’s placeholder. The syntax is –

string.format(value1, value2…)

The placeholders can denote indexed numbers or even empty placeholders. You can perform formatting in four different ways –

  • Using % operator.
  • Using format() string method.
  • Using f-strings.
  • Using String Template Class

Virtual Environment 

In Python, a virtual environment is a tool that facilitates the creation of isolated python environments to keep different projects separated from system site directories. Each virtual environment in Python can have its own unique set of Python packages installed in site directories. 

The ‘venv’ module is used to create lightweight virtual environments. It can be done by executing the following command –

python3 -m venv /path/to/new/virtual/environment

When you run this command, it creates a target directory and places pyvenv.cfg file into it. It also creates lib/pythonX.Y/site-packages subdirectory and a bin containing a copy of the Python binary. 

Enroll in this Python Android app development course to learn the fundamentals of Kivy and Python through hands-on exercises.

Avatar photo
Great Learning
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top