DEV Community 👩‍💻👨‍💻

Cover image for Python Cheat Sheet for Beginners
Rohan Kiratsata
Rohan Kiratsata

Posted on

Python Cheat Sheet for Beginners

These cheatsheets are also available on my GitHub.
Improve this GitHub repository by contributing to it

Download PDF from here

This cheatsheet contains basic concepts of python, I will be uploading advanced concepts of python in Part 2.


Python Cheatsheet for Beginners

Table of Content

Basics

Arithmetic Operations

>>> 5 + 2   # Addition
7
Enter fullscreen mode Exit fullscreen mode
>>> 4 - 3   # Subtraction
1
Enter fullscreen mode Exit fullscreen mode
>>> 4 * 4   # Multiplication
16
Enter fullscreen mode Exit fullscreen mode
>>> 10 / 2  # Division
5.0         # Return float value

>>> 10 // 2 # Division, but return integer value
5
Enter fullscreen mode Exit fullscreen mode
>>> 10 % 2 # Modulas(Remainder)
0
Enter fullscreen mode Exit fullscreen mode
>>> 2 ** 3 # Exponenet(Power)
8
Enter fullscreen mode Exit fullscreen mode

Basic Data Types

Data Type Example
Integer -2,-1,0,1,2
Float -1.5, -1.92, 2.25, 16.4
String 'python','is','love'
Complex 1j, 1+2j
Boolean x = True, x = False

Taking User Input

input() function is used to take input from the user.

name = input("Enter Your Name:")
print("Hello " + name)
Enter fullscreen mode Exit fullscreen mode

Strings

Creating String

 myString = "Python is easy!"
Enter fullscreen mode Exit fullscreen mode

String Concatenation

A way to add two string together using "+" operator.

myString = "Python"
myString2 = "is easy"
ConString = myString + myString2
print(ConString)
Enter fullscreen mode Exit fullscreen mode

String Replication

string = "Python" * 5
print(string)
# OUTPUT: PythonPythonPythonPythonPython
Enter fullscreen mode Exit fullscreen mode

Lists

Lists are used to store the multiple items in a single variable. List are created using square brackets.
List elements are changeable, can allow duplicate elements, and has defined order and that order will not change.Any new element will be placed at end of list. List index will start from 0 and will end at n-1 (where n is number of elements).

Creating List

lst = ["python","cpp","java"]
Enter fullscreen mode Exit fullscreen mode

Fetching Values from List

>>> lst = ["python","cpp","java"]
>>> lst[0]
"python"
>>> lst[1]
"cpp"
>>> lst[2]
"java"
Enter fullscreen mode Exit fullscreen mode

Adding Items to List

lst = [1,2,3]
lst.append(4)
print(lst)
# OUTPUT : [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Method 2
insert() method is used to add item to specific index.

lst = [1,3,4]
# SYNTAX : .insert(index number, element)
lst.insert(1,2)
print(lst)
# OUTPUT : [1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

Removing Items from List

lst = [1,2,3,5]
lst.remove(5)
print(lst)
# OUTPUT : [1,2,3]
Enter fullscreen mode Exit fullscreen mode

Combine Two List

lst1 = [1,2,3]
lst2 = ["x","y","z"]

combineList = lst1 + lst2
print(combineList)
# OUTPUT: [1, 2, 3, "x", "y", "z"]
Enter fullscreen mode Exit fullscreen mode

Nested List

lst1 = [1,2,3]
lst2 = ["x","y","z"]
nestedList = [list1,list2]
print(nestedList)
# OUTPUT : [[1, 2, 3], ["x", "y", "z"]]
Enter fullscreen mode Exit fullscreen mode

Sorting List

lst = [123,51,214,23,56]
lst.sort()
print(lst)
#OUTPUT : [23, 51, 56, 123, 214]
Enter fullscreen mode Exit fullscreen mode

Copy a List

lst = ["a","b","c"]
lstcpy = lst.copy()
print(lstcpy)
# OUTPUT: ["a", "b", "c"]
Enter fullscreen mode Exit fullscreen mode

Tuples

Tuples are similar to list. However, they are immutable and you can't change the values stored in a tuple. Tuple are created using round brackets.

Creating Tuple

myTuple = (1,2,3,4)
print(myTuple)
Enter fullscreen mode Exit fullscreen mode

Access Tuple Items
You can access tuple items by referring to the index number.

myTuple = (1,2,3,4)
print(myTuple[2])
# OUTPUT: 3
Enter fullscreen mode Exit fullscreen mode

Convert Tuple to List

Since Tuples are immutable. Instead we can convert tuple to list and can edit and then convert it back to tuple.

myTuple = (1,2,3)
convertedTuple = list(myTuple)
# Now we can edit the "convertedTuple" list.
convertedTuple[0] = 120
# Converting back to Tuple.
myTuple = tuple(ConvertedTuple)
print(myTuple)
# OUTPUT: (120,2,3)
Enter fullscreen mode Exit fullscreen mode

Sets

Sets are used to store multiple items in a single variable.
A Set is a collection which is both unordered and unindexed.
Sets are written with curly brackets.
Set cannot have two items with same value.
A set can contain different data types.

Creating a Set

mySet = {"python", "java", "cpp"}
print(mySet)
Enter fullscreen mode Exit fullscreen mode

Set Operations

Set with Different Data Types

mySet = {"python",142,True,"abc"}
Enter fullscreen mode Exit fullscreen mode

Adding Element to Set

mySet = {1,2,3}
s.add(4)
print(s)
# OUTPUT: {1,2,3,4}
Enter fullscreen mode Exit fullscreen mode

Adding Multiple Elements to Set

mySet = {1,2,3}
mySet.update([4,5,6,7])
print(mySet)
# OUTPUT : {1,2,3,4,5,6,7}
Enter fullscreen mode Exit fullscreen mode

Dictionaries

Dictionaries are used to store data in pairs.
A Pair contains key and value.
It is ordered,changeable and cannot contain duplicate values. If duplicate values found then it will overwrite the values.

Creating Dictionaries

# SYNTAX

# dictionary_name = {
# "key_name" : "Value",
# "key2_name" : "Value2"
# }

dict = {
    "name" : "Van Rossum",
    "ID" : 1234,
    "year" : 1956
}
Enter fullscreen mode Exit fullscreen mode

Dictionary Operations

Printing Items

print(dict["name"])
Enter fullscreen mode Exit fullscreen mode

Length of Dictionary

print(len(dict))

# OUTPUT : 2
Enter fullscreen mode Exit fullscreen mode

Adding Items

dict = {
    "name" : "Van Rossum",
    "ID" : 1234,
    "year" : 1956
}
# Adding Item
dict["profession"] = "Programmer"
Enter fullscreen mode Exit fullscreen mode

Updating Item

# Syntax
# dict_name.update({"key":"value"})

dict.update({"ID":"9493"})
Enter fullscreen mode Exit fullscreen mode

Print All Items Values

for i in dict:
    print(dict[i])

# OUTPUT:
#   Van Rossum
#   9493
#   1956
Enter fullscreen mode Exit fullscreen mode

Conditional Statements

If Statement

If statement contains a logical expressions using which data is compared and a decision is made.

if expression:
    statements or code

Note : Indentation is required in IF statement
Enter fullscreen mode Exit fullscreen mode
# Let's a create a program to check if person is eligible to vote or not

age = 15

if age < 18: # If age is less than 18 execute the block
    print("Not Eligible to Vote")

if age >= 18: # If age is greater than or equal to 18 execute the block
    print("Eligible to Vote")

# Here age is 15 so, 1st condition will be true and print the message.
Enter fullscreen mode Exit fullscreen mode

Elif Statement

Elif keyword used if the previous if condition is false then it will execute the elif condition.

# Let's take the same example but using elif condition
age = 20

if age < 18:
    print("Not Eligible to Vote")

elif age >= 18:
    print("Eligible to Vote")

#OUTPUT: Eligible to Vote
Enter fullscreen mode Exit fullscreen mode

Else Statement

else keyword is used if all previous condition becomes false then it execute the else block.

# Let us Understand using example of "If Number is +ve or -ve."

n = 0

if n > 0:
    print("N is +ve")

elif n < 0:
    print("N is -ve")

# In this case both the 'if' condition is false so we use 'else' block
else:
    print("N is Zero")

# OUTPUT: N is Zero
Enter fullscreen mode Exit fullscreen mode

Loops

Loops are used when we want to execute same thing repeatedly until condition is not satisfied. For example, If we want to print "Hello World" 100 times, we will write print statement 100 times. We will use loop to achieve this.

While Loops

# print hello World 100 times

i = 1 
while i <= 100:
    print("Hello World")
    i=i+1
Enter fullscreen mode Exit fullscreen mode

For Loop

# Same example but using for loop

# for i in range(101)-> range function is used instead of "i<=100" from while loop
# Syntax for range() function -> range(n-1), So If n=100, range will only include 99.

for i in range(101):
    print("Hello World")

Enter fullscreen mode Exit fullscreen mode

Learn More about Range() Function Here


Functions

Functions are block of code which only runs when it is called. Functions are defined using def keyword.

Creating a Function

SYNTAX

def function_name():
    code inside function
Enter fullscreen mode Exit fullscreen mode
def my_function():
    print("Hello World")

Enter fullscreen mode Exit fullscreen mode

Calling Function

def greeting():
    print("Good Morning")

# Calling Of Function
greeting()
Enter fullscreen mode Exit fullscreen mode

Passing Arguments

# let us understand using example
# -> Take username and greet

# passing name argument
def greet(name):
    print("Hello " + name + ", Good Morning" )


greet("Rohan")

## Passing Two Arguments:

def greet(name, lastname):
    print("Hello " + name + lastname + ", Good Morning" )

greet("Rohan", "Kiratsata")
Enter fullscreen mode Exit fullscreen mode

Lambda Functions

A lambda function is a small anonymous function means function without name.

SYNTAX

lambda arguments: expression
Enter fullscreen mode Exit fullscreen mode
# Lambda function to square of number

n = lambda x : x*x

print(n(5))
Enter fullscreen mode Exit fullscreen mode

This cheatsheet is still in progress


Credits

This cheatsheet is written and managed by Rohan Kiratsata.

Something is missing? Contribute to this repo and improve.


Top comments (3)

Collapse
 
coderrudra profile image
Coder rudra

Nice

Collapse
 
lazydeveloper profile image
Shiva Inampudi

@rohankiratsata nice! 😃
I have added a little contribution to the repo.

Cheers!

Collapse
 
rohankiratsata profile image
Rohan Kiratsata Author

Thanks! I appreciate that. 😄

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.