Comprehensive Python Cheat Sheet for Beginners

16 minute one-stop tutorial for getting started with Python

Apr 10, 2020 · 16 min read

Types

String

`str1 = “I am a string” str2 = ‘I too am a string’ str3 = “” str4 = str1 + ‘ ‘ + str2`
`str5 = “Let’s say we need a single quote i.e. -> ‘ “ str6 = ‘What if we “need” a double quote i.e. -> “ ‘`
`str7 = “Let’s escape both single quote(\’) and double quote(\”)”`
`str8 = ‘’’Yet another way of escaping single (\’) and double (\”)’’’ str9 = “””Yet another way of escaping single (\’) and double (\”)”””`
`# Raw String str10 = R”Let’s escape both single quote(\’) and double quote(\”)”`

Indexing

`# Indexing String print(“str7[0] = “, str7[0]) print(“str7[1] = “, str7[1]) print(“str7[0:10] = “, str7[0:10]) print(“str7[10:5] = “, str7[10:5]) print(“str7[10:25] = “, str7[10:25])`

Type Conversion

`# Type Conversion (Initial Types Used)str1 = “15” in1 = 10 fl1 = 10.8`

Operators

Numerical Operations

`# Operators num1 = 10 num2 = 4 num3 = 5e2 num1 += 1 num1 *= 3 num1 /= 2`

Bitwise Operations

`# Bitwise Operations num4 = 12 num5 = 9 bool1 = True bool2 = False`

Data Structures

List Indexing and slicing

`# List Indexing l1 = [1,2,3,4,5,6,7,8,9,10]`

Tuple

`# Tuples tp1 = (“hello”, ) # Single length tuple tp2 = (1,2,3,[5,6]) # Tuple containing mutable types`
`# Immutability tp2[0] = 0`
`# Changing the mutable parts tp2[3][1] = 4`

Set

`# Sets set1 = {‘a’, ‘b’, ‘c’, ‘a’} set2 = {‘a’, ‘d’, ‘e’, ‘f’} set3 = {‘a’, ‘d’}`
`list1 = [‘a’,’b’, ‘a’, ‘a’] set1  = set(list1) #How to convert list to a set`

Dictionary

`# Dictionary dict1 = {‘a’: 12, ‘b’: 13, ‘c’:14, ‘d’:15} dict2 = {‘d’ : 16, ‘e’: 17} # Update old key and add new key dict1.update(dict2)`

Control Flow

For Loop

`str1 = “Hello World!” print(str1) for c in str1:   print(c)`

Break, Continue, Pass Statements

`fruits = [“apple”, “banana”, “cherry”, “dragonfruit”, “elephant”, “fig”] print(“Available Fruits = “, fruits) for fruit in fruits:  if(fruit == “elephant”):    print(“I cannot eat”, fruit)    break  else:    print(“I can eat”, fruit)`

While Loop

`# While Loop count = 0 while count < 5:   print(count)   count += 1`

Functions

Lambda Functions

`# Lambda Function x = lambda a : a/2`

File Handling

`# File Writingfilename = “test.txt” file_handle = open(filename, “w”) file_handle.write(“Yay!! File Created”)   # File Openingfile_handle = open(filename, “r”) print(file_handle.read())`

Pandas

`import numpy as np import pandas as pd house_data = pd.read_csv(“https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv", sep=”,”) print(house_data.head())`
`import matplotlib.pyplot as plt house_data[“median_income”].hist() plt.show()`

Written by

Written by