Programs

Python Cheat Sheet [2024]: A Must for Every Python Developer

Anyone who follows computer programming languages knows that Python is moving forward at a tremendous pace. Back in June 2019, TIOBE noted that “if Python can keep this pace, it will probably replace C and Java in 3 to 4 years time, thus becoming the most popular programming language of the world.” 

Fast forward to 2024 and Python is currently at the second position with a rating of 11.84%, and is well-positioned to surpass C to establish itself as the No. 1 programming language amongst developers!

What’s noteworthy is that Python’s ratings have significantly grown between this period — so much that it won the TIOBE programming language of 2020 award due to its rising popularity.

In this article, we deep-dive into Python and bring you a comprehensive Python syntax cheat sheet so you can brush up on important concepts of Python. It can work as a quick reference for both beginners and advanced developers. 

So, let’s get started!

What is Python? 

Python is a powerful, easy to learn, close-to-human language capable of delivering highly efficient and scalable applications. It is an open-source, high-level language offering a wide range of options for web development. Its real-world applications include artificial intelligence and machine learning, game development, scientific and numerical computation, web scraping, and more. 

Python finds extensive use in data science and machine learning (ML). In 2020, its scikit-learn ML library witnessed an 11% growth in usage! However, that’s nothing compared to the 159% leap its PyTorch ML framework saw in the field of deep learning. As per the O’Reilly Data Science Salary Survey, nearly 54% of respondents stated that Python is their go-to tool for data science.

Since its launch in 1990 by Dutch programmer Guido van Rossum, Python has enjoyed the backing of developers worldwide and is favoured among junior developers as one of the easiest programming languages to learn. Python is often referred to as a scripting language that prioritizes code readability. It lays emphasis on the use of whitespace as compared to other programming languages that employ compact, tiny source files. 

Among Python’s many popular products are Mozilla, Google, Cisco, NASA, and Instagram, among others. Not to mention, Python is a hugely popular extension for Microsoft’s Visual Studio Code.

Now, without further ado, let’s get started with our Python cheat sheet! We’ll begin with the basics.

Learn data science course from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

upGrad’s Exclusive Data Science Webinar for you –

ODE Thought Leadership Presentation

Operators in Python

1. Arithmetic Operators

There are seven maths operators in Python:

S.No

Maths Operators

Operation

Example

1

**

Exponent

2 ** 2 = 4

2

%

Modulus/Remainder

22 % 6 = 4

3

//

Integer division

22 // 8 = 2

4

/

Division

22 / 8 = 2.75

5

*

Multiplication

4 * 4 = 16

6

Subtraction

5 – 1 = 4

7

+

Addition

3 + 2 = 5

Here is a Python program using these operators: 

x = 10

y =5

# Output: x + y = 15

print(‘x + y =’,x+y)

# Output: x – y = 5

print(‘x – y =’,x-y)

# Output: x * y = 50

print(‘x * y =’,x*y)

# Output: x / y = 2

print(‘x / y =’,x/y)

# Output: x // y = 2

print(‘x // y =’,x//y)

Output:

x + y = 15

x – y = 5

x * y = 50

x / y = 2

x // y =32

2. Logical Operators

There are three logical operators: and, or, not

  1. and: Returns True if both operands are true — x and y
  2. or: Returns True if any one of the operands is true — x or y
  3. not: It checks if the operand is false and returns True — not x

Here is a program showing how logical operators are used in Python: 

x = True

y = False

print(‘The output of x and y is’,x and y)

print(‘The output of x or y is’,x or y)

print(‘The output of not x is’,not x)

Output

The output of x and y is False

The output of x or y is True

The output of not x is False

Explore our Popular Data Science Certifications

Our learners also read: Top Python Free Courses

3. Comparison Operators 

Python has 6 comparison operators:

1. Equals: a == b 

It checks whether the value on the left is equal to the value of the right.

2. Not Equals: a != b

It returns true if the value on the left is not equal to the value on the right.

3. Greater than: a > b

It returns true if the value on the left is greater than the value on the right.

4. Greater than or equal to: a >= b

It checks whether the value on the left is equal to the value on the right or greater than it. 

5. Less than: a < b

If the value on the left is less than the value on the right, the condition becomes true.

6. Less than or equal to: a <= b

It returns true when the value on the left is equal to the value on the right or less than it. 

Here is an example program:

x = 15

y = 12

z = 15

if ( x == z ):

   print “Output 1: x is equal to z”

else:

   print “Output 1: x is not equal to z”

if ( x != y ):

   print “Output 2: x is not equal to y”

else:

   print “Output 2: x is equal to y”

if ( x < y ):

   print “Output 3: x is less than y” 

else:

   print “Output: x is not less than y”

if ( x > y ):

   print “Output 4: x is greater than y”

else:

   print “Output 4: x is not greater than y”

x = 15;

y = 30;

if ( a <= b ):

   print “Output 5: x is less than or equal to y”

else:

   print “Output 5: x neither less than nor equal to y”

if ( x >= y ):

   print “Output 6: x is greater than or equal to y”

else:

   print “Output 6: x is neither greater than nor equal to y”

The result of the above program will be−

Output 1: x is equal to z

Output 2: x is not equal to y

Output 3: x is not less than y

Output 4: x is greater than y

Output 5: x neither less than nor equal to y

Output 6: x is neither greater than nor equal to y

Check out all trending Python tutorial concepts in 2024.

Control Statements in Python

1. If Statements

Python’s logical statements can be used with conditional operators or if statements and loops to accomplish decision-making. 

There are six conditional statements: If statement, if-else statement, nested if statement, If..elif ladder, short hand if statement, short hand if-else statement. These statements checked whether the given program is true or false. 

2. If 

These are used for simple conditions. Here is a short program for an if statement: 

if 10 == 1:

        print(“True!”)

Output:

True!

3. Nested If 

Here is a short program for nested if statements used to perform complex operations: 

x = 45

if x > 30:

  print(“The result is above thirty,”)

  if x > 35:

    print(“and also above thirty five!”)

Output

The result is above thirty

and also above thirty five!

We use indentation (or whitespace), an important functionality of Python used to separate blocks of code.

4. Elif Statements

elif keyword allows you to check more than another condition if the “if statement” was False. Here is a short program for an elif statement:

a = 99

b = 99

if b > a:

  print(“b is greater than a”)

elif a == b:

  print(“a and b are equal”)

Output:

a and b are equal

5. If Else Statements

If else statements allow adding more than one condition to a program. Take a look at this if-elif-else program:

if age < 5: 

entry_charge = 0 

elif age < 20: 

entry_charge = 10 

else: entry_charge = 20

6. If-Not-Statements

Not keyword lets you check for the opposite meaning to verify whether the value is NOT True:

new_list = [10, 20, 30, 40]

x = 50

if x not in new_list:

    print(“‘x’ is not included on the list, so the condition is True!”)

Output:

‘x’ is not included on the list, so the condition is True!

Loops

Python has 2 kinds of loops: For loop and While loop. 

1. For loop

It is used to execute the same sequence of statements n number of times. They are often used with lists. 

# Program to find the sum of all numbers stored in a list

# List containing numbers

numbers = [6, 5, 3, 18, 4, 2, 15, 4, 11]

# variable to store the sum

sum = 0

# run iterations on the list

for val in numbers:

    sum = sum+val

print(“The resultant sum is”, sum)

Output

The resultant sum is 68

2. While loop

It is used to repeat a statement if a given condition is found to be true. It is also applicable to a sequence of statements. In the while loop, the condition is tested first, which is then followed by the execution. 

# Program to compute the sum of natural numbers up to n

# sum = 1+2+3+…+n

# To get the value of n from the user,

n = int(input(“Enter the value of n: “))

# n = 5

# initialize sum and counter

sum = 0

i = 1

while i <= n:

    sum = sum + i

    i = i+1 # counter gets updated

# print the resultant sum

print(“The sum of the n naturals numbers is”, sum)

Output:

Enter the value of n: 5

The sum of the n naturals numbers is 15

Break and Continue Statements 

In Python, Break and continue are used in the modification of the flow of a running loop. If a programmer wishes to end a current loop without checking whether the test expression is true or false, we use break and continue statements. 

The break statement will immediately end the iteration running inside the loop it is included. In the case of a nested loop, the loop where the break is included is terminated. 

Here is an example for a break statement:

# Use of break statement inside the loop

for val in “character”:

    if val == “r”:

        break

    print(val)

print(“Program ends here”)

Output

c

h

a

r

Program ends here

The continue statement skips the remaining code in the iteration and continues to the next.

Here’s a program to for a continue statement: 

while True:

    print(‘What is your name?’)

    name = input()

    if name != ‘Maria’:

        continue

    print(‘Hi Maria. Enter your password. (It is an apple.)’)

    password = input()

    if password == ‘pineapple’:

        break

print(‘You’ve been granted access!’)

Pass Statements

A null statement is denoted as a pass statement in Python. As opposed to a comment, pass statements aren’t disregarded by Python. However, the execution of the statement still results in no operation (NOP).

Here’s an example for a pass statement:

”Time Is just a placeholder for

functionality that will be added later.”’

sequence = {‘t’, ‘i’, ‘m’, ‘e’}

for val in sequence:

    pass

Function in Python

Functions are designated to perform a specific task. They comprise blocks of code that can be reused throughout the program as needed. 

You can define your own function using the def keyword in Python. It is followed the name of the function and parentheses which take arguments: def name():

Here’s a short program to give you an idea:

def name():

    print(“How are you doing?”)

name.py

def name():

    print(“How are you doing?”)

name()

You can also add arguments to define the parameters of your function: 

def subtract_numbers(x, y, z):

    a = x – y

    b = x – z

    c = y – z

    print(a, b, c)

subtract_numbers(6, 5, 4)

Output:

1

2

1

Passing Keyword Arguments to a Function

Functions also allow you to pass keywords as arguments. Here’s a simple Python code to do so: 

# Define function with the following parameters

def item_info(item name, price):

    print(“itemname: ” + item name)

    print(“Price ” + str(dollars))

# Call the above function with assigned parameters 

item_info(“Blue T-shirt”, 25 dollars)

# Call function using keyword arguments

item_info(itemname=”Trousers”, price=95)

Output:

Productname: Blue T-shirt

Price: 25

Productname: Trousers

Price: 95

Top Data Science Skills to Learn

Collections in Python

Python has four collection data types: List, Tuple, Set, and Dictionary.

1. Lists

Lists are data types that represent a sequence of elements in Python. It is one of the most commonly used data structures. They keep relevant data combined and allow you to perform common operations on different values simultaneously. Lists are mutable containers whereas strings are not. 

Here is an example of lists: 

first_list = [1, 2, 3]

second_list = [“a”, “b”, “c”]

third_list = [“4”, d, “book”, 5]

Lists can also be as functions: 

master_list = list((“10”, “20”, “30”)) 

print(master_list)

2. Adding Items to a List

Here is a program for adding items to a list using append() function:

beta_list = [“eggs”, bacon”, “bread”]

beta_list.append(milk”)

print(beta_list)

Here is a program for adding items to a list using index() function:

beta_list = [“eggs”, bacon”, “bread”]

beta_list.insert(“2 mill”)

print(beta_list)

There are a number of actions you can perform on lists. These include adding items, removing items, combining items, creating nested lists, sorting, slicing, copying, etc. 

3. List concatenation

Here’s a program to show list concatenation in Python:

>>> [X, Y, Z] + [‘A’, ‘B’, ‘C’]

[X, Y, Z, ‘A’, ‘B’, ‘C’]

>>> [‘L’, ‘M’, ‘N’] * 3

[‘L’, ‘M’, ‘N’ ‘L’, ‘M’, ‘N’ ‘L’, ‘M’, ‘N’]

>>> list_spam = [1, 2, 3]

>>> list_spam = list_spam + [‘A’, ‘B’, ‘C’]

>>> list_spam

[1, 2, 3, ‘A’, ‘B’, ‘C’]

4. Changing list values

Here’s a program to change list values using indexes:

>>> list_spam = [‘cat’, ‘dog’, ‘rat’]

>>> list_spam[1] = ‘gadjlnhs’

>>> list_spam

[‘cat’, ‘gadjlnhs’, ‘rat’]

>>> list_spam[2] = list_spam[1]

>>> list_spam

[‘cat’, ‘gadjlnhs’, ‘gadjlnhs’]

Lists find extensive use when working with data cleaning and for-loopsHere’s a Python syntax cheat sheet for using lists for different purposes:

Dictionaries  

A Dictionary in Python is what enables element lookups. It is a commonly used data structure that leverages keys and values for indexing.

dict = {‘x’: 1, ‘y’: 2}

 There are key-value pairs wherein every key has a value. This is a type of data structure that is extremely valuable for data scientists and finds use in web scraping.

Here’s an example for for using Dictionaries in Python:

thisdict = {

  “brand”: “Skoda”,

  “model”: “Octavia”,

  “year”:”2017″

}

Tuple

If you need to store more than one item in a single variable, you can use Tuples. They are built-in data types that can be ordered or unchangeable. 

Here’s an example:

thistuple = (“mango”, “papaya”, “blueberry”)

print(thistuple)

You can also add the same value twice or more times. 

thistuple = (“mango”, “papaya”, “papaya”, “blueberry”)

print(thistuple)

Set 

Set is another data type collection in Python that stores a sequence of elements in a single variable. They are also both ordered and unchangeable. The difference between sets and tuples is that sets are written using curly brackets whereas tuples are written using round brackets. 

Another key differentiator is that sets do not accept duplicate elements.

this_set = (“mango”, 34, “papaya”, 40, “blueberry”)

print(this_set)

Here is an example for computing the difference of two sets:

X = {5, 6, 7, 8, 9}

Y = {8, 9, 10, 11, 12}

print(X-Y)

Output:

{5, 6, 7}

Here is an example for finding the interaction of two sets:

X = {5, 6, 7, 8, 9}

Y = {8, 9, 10, 11, 12}

print(A & B)

Output:

{8, 9}

Here’s listing a few methods that can be used with sets: 

Method

Description

add()

To add one or more elements to a set

clear()

To clear the set of elements

copy()

To create a copy

difference()

It computes the difference of multiple sets and returns a new set

difference_update()

Every element from another set is removed from the current set

discard()

If an element is a member of the set, the function removes it. If it’s not, it does nothing

intersection()

It computes the intersection of two sets and returns the result in a new set

isdisjoint()

If there are no common elements in two sets, it turns True

issubset()

If another is a subset of the current set, it returns True

issuperset()

Returns True if this set contains another set

remove()

If the element is present in the set, it removes it. If not, a KeyError is raised

union()

It computes the union of sets and returns the result in a new set

Types in Python

Strings

Strings, as the name suggests, is a sequence of characters. 

Some common methods used with respect to strings are lower(), upper(), lower(), replace(), count(), capitalize(), title().

String methods will return new values without modifying the original string. Anything that can be typed on the keyboard is a string — alphabet, number, special character. 

In Python, strings are enclosed within single and double quotes, both of which represent the ends of a string. 

Here is a Python strings cheat sheet:

Function

Description

str = str.strip()

To strip the string of all whitespace occurrences from either ends.

str = str.strip(‘chars’)

To strip all characters passed from either ends.

list = str.split()

To split any number of whitespaces.

str = str.join(coll_of_strings)

To join elements with a string acting as a separator.

bool = sub_str in str

To check whether or not a string contains a substring.

int = str.find(sub_str)

To return the initial index of the first match or return -1.

str = chr(int)

To convert the int value into a Unicode char.

int = ord(str)

To convert a unicode char into an int value

Regular Expressions (Regex)

A Regular Expression (RegEx) refers to a sequence of characters that points towards a search pattern in Python.

There’s a module in Python called re which is used with RegEx. Check out the example below:

import re

pattern = ‘*ma..er$’

test_str = ‘master’

result = re.match(pattern, test_str)

if result:

  print(“The match was successful.”)

else:

  print(“The match was unsuccessful.”)

Python has 14 metacharacters which are listed below:

\

Indicates a special meaning for the character that follows jt

[]

Character class

^

Matches with the beginning

$

Matches with the end

.

All characters except new line are matched

?

Matches zero. Also matches one occurrence

|

Represents OR. Any character separated by it is matched

*

Matches zero and any number of occurrences

{}

Points towards the number of occurrences that precede RE

()

Used to enclose more than one REs

Here is a Python RegEx cheat sheet for quick reference:

str = re.sub(regex, new, text, count=0)

Every occurrence is substituted with ‘new’.

list = re.findall(regex, text)

Every occurrence is converted into a string.

match = re.search(regex, text)

It goes through the regEx to look for the pattern’s first occurrence

match = re.match(regex, text)

Only the beginning of the text is searched

iter = re.finditer(regex, text)

All occurrences are returned as match objects.

Regex is commonly used by data scientists for data cleaning since it saves a lot of time.

Return Values and Return Statements in Python 

When you define a function using def, Python allows you to specify the return value using a return statement. The statements include the return keyword along with the return value that the function is supposed to return.

Here’s an example:

import random

def findAnswer(answerNo):

    if answerNo == 10:

        return ‘It is accurate’

    elif answerNo == 20:

        return ‘It is not certain’

    elif answerNo == 30:

        return ‘Successful’

    elif answerNo == 40:

        return ‘Try again later’

    elif answerNo == 50:

        return ‘Unsuccessful. Try again later’

    elif answerNo == 60:

        return ‘Still unsuccessful. Try again later’

    elif answerNo == 70:

        return ‘The answer is no’

    elif answerNo == 80:

        return ‘The reply does not look so good’

    elif answerNo == 90:

        return ‘It is doubtful’

r = random.randint(1, 9)

fortune = findAnswer(r)

print(fortune)

Exception Handling in Python

An event or occurrence that disrupts the program flow or deviates from the program’s instructions is an exception. Python raises an exception if it encounters an event that it is not capable of dealing with. It essentially refers to an error:

Here’s a program to demonstrate exception handling in Python:

>>> while True:

… try:

… x = int(input(“Enter the number: “))

… break

… except ValueError:

… print(“Incorrect entry. Try again.”

This brings us to the end of our Python syntax cheat sheet. Given Python’s growing applications in data science, it is clear that the language will continue to dominate the industry for years to come. Its low learning curve and unmatched flexibility and scalability make it one of the best programming languages to learn today. 

So if you’re interested in learning Python in-depth, join our Advanced Certificate Programme in Data Science now to build expertise in the domain and attract job opportunities from the top companies worldwide.

Read our popular Data Science Articles

Learn Python to Progress in the field of Data Science

Through the cutting-edge curriculum put together by upGrad and IIITB, students stand to gain industry-relevant skills and acquire knowledge of Statistics, Python Programming, Predictive Analytics using Python, Basic & Advanced SQL, Visualization using Python, EDA, and Basic & Advanced Machine Learning Algorithms. 

The program also includes a complimentary Python programming Bootcamp for you to enhance your skills through hands-on industry projects. upGrad’s industry mentorship and peer to peer networking opportunities can land you high-paying jobs as a Data Scientist, ML Engineer, Data Analyst, Product Analyst, Business Analyst, or Chief Architect — depending on your field of interest. 

So, don’t hesitate, kickstart your learning journey today! Let us know if you have any questions, we will be happy to help! 

Explain local and global variables in Python?

1. Local Variables: Variables that are defined or changed within a function are called local variables. The scope of these variables remains only within the function they are declared in and gets destroyed once the function ends.
2. Global Variables: Variables that are defined outside of a function or have a global scope are termed global variables. The scope of these variables remains throughout the program. The value of such a variable cannot be changed inside a function or else it will throw an error.

Which built-in data types are immutable in nature?

The immutable data types in Python include Number, Strings, and Tuple. The data stored in the variables of these types cannot be modified after declaration. The immutable nature makes the data more secure and provides ease to work with.
If you re-assign a new value to an immutable variable, then it allocates a separate space in the memory to store the new value. Hence, the original value of the immutable variable does get modified in any case.

Describe the major difference between list, tuple, set, and dictionary?

The following differentiates the Python collections based on the major parameters:
1. List -
a.The list is used to store ordered data
b. The data stored in a list can be mutated.
c. Lists can have duplicate elements.
2. Tuple -
a. A tuple is used to store ordered data.
b. The data stored in a tuple cannot be mutated.
c. Tuples can also contain duplicate elements.
3. Set -
a. Set is used to store unordered data.
b. Sets can be easily mutated.
c. A set can only contain unique data elements.
4. Dictionary
a. A dictionary is used to store unordered data.
b. The key-value pairs stored in a dictionary are mutable.
c. Dictionary elements should be unique as duplicates are not allowed.

Want to share this article?

Be a Certified Data Scientist - Data Science Certificate from IIIT Bangalore

Leave a comment

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

Our Popular Data Science Course

Get Free Consultation

Leave a comment

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

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks