Python Cheetsheets
Python Cheetsheets
Cheat Sheet
Software
Programming
Code
Syntax
Similar to Grammar rules in English, Hindi, each programming language has a unique set of rules. These rules are
called the Syntax of a Programming Language.
Why Python
Python is an easy to learn, powerful programming language. With Python, it is possible to create programs with
minimal amount of code. Look at the code in Java and Python used for printing the message "Hello World"
Java:
JAVA
1 class Main {
2 public static void main(String[] args) {
3 System.out.println("Hello World");
4 }
5 }
Python:
PYTHON
1 print("Hello World")
Applications of Python
Career Opportunities
DevOps Engineer
Software Developer
Data Analyst
Data Scientist
Machine Learning (ML) Engineer
AI Scientist, etc.
Here is a simple Python code that you can use to display the message "Hello World"
Code
PYTHON
1 print("Hello World!")
Output
Hello World!
Possible Mistakes
Possible mistakes you may make while writing Python code to display the message "Hello World"
PYTHON
1 prnt("Hello World!")
PYTHON
1 Print("Hello World!")
Missing quotes
PYTHON
1 print(Hello World!)
Missing parentheses
PYTHON
1 print("Hello World!"
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=6bdf14a9-2664-4a96-9764-89d965de71a… 2/5
1/23/22, 8:51 PM Revolutionizing the Job Market | NxtWave
If we want to print the numerical result of 2 + 5, we do not add quotes.
Code
PYTHON
1 print(2 + 5)
Output
If we want to print the exact message "2 + 5", then we add the quotes.
Code
PYTHON
1 print("2 + 5")
Output
2 + 5
Addition
Addition is denoted by
Code
PYTHON
1 print(2 + 5)
2 print(1 + 1.5)
Output
7
2.5
Subtraction
Subtraction is denoted by
Code
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=6bdf14a9-2664-4a96-9764-89d965de71a… 3/5
1/23/22, 8:51 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 print(5 - 2)
Output
Multiplication
Multiplication is denoted by
* sign.
Code
PYTHON
1 print(2 * 5)
2 print(5 * 0.5)
Output
10
2.5
Division
Division is denoted by
/ sign.
Code
PYTHON
1 print(5 / 2)
2 print(4/2)
Output
2.5
2.0
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=6bdf14a9-2664-4a96-9764-89d965de71a… 4/5
1/23/22, 8:51 PM Revolutionizing the Job Market | NxtWave
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=6bdf14a9-2664-4a96-9764-89d965de71a… 5/5
1/23/22, 8:54 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Variables
Values
Data Type
In programming languages, every value or data has an associated type to it known as data type.
Some commonly used data types
String
Integer
Float
Boolean
This data type determines how the value or data can be used in the program. For example, mathematical
operations can be done on Integer and Float types of data.
String
Capital Letters ( A – Z )
Small Letters ( a – z )
Digits ( 0 – 9 )
Special Characters (~ ! @ # $ % ^ . ?,)
Space
Some Examples
"Hello World!"
"some@example.com"
"1234"
Integer
All whole numbers (positive, negative and zero) without any fractional part come under Integers.
Examples
Float
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=6bdf14a9-2664-4a96-9764-89d965de71a… 1/2
1/23/22, 8:54 PM Revolutionizing the Job Market | NxtWave
Boolean
In a general sense, anything that can take one of two possible values is considered a Boolean. Examples include
the data that can take values like
True or False
Yes or No
0 or 1
On or Off , etc.
True and False are considered as Boolean values. Notice that both start with a
capital letter.
10 to a variable age
PYTHON
1 age = 10
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=6bdf14a9-2664-4a96-9764-89d965de71a… 2/2
1/23/22, 8:54 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Sequence of Instructions
Program
A program is a sequence of instructions given to a computer.
Defining a Variable
A variable gets created when you assign a value to it for the first time.
Code
PYTHON
1 age = 10
Code
PYTHON
1 age = 10
2 print(age)
Output
10
Code
PYTHON
1 age = 10
2 print("age")
Output
age
Variable name enclosed in quotes will print variable rather than the value in it.
If you intend to print value, do not enclose the variable in quotes.
Order of Instructions
Code
PYTHON
1 i t( )
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=6bdf14a9-2664-4a96-9764-89d965de71a… 1/4
1/23/22, 8:54 PM Revolutionizing the Job Market | NxtWave
1 print(age)
2 age = 10
Output
Variable
Spacing in Python
Code
PYTHON
1 a = 10 * 5
2 b = 5 * 0.5
3 b = a + b
Output
Variable Assignment
Code
PYTHON
1 a = 1
2 print(a)
3 a = 2
4 print(a)
Output
1
2
Code
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=6bdf14a9-2664-4a96-9764-89d965de71a… 2/4
1/23/22, 8:54 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 a = 2
2 print(a)
3 a = a + 1
4 print(a)
Output
2
3
Code
PYTHON
1 a = 1
2 b = 2
3 a = b + 1
4 print(a)
5 print(b)
Output
3
2
Expression
Examples
a*b
a+2
5 2+3 4
BODMAS
The standard order of evaluating an expression
- Brackets (B)
- Orders (O)
- Division (D)
- Multiplication (M)
- Addition (A)
- Subtraction (S)
(5 * 2) + (3 * 4)
(10) + (12)
22
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=6bdf14a9-2664-4a96-9764-89d965de71a… 3/4
1/23/22, 8:54 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 print(10 / 2 + 3)
2 print(10 / (2 + 3))
Output
8.0
2.0
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=6bdf14a9-2664-4a96-9764-89d965de71a… 4/4
1/23/22, 8:56 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
input() allows flexibility to take the input from the user. Reads a line of input as a string.
Code
PYTHON
1 username = input()
2 print(username)
Input
Ajay
Output
Ajay
String Concatenation
Code
PYTHON
1 a = "Hello" + " " + "World"
2 print(a)
Output
Hello World
Concatenation Errors
Code
PYTHON
1 a = "*" + 10
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=56e26399-b147-4b8b-bb2c-d4f390c2a51… 1/4
1/23/22, 8:56 PM Revolutionizing the Job Market | NxtWave
2 print(a)
Output
String Repetition
Code
PYTHON
1 a = "*" * 10
2 print(a)
Output
**********
Code
PYTHON
1 s = "Python"
2 s = ("* " * 3) + s + (" *" * 3)
3 print(s)
Output
* * * Python * * *
Length of String
Code
PYTHON
1 username = input()
2 length = len(username)
3 print(length)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=56e26399-b147-4b8b-bb2c-d4f390c2a51… 2/4
1/23/22, 8:56 PM Revolutionizing the Job Market | NxtWave
Input
Ravi
Output
String Indexing
We can access an individual character in a string using their positions (which start from 0) .
These positions are also called as index.
Code
PYTHON
1 username = "Ravi"
2 first_letter = username[0]
3 print(first_letter)
Output
IndexError
Code
PYTHON
1 username = "Ravi"
2 print(username[4])
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=56e26399-b147-4b8b-bb2c-d4f390c2a51… 3/4
1/23/22, 8:56 PM Revolutionizing the Job Market | NxtWave
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=56e26399-b147-4b8b-bb2c-d4f390c2a51… 4/4
1/23/22, 8:57 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Type Conversion
String Slicing
Code
PYTHON
1 variable_name[start_index:end_index]
Code
PYTHON
1 message = "Hi Ravi"
2 part = message[3:7]
3 print(part)
Output
Ravi
Slicing to End
If end index is not specified, slicing stops at the end of the string.
Code
PYTHON
1 message = "Hi Ravi"
2 part = message[3:]
3 print(part)
Output
Ravi
Code
PYTHON
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=56e26399-b147-4b8b-bb2c-d4f390c2a51… 1/4
1/23/22, 8:57 PM Revolutionizing the Job Market | NxtWave
Output
Hi
type()
Code
PYTHON
1 print(type(10))
2 print(type(4.2))
3 print(type("Hi"))
Output
<class 'int'>
<class 'float'>
<class 'str'>
Type Conversion
Converting the value of one data type to another data type is called Type Conversion or Type Casting.
We can convert
String to Integer
Integer to Float
Float to String and so on.
String to Integer
Code
PYTHON
1 a = "5"
2 a = int(a)
3 print(type(a))
4 print(a)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=56e26399-b147-4b8b-bb2c-d4f390c2a51… 2/4
1/23/22, 8:57 PM Revolutionizing the Job Market | NxtWave
Output
<class 'int'>
5
Code
PYTHON
1 a = "Five"
2 a = int(a)
3 print(type(a))
Output
ValueError:
invalid literal for int() with base 10: 'Five'
Code
PYTHON
1 a = "5.0"
2 a = int(a)
3 print(type(a))
Output
Code
PYTHON
1 a = input()
2 a = int(a)
3 b = input()
4 b = int(b)
5 result = a + b
6 print(result)
Input
2
3
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=56e26399-b147-4b8b-bb2c-d4f390c2a51… 3/4
1/23/22, 8:57 PM Revolutionizing the Job Market | NxtWave
Output
Integer to String
Code
PYTHON
1 a = input()
2 a = int(a)
3 b = input()
4 b = int(b)
5 result = a + b
6 print("Sum: " + str(result))
Input
2
3
Output
Sum: 5
Summary
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=56e26399-b147-4b8b-bb2c-d4f390c2a51… 4/4
1/23/22, 8:59 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Relational Operators
Operator Name
== Is equal to
!= Is not equal to
Code
PYTHON
1 print(5 < 10)
2 print(2 > 1)
Output
True
True
Possible Mistakes
Mistake - 1
Code
PYTHON
1 print(3 = 3)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=36b50c7e-806a-4834-859f-1c031bdf9942… 1/3
1/23/22, 8:59 PM Revolutionizing the Job Market | NxtWave
Mistake - 2
Code
PYTHON
1 print(2 < = 3)
Output
Comparing Numbers
Code
PYTHON
1 print(2 <= 3)
2 print(2.53 >= 2.55)
Output
True
False
Code
PYTHON
1 print(12 == 12.0)
2 print(12 == 12.1)
Output
True
False
Comparing Strings
Code
PYTHON
1 print("ABC" == "ABC")
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=36b50c7e-806a-4834-859f-1c031bdf9942… 2/3
1/23/22, 8:59 PM Revolutionizing the Job Market | NxtWave
1 print( ABC ABC )
2 print("CBA" != "ABC")
Output
True
True
Case Sensitive
Code
PYTHON
1 print("ABC" == "abc")
Output
False
X (Capital letter) and x (small letter) are not the same in Python.
Code
PYTHON
1 print(True == "True")
2 print(123 == "123")
3 print(1.1 == "1.1")
Output
False
False
False
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=36b50c7e-806a-4834-859f-1c031bdf9942… 3/3
1/23/22, 8:59 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Logical Operators
The logical operators are used to perform logical operations on Boolean values.
Gives
and
or
not
Gives
Code
PYTHON
1 print(True and True)
Output
True
Code
PYTHON
1 print((2 < 3) and (1 < 2))
Output
True
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=36b50c7e-806a-4834-859f-1c031bdf9942… 1/3
1/23/22, 8:59 PM Revolutionizing the Job Market | NxtWave
Logical OR Operator
Gives
Code
PYTHON
1 print(False or False)
Output
False
Examples of Logical OR
Code
PYTHON
1 print((2 < 3) or (2 < 1))
(2 < 3) or (2 < 1)
True or (2 < 1)
True or False
Output
True
Code
PYTHON
1 print(not(False))
Output
True
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=36b50c7e-806a-4834-859f-1c031bdf9942… 2/3
1/23/22, 8:59 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 print(not(2 < 3))
not(2 < 3)
not(True)
False
Output
False
Summary
1. Logical AND Operator gives True if all the booleans are true.
2. Logical OR Operator gives True if any of the booleans are true.
3. Logical NOT Operator gives the opposite value
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=36b50c7e-806a-4834-859f-1c031bdf9942… 3/3
1/23/22, 9:00 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Conditional Statements
Block of Code
Condition
True or False
Examples
i. 2 < 3
ii. a == b
iii. True
Conditional Statement
Conditional Statement allows you to execute a block of code only when a specific condition is
True
Conditional Block
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=36b50c7e-806a-4834-859f-1c031bdf9942… 1/4
1/23/22, 9:00 PM Revolutionizing the Job Market | NxtWave
Indentation
Possible Mistakes
Each statement inside a conditional block should have the same indentation (spacing).
Wrong Code
PYTHON
1 if True:
2 print("If Block")
3 print("Inside If")
Output
Correct Code
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=36b50c7e-806a-4834-859f-1c031bdf9942… 2/4
1/23/22, 9:00 PM Revolutionizing the Job Market | NxtWave
PYTHON
1 if True:
2 print("If Block")
3 print("Inside If")
If - Else Syntax
When If - Else conditional statement is used, Else block of code executes if the condition is
False
Using If-Else
Code
PYTHON
1 a = int(input())
2 if a > 0:
3 print("Positive")
4 else:
5 print("Not Positive")
6 print("End")
Input
Output
Positive
End
Else can only be used along with if condition. It is written below if conditional block
Code
PYTHON
1 if False:
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=36b50c7e-806a-4834-859f-1c031bdf9942… 3/4
1/23/22, 9:00 PM Revolutionizing the Job Market | NxtWave
2 print("If Block")
3 print("After If")
4 else:
5 print("Else Block")
6 print("After Else")
Output
SingleLineWarning
Warning
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=36b50c7e-806a-4834-859f-1c031bdf9942… 4/4
1/23/22, 9:01 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Modulus
a%b
Code
PYTHON
1 print(6 % 3)
Output
Exponent
**
a ** b
Code
PYTHON
1 print(2 ** 3)
Output
You can use the exponent operator to calculate the square root of a number bu keeping the exponent as
0.5
Code
PYTHON
1 print(16 ** 0.5)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9b13ad84-b75c-4328-9cd3-0c6751ae6b4… 1/2
1/23/22, 9:01 PM Revolutionizing the Job Market | NxtWave
4.0
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9b13ad84-b75c-4328-9cd3-0c6751ae6b4… 2/2
1/23/22, 9:02 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Nested Conditions
The conditional block inside another if/else conditional block is called as nested conditional block.
In the below example, Block 2 is nested conditional block and condition B is called nested conditional statement.
Code
PYTHON
1 matches_won = int(input())
2 goals = int(input())
3 if matches_won > 8:
4 if goals > 20:
5 print("Hurray")
6 print("Winner")
Input
10
22
Output
Hurray
Winner
Input
10
18
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9b13ad84-b75c-4328-9cd3-0c6751ae6b4… 1/6
1/23/22, 9:02 PM Revolutionizing the Job Market | NxtWave
Output
Winner
Code
PYTHON
1 a = 2
2 b = 3
3 c = 1
4 is_a_greatest = (a > b) and (a > c)
5 if is_a_greatest:
6 print(a)
7 else:
8 is_b_greatest = (b > c)
9 if is_b_greatest:
10 print(b)
Expand
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9b13ad84-b75c-4328-9cd3-0c6751ae6b4… 2/6
1/23/22, 9:02 PM Revolutionizing the Job Market | NxtWave
Elif Statement
Use the elif statement to have multiple conditional statements between if and else.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9b13ad84-b75c-4328-9cd3-0c6751ae6b4… 3/6
1/23/22, 9:02 PM Revolutionizing the Job Market | NxtWave
Python will execute the elif block whose expression evaluates to true.
If multiple
elif conditions are true, then only the first elif block which is True will be executed.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9b13ad84-b75c-4328-9cd3-0c6751ae6b4… 4/6
1/23/22, 9:02 PM Revolutionizing the Job Market | NxtWave
if - elif statements.
Code
PYTHON
1 number = 5
2 is_divisible_by_10 = (number % 10 == 0)
3 is_divisible_by_5 = (number % 5 == 0)
4 if is_divisible_by_10:
5 print("Divisible by 10")
6 elif is_divisible_by_5:
7 print("Divisible by 5")
8 else:
9 print("Not Divisible by 10 or 5")
Output
Divisible by 5
Possible Mistake
else statement.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9b13ad84-b75c-4328-9cd3-0c6751ae6b4… 5/6
1/23/22, 9:02 PM Revolutionizing the Job Market | NxtWave
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9b13ad84-b75c-4328-9cd3-0c6751ae6b4… 6/6
1/23/22, 9:02 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Loops
So far we have seen that Python executes code in a sequence and each block of code is executed once.
Loops allow us to execute a block of code several times.
While Loop
True .
The following code snippet prints the next three consecutive numbers after a given number.
Code
PYTHON
1 a = int(input())
2 counter = 0
3 while counter < 3:
4 a = a + 1
5 print(a)
6 counter = counter + 1
Input
Output
5
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=88a029ac-5f25-41c7-8c30-57115bd29dc… 1/3
1/23/22, 9:02 PM Revolutionizing the Job Market | NxtWave
6
7
Possible Mistakes
1. Missing Initialization
Code
PYTHON
1 a = int(input())
2 while counter < 3:
3 a = a + 1
4 print(a)
5 counter = counter + 1
6 print("End")
Input
Output
Code
PYTHON
1 a = int(input())
2 counter = 0
3 condition = (counter < 3)
4 while condition:
5 a = a + 1
6 print(a)
7 counter = counter + 1
Input
10
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=88a029ac-5f25-41c7-8c30-57115bd29dc… 2/3
1/23/22, 9:02 PM Revolutionizing the Job Market | NxtWave
Infinite Loop
True .
Code
PYTHON
1 a = int(input())
2 counter = 0
3 while counter < 3:
4 a = a + 1
5 print(a)
6 print("End")
Input
10
Output
Infinite Loop
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=88a029ac-5f25-41c7-8c30-57115bd29dc… 3/3
1/23/22, 9:03 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
For Loop
Examples of sequences:
For Syntax
Code
PYTHON
1 word = "Python"
2 for each_char in word:
3 print(each_char)
Output
P
y
t
h
o
n
Range
Code
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=88a029ac-5f25-41c7-8c30-57115bd29dc… 1/2
1/23/22, 9:03 PM Revolutionizing the Job Market | NxtWave
PYTHON
1 for number in range(3):
2 print(number)
Output
0
1
2
start
Code
PYTHON
1 for number in range(5, 8):
2 print(number)
Output
5
6
7
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=88a029ac-5f25-41c7-8c30-57115bd29dc… 2/2
1/23/22, 9:04 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Extended Slicing
Syntax:
variable[start_index:end_index:step]
Code
PYTHON
1 a = "Waterfall"
2 part = a[1:6:3]
3 print(part)
Output
ar
Methods
String Methods
isdigit()
strip()
lower()
upper()
startswith()
d i h()
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=88a029ac-5f25-41c7-8c30-57115bd29dc… 1/5
1/23/22, 9:04 PM Revolutionizing the Job Market | NxtWave
endswith()
replace() and more...
Isdigit
Syntax:
str_var.isdigit()
Gives
Code
PYTHON
1 is_digit = "4748".isdigit()
2 print(is_digit)
Output
True
Strip
Syntax:
str_var.strip()
Code
PYTHON
1 mobile = " 9876543210 "
2 mobile = mobile.strip()
3 print(mobile)
Output
9876543210
Syntax:
str_var.strip(chars)
Code
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=88a029ac-5f25-41c7-8c30-57115bd29dc… 2/5
1/23/22, 9:04 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 name = "Ravi."
2 name = name.strip(".")
3 print(name)
Output
Ravi
Removes all spaces, comma(,) and full stop(.) that lead or trail the string.
Code
PYTHON
1 name = ", .. ,, ravi ,, .. ."
2 name = name.strip(" ,.")
3 print(name)
Output
ravi
Replace
Syntax:
str_var.replace(old,new)
Gives a new string after replacing all the occurrences of the old substring with the new substring.
Code
PYTHON
1 sentence = "teh cat and teh dog"
2 sentence = sentence.replace("teh","the")
3 print(sentence)
Output
Startswith
Syntax:
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=88a029ac-5f25-41c7-8c30-57115bd29dc… 3/5
1/23/22, 9:04 PM Revolutionizing the Job Market | NxtWave
Syntax:
str_var.startswith(value)
Gives
True if the string starts with the specified value. Otherwise, False
Code
PYTHON
1 url = "https://onthegomodel.com"
2 is_secure_url = url.startswith("https://")
3 print(is_secure_url)
Output
True
Endswith
Syntax:
str_var.endswith(value)
Gives
True if the string ends with the specified value. Otherwise, False
Code
PYTHON
1 gmail_id = "rahul123@gmail.com"
2 is_gmail = gmail_id.endswith("@gmail.com")
3 print(is_gmail)
Output
True
Upper
Syntax:
str_var.upper()
Gives a new string by converting each character of the given string to uppercase.
Code
PYTHON
" i"
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=88a029ac-5f25-41c7-8c30-57115bd29dc… 4/5
1/23/22, 9:04 PM Revolutionizing the Job Market | NxtWave
1 name = "ravi"
2 print(name.upper())
Output
RAVI
Lower
Syntax:
str_var.lower()
Gives a new string by converting each character of the given string to lowercase.
Code
PYTHON
1 name = "RAVI"
2 print(name.lower())
Output
ravi
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=88a029ac-5f25-41c7-8c30-57115bd29dc… 5/5
1/23/22, 9:05 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Nested Loops
An inner loop within the repeating block of an outer loop is called Nested Loop.
The Inner Loop will be executed one time for each iteration of the Outer Loop.
Code
PYTHON
1 for i in range(2):
2 print("Outer: " + str(i))
3 for j in range(2):
4 print(" Inner: " + str(j))
Output
Outer: 0
Inner: 0
Inner: 1
Outer: 1
Inner: 0
Inner: 1
The one highlighted in the blue dotted line is the repeating block of the inner loop.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=e322db60-81d5-42bc-910a-5c832956b5a… 1/3
1/23/22, 9:05 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 for i in range(2):
2 print("Outer: " + str(i))
3 for j in range(2):
4 print(" Inner: " + str(j))
5 print("END")
In the above example, the below line is the repeating block of the nested loop.
Code
PYTHON
1 print(" Inner: " + str(j))
Output
Outer: 0
Inner: 0
Inner: 1
Outer: 1
Inner: 0
Inner: 1
END
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=e322db60-81d5-42bc-910a-5c832956b5a… 2/3
1/23/22, 9:05 PM Revolutionizing the Job Market | NxtWave
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=e322db60-81d5-42bc-910a-5c832956b5a… 3/3
1/23/22, 9:05 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Examples
if-elif-else
while, for
break, continue
Break
Using Break
i value equals to 3 the break statement gets executed and stops the execution
of the loop further.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=e322db60-81d5-42bc-910a-5c832956b5a… 1/4
1/23/22, 9:05 PM Revolutionizing the Job Market | NxtWave
p
Code
PYTHON
1 for i in range(5):
2 if i == 3:
3 break
4 print(i)
5 print("END")
Output
0
1
2
END
Continue
Continue makes the program skip the remaining statements in the current iteration and begin the next iteration.
Using Continue
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=e322db60-81d5-42bc-910a-5c832956b5a… 2/4
1/23/22, 9:05 PM Revolutionizing the Job Market | NxtWave
Generally, continue is used to skip the remaining statements in the current iteration when a condition is satisfied.
i value equals to 3 the next statements in the loop body are skipped.
Code
PYTHON
1 for i in range(5):
2 if i == 3:
3 continue
4 print(i)
5 print("END")
Output
0
1
2
4
END
Pass
Generally used when we have to test the code before writing the complete code.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=e322db60-81d5-42bc-910a-5c832956b5a… 3/4
1/23/22, 9:05 PM Revolutionizing the Job Market | NxtWave
We can use pass statements to test code written so far, before writing loop logic.
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=e322db60-81d5-42bc-910a-5c832956b5a… 4/4
1/23/22, 9:06 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Comparing Strings
Ord
ord()
Code
PYTHON
1 unicode_value = ord("A")
2 print(unicode_value)
Output
65
chr
To find the character with the given Unicode value, we use the
chr()
Code
PYTHON
1 char = chr(75)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=1badf66e-560a-4c03-b772-7fd8151dcc59… 1/5
1/23/22, 9:06 PM Revolutionizing the Job Market | NxtWave
( )
2 print(char)
Output
Unicode Ranges
Printing Characters
A to Z
Code
PYTHON
1 for unicode_value in range(65,91):
2 print(chr(unicode_value))
Output
A
B
C
D
E
F
G
H
I
J
Expand
Comparing Strings
Code
PYTHON
1 print("A" < "B")
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=1badf66e-560a-4c03-b772-7fd8151dcc59… 2/5
1/23/22, 9:06 PM Revolutionizing the Job Market | NxtWave
Output
True
As unicode value of
Code
PYTHON
1 print("BAD" >= "BAT")
Output
False
Code
PYTHON
1 print("98" < "984")
Output
True
Best Practices
Naming Variables Rule #1
Capital Letters ( A – Z )
Small Letters ( a – z )
Digits ( 0 – 9 )
Underscore(_)
Examples:
age, total_bill
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=1badf66e-560a-4c03-b772-7fd8151dcc59… 3/5
1/23/22, 9:06 PM Revolutionizing the Job Market | NxtWave
Blanks ( )
Commas ( , )
Special Characters
( ~ ! @ # $ % ^ . ?, etc. )
Capital Letters ( A – Z )
Small Letters ( a – z )
Underscore( _ )
int
str
print etc.,
Keywords
Code
PYTHON
1 help("keywords")
Output
Here is a list of the Python keywords. Enter any keyword to get more help.
Case Styles
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=1badf66e-560a-4c03-b772-7fd8151dcc59… 4/5
1/23/22, 9:06 PM Revolutionizing the Job Market | NxtWave
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=1badf66e-560a-4c03-b772-7fd8151dcc59… 5/5
1/23/22, 9:07 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Round
Rounding Numbers
round(number, digits(optional)) Rounds the float value to the given number of decimal digits.
digits -> define the number of decimal digits to be considered for rounding.
Code
PYTHON
1 a = round(3.14,1)
2 print(a)
3 a = round(3.14)
4 print(a)
Output
3.1
3
Code
print(0.1 + 0.2)
Output
0.30000000000000004
Code
PYTHON
1 print((0.1 + 0.2) == 0.3)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=1badf66e-560a-4c03-b772-7fd8151dcc59… 1/2
1/23/22, 9:07 PM Revolutionizing the Job Market | NxtWave
False
round()
Code
PYTHON
1 a = round((0.1 + 0.2), 1)
2 print(a)
3 print(a == 0.3)
Output
0.3
True
Comments
Code
PYTHON
1 n = 5
2 # Finding if Even
3 even = (n % 2 == 0)
4 print(even) # prints boolean value
Output
False
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=1badf66e-560a-4c03-b772-7fd8151dcc59… 2/2
1/23/22, 9:08 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
//
a // b
Code
PYTHON
1 print(3 // 2)
Output
+= , -= , *= , /= , %=
a += 1 is similar to a=a+1
Code
PYTHON
1 a = 10
2 a -= 2
3 print(a)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=1badf66e-560a-4c03-b772-7fd8151dcc59… 1/4
1/23/22, 9:08 PM Revolutionizing the Job Market | NxtWave
8
Code
PYTHON
1 a = 10
2 a /= 2
3 print(a)
Output
5.0
Code
PYTHON
1 a = 10
2 a %= 2
3 print(a)
Output
Escape Characters
Code
PYTHON
1 sport = 'Cricket'
2 print(type(sport))
3 sport = "Cricket"
4 print(type(sport))
Output
<class 'str'>
<class 'str'>
Code
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=1badf66e-560a-4c03-b772-7fd8151dcc59… 2/4
1/23/22, 9:08 PM Revolutionizing the Job Market | NxtWave
PYTHON
1 is_same = ('Cricket' == "Cricket")
2 print(is_same)
Output
True
Escape Characters
Escape Characters are a sequence of characters in a string that are interpreted differently by the computer.
We use escape characters to insert characters that are illegal in a string.
Code
PYTHON
1 print("Hello\nWorld")
Output
Hello
World
\n escape character.
The backslash
\ character here tells Python not to consider the next character as the ending of the
string.
Code
PYTHON
1 print('It\'s Python')
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=1badf66e-560a-4c03-b772-7fd8151dcc59… 3/4
1/23/22, 9:08 PM Revolutionizing the Job Market | NxtWave
It's Python
Code
PYTHON
1 print("It's Python")
Output
It's Python
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=1badf66e-560a-4c03-b772-7fd8151dcc59… 4/4
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Data Structures
List
Tuple
Set
Dictionary
List
Creating a List
Code
PYTHON
1 a = 2
2 list_a = [5, "Six", a, 8.2]
3 print(type(list_a))
4 print(list_a)
Output
<class 'list'>
[5, 'Six', 2, 8.2]
Code
PYTHON
1 a = 2
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 1/6
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
1 a 2
2 list_a = [5, "Six", a, 8.2]
3 list_b = [1, list_a]
4 print(list_b)
Output
Length of a List
Code
PYTHON
1 a = 2
2 list_a = [5, "Six", a, 8.2]
3 print(len(list_a))
Output
Code
PYTHON
1 a = 2
2 list_a = [5, "Six", a, 8.2]
3 print(list_a[1])
Output
Six
Code
PYTHON
1 a = 2
2 list_a = [5, "Six", a, 8.2]
3 for item in list_a:
4 print(item)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 2/6
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
Output
5
Six
2
8.2
List Concatenation
Similar to strings,
Code
PYTHON
1 list_a = [1, 2, 3]
2 list_b = ["a", "b", "c"]
3 list_c = list_a + list_b
4 print(list_c)
Output
Code
PYTHON
1 list_a = []
2 print(list_a)
3 for i in range(1,4):
4 list_a += [i]
5 print(list_a)
Output
[]
[1, 2, 3]
Repetition
Code
PYTHON
1 list a = [1 2]
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 3/6
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
1 list_a = [1, 2]
2 list_b = list_a * 3
3 print(list_b)
Output
[1, 2, 1, 2, 1, 2]
List Slicing
Code
PYTHON
1 list_a = [5, "Six", 2, 8.2]
2 list_b = list_a[:2]
3 print(list_b)
Output
[5, 'Six']
Extended Slicing
Similar to string extended slicing, we can extract alternate items using step.
Code
PYTHON
1 list_a = ["R", "B", "G", "O", "W"]
2 list_b = list_a[0:5:3]
3 print(list_b)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 4/6
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
['R', 'O']
Converting to List
Code
PYTHON
1 color = "Red"
2 list_a = list(color)
3 print(list_a)
Output
Code
PYTHON
1 list_a = list(range(4))
2 print(list_a)
Output
[0, 1, 2, 3]
Code
PYTHON
1 list_a = [1, 2, 3, 5]
2 print(list_a)
3 list_a[3] = 4
4 print(list_a)
Output
[1, 2, 3, 5]
[1, 2, 3, 4]
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 5/6
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 message = "sea you soon"
2 message[2] = "e"
3 print(message)
Output
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 6/6
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Object
Examples
"A"
1.25
[1,2,3]
Identity of an Object
This unique id can be different for each time you run the program.
Every object that you use in a Python Program will be stored in Computer Memory.
The unique id will be related to the location where the object is stored in the Computer Memory.
Finding Id
Code
PYTHON
1 print(id("Hello"))
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 1/7
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
Output
140589419285168
Id of Lists
PYTHON
1 list_a = [1, 2, 3]
2 list_b = [1, 2, 3]
3 print(id(list_a))
4 print(id(list_b))
Output
139637858236800
139637857505984
Modifying Lists
Modifying Lists - 1
Code
PYTHON
1 list_a = [1, 2, 3]
2 list_b = list_a
3 print(id(list_a))
4 print(id(list_b))
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 2/7
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
Output
140334087715264
140334087715264
Modifying Lists - 2
Code
PYTHON
1 list_a = [1, 2, 3, 5]
2 list_b = list_a
3 list_b[3] = 4
4 print("list a : " + str(list_a))
5 print("list b : " + str(list_b))
Output
list a : [1, 2, 3, 4]
list b : [1, 2, 3, 4]
Modifying Lists - 3
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 3/7
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 list_a = [1, 2]
2 list_b = list_a
3 list_a = [6, 7]
4 print("list a : " + str(list_a))
5 print("list b : " + str(list_b))
Output
list a : [6, 7]
list b : [1, 2]
Modifying Lists - 4
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 4/7
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 list_a = [1, 2]
2 list_b = list_a
3 list_a = list_a + [6, 7]
4 print("list a : " + str(list_a))
5 print("list b : " + str(list_b))
Output
list a : [1, 2, 6, 7]
list b : [1, 2]
Modifying Lists - 5
Compound assignment will update the existing list instead of creating a new object.
Code
PYTHON
1 list_a = [1, 2]
2 list_b = list_a
3 list_a += [6, 7]
4 print("list a : " + str(list_a))
5 print("list b : " + str(list_b))
Output
list a : [1, 2, 6, 7]
list b : [1, 2, 6, 7]
Modifying Lists 6
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 5/7
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
Modifying Lists - 6
Updating mutable objects will also effect the values in the list, as the reference is changed.
Code
PYTHON
1 list_a = [1,2]
2 list_b = [3, list_a]
3 list_a[1] = 4
4 print(list_a)
5 print(list_b)
Output
[1, 4]
[3, [1, 4]]
Modifying Lists - 7
Updating immutable objects will not effect the values in the list, as the reference will be changed.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 6/7
1/23/22, 9:09 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 a = 2
2 list_a = [1,a]
3 print(list_a)
4 a = 3
5 print(list_a)
Output
[1, 2]
[1, 2]
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=61c4fcc8-aa24-4a69-bf08-554286988766… 7/7
1/23/22, 9:10 PM Revolutionizing the Job Market | NxtWave
str_var.split(separator)
Code
PYTHON
1 nums = "1 2 3 4"
2 num_list = nums.split()
3 print(num_list)
Output
Multiple WhiteSpaces
Code
PYTHON
1 nums = "1 2 3 4 "
2 num_list = nums.split()
3 print(num_list)
Output
New line
Code
PYTHON
1 nums = "1\n2\t3 4"
2 num_list = nums.split()
3 print(num_list)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 1/9
1/23/22, 9:10 PM Revolutionizing the Job Market | NxtWave
p
Using Separator
Example -1
Code
PYTHON
1 nums = "1,2,3,4"
2 num_list = nums.split(',')
3 print(num_list)
Output
Example -2
Code
PYTHON
1 nums = "1,2,,3,4,"
2 num_list = nums.split(',')
3 print(num_list)
Output
Space as Separator
Code
PYTHON
1 nums = "1 2 3 4 "
2 num_list = nums.split(" ")
3 print(num_list)
Output
String as Separator
Example - 1
Code
PYTHON
1 string_a = "Python is a programming language"
2 list_a = string_a.split('a')
3 print(list_a)
Output
Example - 2
PYTHON
1 string_a = "step-by-step execution of code"
2 list_a = string_a.split('step')
3 print(list_a)
Output
Joining
str.join(sequence)
Takes all the items in a sequence of strings and joins them into one string.
Code
PYTHON
1 list_a = ['Python is ', ' progr', 'mming l', 'ngu', 'ge']
2 string_a = "a".join(list_a)
3 print(string_a)
Output
Code
PYTHON
1 list_a = list(range(4))
2 string_a = ",".join(list_a)
3 print(string_a)
Output
Negative Indexing
Using a negative index returns the nth item from the end of list.
-1
Reversing a List
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 list_b = list_a[::-1]
3 print(list_b)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 4/9
1/23/22, 9:10 PM Revolutionizing the Job Market | NxtWave
Output
[1, 2, 3, 4, 5]
Example-1
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 item = list_a[-1]
3 print(item)
Output
Example-2
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 item = list_a[-4]
3 print(item)
Output
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 list_b = list_a[-3:-1]
3 print(list_b)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 5/9
1/23/22, 9:10 PM Revolutionizing the Job Market | NxtWave
[3, 2]
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 list_b = list_a[-6:-2]
3 print(list_b)
Output
[5, 4, 3]
variable[start:end:negative_step]
Negative Step determines the decrement between each index for slicing.
Start index should be greater than the end index in this case
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 6/9
1/23/22, 9:10 PM Revolutionizing the Job Market | NxtWave
Sta t de s ou d be g eate t a t e e d de t s case
Example - 1
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 list_b = list_a[4:2:-1]
3 print(list_b)
Output
[1, 2]
Example - 2
Code
PYTHON
1 list_a = [5, 4, 3, 2, 1]
2 list_b = list_a[2:4:-1]
3 print(list_b)
Output
[]
Reversing a List
Output
[1, 2, 3, 4, 5]
Reversing a String
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 7/9
1/23/22, 9:10 PM Revolutionizing the Job Market | NxtWave
Reversing a String
Code
PYTHON
1 string_1 = "Program"
2 string_2 = string_1[::-1]
3 print(string_2)
Output
margorP
Code
PYTHON
1 string_1 = "Program"
2 string_2 = string_1[6:0:-2]
3 print(string_2)
Output
mro
Example - 1
Code
PYTHON
1 string_1 = "Program"
2 string_2 = string_1[-1]
3 print(string_2)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 8/9
1/23/22, 9:10 PM Revolutionizing the Job Market | NxtWave
Example - 2
Code
PYTHON
1 string_1 = "Program"
2 string_2 = string_1[-4:-1]
3 print(string_2)
Output
gra
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 9/9
1/23/22, 9:11 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Functions
Reusing Code
Code
PYTHON
1 def greet():
2 print("Hello")
3
4 name = input()
5 print(name)
Input
Teja
Output
Teja
Defining a Function
function_name
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 1/7
1/23/22, 9:11 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 def greet():
2 print("Hello")
3
4 name = input()
5 print(name)
Input
Teja
Output
Teja
Calling a Function
The functional block of code is executed only when the function is called.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 2/7
1/23/22, 9:11 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 def greet():
2 print("Hello")
3
4 name = input()
5 greet()
6 print(name)
Input
Teja
Output
Hello
Teja
Code
PYTHON
1 name = input()
2 greet()
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 3/7
1/23/22, 9:11 PM Revolutionizing the Job Market | NxtWave
2 greet()
3 print(name)
4
5 def greet():
6 print("Hello")
Input
Teja
Output
Printing a Message
Consider the following scenario, we want to create a function, that prints a custom message, based on some variable
that is defined outside the function. In the below code snippet, we want to access the value in the variable
Code
PYTHON
1 def greet():
2 msg = "Hello " + ?
3 print(msg)
4
5 name = input()
6 greet()
Input
Teja
Desired Output
Hello Teja
Code
PYTHON
1 def greet(word):
2 msg = "Hello " + word
3 print(msg)
4
5 name = input()
6 greet(word=name)
Input
Teja
Output
Hello Teja
Code
PYTHON
1 def greet(word):
2 msg = "Hello " + word
3
4 name = input()
5 greet(word=name)
6 print(msg)
Input
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 5/7
1/23/22, 9:11 PM Revolutionizing the Job Market | NxtWave
Teja
Output
Returning a Value
return keyword.
Code
PYTHON
1 def greet(word):
2 msg = "Hello " + word
3 return msg
4
5 name = input()
6 greeting = greet(word=name)
7 print(greeting)
Input
Teja
Output
Hello Teja
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 6/7
1/23/22, 9:11 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 def greet(word):
2 msg = "Hello "+word
3 return msg
4 print(msg)
5
6 name = input()
7 greeting = greet(word=name)
8 print(greeting)
Input
Teja
Output
Hello Teja
Built-in Functions
print()
int()
str()
len()
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 7/7
1/23/22, 9:12 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Function Arguments
Keyword Arguments
Code
PYTHON
1 def greet(arg_1, arg_2):
2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(arg_1=greeting,arg_2=name)
Input
Good Morning
Ram
Output
Code
PYTHON
1 def greet(arg_1, arg_2):
2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 1/7
1/23/22, 9:12 PM Revolutionizing the Job Market | NxtWave
p ()
6 greet(arg_2=name)
Input
Good Morning
Ram
Output
Positional Arguments
Code
PYTHON
1 def greet(arg_1, arg_2):
2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(greeting,name)
Input
Good Morning
Ram
Output
Mistake - 1
Code
PYTHON
1 def greet(arg_1, arg_2):
2 print(arg_1 + " " + arg_2)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 2/7
1/23/22, 9:12 PM Revolutionizing the Job Market | NxtWave
3
4 greeting = input()
5 name = input()
6 greet(greeting)
Input
Good Morning
Ram
Output
Mistake - 2
Code
PYTHON
1 def greet(arg_1, arg_2):
2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet()
Input
Good Morning
Ram
Output
Default Values
Example - 1
Code
PYTHON
1 def greet(arg_1="Hi", arg_2="Ram"):
2 print(arg_1 + " " + arg_2)
3
4 ti i t()
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 3/7
1/23/22, 9:12 PM Revolutionizing the Job Market | NxtWave
4 greeting = input()
5 name = input()
6 greet()
Input
Hello
Teja
Output
Hi Ram
Example - 2
Code
PYTHON
1 def greet(arg_1="Hi", arg_2="Ram"):
2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(greeting)
Input
Hello
Teja
Output
Hello Ram
Example - 3
Code
PYTHON
1 def greet(arg_1="Hi", arg_2="Ram"):
2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(name)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 4/7
1/23/22, 9:12 PM Revolutionizing the Job Market | NxtWave
Input
Hello
Teja
Output
Teja Ram
Example - 4
Code
PYTHON
1 def greet(arg_1="Hi", arg_2="Ram"):
2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(arg_2=name)
Input
Hello
Teja
Output
Hi Teja
Example - 5
Code
PYTHON
1 def greet(arg_1="Hi", arg_2):
2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(arg_2=name)
Input
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 5/7
1/23/22, 9:12 PM Revolutionizing the Job Market | NxtWave
Hello
Teja
Output
Example - 6
Code
PYTHON
1 def greet(arg_2, arg_1="Hi"):
2 print(arg_1 + " " + arg_2)
3
4 greeting = input()
5 name = input()
6 greet(arg_2=name)
Input
Hello
Teja
Output
Hi Teja
Code
PYTHON
1 def increment(a):
2 a += 1
3
4 a = int(input())
5 increment(a)
6 print(a)
Input
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 6/7
1/23/22, 9:12 PM Revolutionizing the Job Market | NxtWave
Output
Even though variable names are same, they are referring to two different objects.
Changing the value of the variable inside the function will not affect the variable outside.
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ad7cec3e-761f-4e2a-b20a-9308829941c… 7/7
1/23/22, 9:14 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Code
PYTHON
1 def add_item(list_x):
2 list_x += [3]
3
4 list_a = [1,2]
5 add_item(list_a)
6 print(list_a)
Output
[1, 2, 3]
Code
PYTHON
1 def add_item(list_x):
2 list_x = list_x + [3]
3
4 list_a = [1,2]
5 add_item(list_a)
6 print(list_a)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 1/5
1/23/22, 9:14 PM Revolutionizing the Job Market | NxtWave
[1, 2]
Default args are evaluated only once when the function is defined, not each time the function is called.
Code
PYTHON
1 def add_item(list_x=[]):
2 list_x += [3]
3 print(list_x)
4
5 add_item()
6 add_item([1,2])
7 add_item()
Output
[3]
[1, 2, 3]
[3, 3]
Built-in functions
print()
int()
str()
len()
Finding Minimum
min() returns the smallest item in a sequence or smallest of two or more arguments.
PYTHON
1 min(sequence)
2 min(arg1, arg2, arg3 ...)
Example - 1
Code
PYTHON
1 smallest= min(3,5,4)
2 print(smallest)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 2/5
1/23/22, 9:14 PM Revolutionizing the Job Market | NxtWave
p
Example - 2
Code
smallest = min([1,-2,4,2])
print(smallest)
Output
-2
Minimum of Strings
min(str_1, str_2)
P - 80(unicode)
J - 74(unicode)
Code
PYTHON
1 smallest = min("Python", "Java")
2 print(smallest)
Output
Java
Finding Maximum
max() returns the largest item in a sequence or largest of two or more arguments.
PYTHON
1 max(sequence)
2 max(arg1, arg2, arg3 ...)
Example - 1
Code
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 3/5
1/23/22, 9:14 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 largest = max(3,5,4)
2 print(largest)
Ouput
Example - 2
Code
PYTHON
1 largest = max([1,-2,4,2])
2 print(largest)
Output
Finding Sum
Code
PYTHON
1 sum_of_numbers = sum([1,-2,4,2])
2 print(sum_of_numbers)
Output
sorted(sequence) returns a new sequence with all the items in the given sequence
ordered in increasing order.
Code
PYTHON
1 list_a = [3, 5, 2, 1, 4, 6]
2 list_x = sorted(list_a)
3 print(list x)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 4/5
1/23/22, 9:14 PM Revolutionizing the Job Market | NxtWave
3 print(list_x)
Output
[1, 2, 3, 4, 5, 6]
Code
PYTHON
1 list_a = [3, 5, 2, 1, 4, 6]
2 list_x = sorted(list_a, reverse=True)
3 print(list_x)
Output
[6, 5, 4, 3, 2, 1]
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 5/5
1/23/22, 9:15 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Calling a Function
Calling
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 1/5
1/23/22, 9:15 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 def get_largest_sqr(list_x):
2 len_list = len(list_x)
3 for i in range(len_list):
4 x = list_x[i]
5 list_x[i] = x * x
6 largest = max(list_x)
7 return largest
8
9 list_a = [1,-3,2]
10 result = get_largest_sqr(list_a)
Expand
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 2/5
1/23/22, 9:15 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 def get_sqrd_val(x):
2 return (x * x)
3
4 def get_sum_of_sqrs(list_a):
5 sqrs_sum = 0
6 for i in list_a:
7 sqrs_sum += get_sqrd_val(i)
8 return sqrs_sum
9
10 list_a = [1, 2, 3]
Expand
Output
14
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 3/5
1/23/22, 9:15 PM Revolutionizing the Job Market | NxtWave
Recursion
Multiply N Numbers
PYTHON
1 def factorial(n): # Recursive Function
2 if n == 1: # Base Case
3 return 1
4 return n * factorial(n - 1) # Recursion
5 num = int(input())
6 result = factorial(num)
7 print(result)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 4/5
1/23/22, 9:15 PM Revolutionizing the Job Market | NxtWave
Base Case
Input
Output
Code
PYTHON
1 def factorial(n):
2 return n * factorial(n - 1)
3 num = int(input())
4 result = factorial(num)
5 print(result)
Input
Output
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 5/5
1/23/22, 9:15 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
List Methods
append()
extend()
insert()
pop()
clear()
remove()
sort()
index()
Append
Code
PYTHON
1 list_a = []
2 for x in range(1,4):
3 list_a.append(x)
4 print(list_a)
Output
[1, 2, 3]
Extend
list_a.extend(list_b) Adds all the elements of a sequence to the end of the list.
Code
PYTHON
1 list_a = [1, 2, 3]
2 list_b = [4, 5, 6]
3 list_a.extend(list_b)
4 print(list_a)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 1/5
1/23/22, 9:15 PM Revolutionizing the Job Market | NxtWave
[1, 2, 3, 4, 5, 6]
Insert
Code
PYTHON
1 list_a = [1, 2, 3]
2 list_a.insert(1,4)
3 print(list_a)
Output
[1, 4, 2, 3]
Pop
Code
PYTHON
1 list_a = [1, 2, 3]
2 list_a.pop()
3 print(list_a)
Output
[1, 2]
Remove
Code
PYTHON
1 list_a = [1, 3, 2, 3]
2 list_a.remove(3)
3 print(list_a)
Output
[1, 2, 3]
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 2/5
1/23/22, 9:15 PM Revolutionizing the Job Market | NxtWave
Clear
Code
PYTHON
1 list_a = [1, 2, 3]
2 list_a.clear()
3 print(list_a)
Output
[]
Index
list.index(value) Returns the index at the first occurrence of the specified value.
Code
PYTHON
1 list_a = [1, 3, 2, 3]
2 index =list_a.index(3)
3 print(index)
Output
Count
Code
PYTHON
1 list_a = [1, 2, 3]
2 count = list_a.count(2)
3 print(count)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 3/5
1/23/22, 9:15 PM Revolutionizing the Job Market | NxtWave
Sort
Code
PYTHON
1 list_a = [1, 3, 2]
2 list_a.sort()
3 print(list_a)
Output
[1, 2, 3]
Code
PYTHON
1 list_a = [1, 3, 2]
2 list_a.sort()
3 print(list_a)
Output
[1, 2, 3]
Code
PYTHON
1 list_a = [1, 3, 2]
2 sorted(list_a)
3 print(list_a)
Output
[1, 3, 2]
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 4/5
1/23/22, 9:15 PM Revolutionizing the Job Market | NxtWave
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=23e2e09c-faf2-4563-b9b9-4a297bea7e2… 5/5
1/23/22, 9:16 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
None
Code
PYTHON
1 var = None
2 print(var)
3 print(type(var))
Output
None
<class 'NoneType'>
Code
PYTHON
1 def increment(a):
2 a += 1
3
4 a = 55
5 result = increment(a)
6 print(result)
Output
None
None
E l 1
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 1/8
1/23/22, 9:16 PM Revolutionizing the Job Market | NxtWave
Example - 1
Code
PYTHON
1 def increment(a):
2 a += 1
3 return
4
5 a = 55
6 result = increment(a)
7 print(result)
Output
None
Example - 2
Code
PYTHON
1 def increment(a):
2 a += 1
3 return None
4
5 a = 5
6 result = increment(a)
7 print(result)
Output
None
Example - 3
Code
PYTHON
1 result = print("Hi")
2 print(result)
Output
Hi
None
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 2/8
1/23/22, 9:16 PM Revolutionizing the Job Market | NxtWave
Tuple
Code
a = 2
tuple_a = (5, "Six", a, 8.2)
Creating a Tuple
Code
PYTHON
1 a = 2
2 tuple_a = (5, "Six", a, 8.2)
3 print(type(tuple_a))
4 print(tuple_a)
Output
<class 'tuple'>
(5, 'Six', 2, 8.2)
Code
PYTHON
1 a = (1,)
2 print(type(a))
3 print(a)
Output
<class 'tuple'>
(1,)
Accessing Tuple elements is also similar to string and list accessing and slicing.
Code
PYTHON
1 a = 2
2 tuple_a = (5, "Six", a, 8.2)
3 print(tuple a[1])
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 3/8
1/23/22, 9:16 PM Revolutionizing the Job Market | NxtWave
3 print(tuple_a[1])
Output
Six
Code
PYTHON
1 tuple_a = (1, 2, 3, 5)
2 tuple_a[3] = 4
3 print(tuple_a)
Output
len()
Iterating
Slicing
Extended Slicing
Converting to Tuple
String to Tuple
Code
PYTHON
1 color = "Red"
2 tuple_a = tuple(color)
3 print(tuple_a)
Output
List to Tuple
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 4/8
1/23/22, 9:16 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 list_a = [1, 2, 3]
2 tuple_a = tuple(list_a)
3 print(tuple_a)
Output
(1, 2, 3)
Sequence to Tuple
Code
PYTHON
1 tuple_a = tuple(range(4))
2 print(tuple_a)
Output
(0, 1, 2, 3)
Membership Check
Membership Operators
in
not in
Example - 1
Code
PYTHON
1 tuple_a = (1, 2, 3, 4)
2 is_part = 5 in tuple_a
3 print(is_part)
Output
False
Example - 2
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 5/8
1/23/22, 9:16 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 tuple_a = (1, 2, 3, 4)
2 is_part = 1 not in tuple_a
3 print(is_part)
Output
False
List Membership
Code
PYTHON
1 list_a = [1, 2, 3, 4]
2 is_part = 1 in list_a
3 print(is_part)
Output
True
String Membership
Code
PYTHON
1 word = 'Python'
2 is_part = 'th' in word
3 print(is_part)
Output
True
Code
PYTHON
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 6/8
1/23/22, 9:16 PM Revolutionizing the Job Market | NxtWave
PYTHON
1 tuple_a = ('R', 'e', 'd')
2 (s_1, s_2, s_3) = tuple_a
3 print(s_1)
4 print(s_2)
5 print(s_3)
Output
R
e
d
Errors in Packing
Code
PYTHON
1 tuple_a = ('R', 'e', 'd')
2 s_1, s_2 = tuple_a
3 print(s_1)
4 print(s_2)
Output
Code
PYTHON
1 tuple_a = ('R', 'e', 'd')
2 s_1, s_2, s_3, s_4 = tuple_a
3 print(s_1)
Output
Tuple Packing
Code
PYTHON
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 7/8
1/23/22, 9:16 PM Revolutionizing the Job Market | NxtWave
1 a = 1, 2, 3
2 print(type(a))
3 print(a)
Output
<class 'tuple'>
(1, 2, 3)
Code
PYTHON
1 a = 1,
2 print(type(a))
3 print(a)
Output
<class 'tuple'>
(1,)
Code
PYTHON
1 a, = 1,
2 print(type(a))
3 print(a)
Output
<class 'int'>
1
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 8/8
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Sets
Creating a Set
Code
PYTHON
1 a = 2
2 set_a = {5, "Six", a, 8.2}
3 print(type(set_a))
4 print(set_a)
Output
<class 'set'>
{8.2, 2, 'Six', 5}
No Duplicate Items
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 1/5
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 set_a = {"a", "b", "c", "a"}
2 print(set_a)
Output
Immutable Items
Code
PYTHON
1 set_a = {"a", ["c", "a"]}
2 print(set_a)
Output
We use
Code
PYTHON
1 set_a = set()
2 print(type(set_a))
3 print(set_a)
Output
<class 'set'>
set()
Converting to Set
List to Set
Code
PYTHON
1 set_a = set([1,2,1])
2 print(type(set_a))
3 print(set_a)
Output
<class 'set'>
{1, 2}
String to Set
Code
PYTHON
1 set_a = set("apple")
2 print(set_a)
Output
Tuple to Set
Code
PYTHON
1 set_a = set((1, 2, 1))
2 print(set_a)
Output
{1, 2}
Accessing Items
Indexing
Slicing
Code
PYTHON
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 3/5
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
1 set_a = {1, 2, 3}
2 print(set_a[1])
3 print(set_a[1:3])
Output
Adding Items
set.add(value) adds the item to the set, if the item is not present already.
Code
PYTHON
1 set_a = {1, 3, 6, 2, 9}
2 set_a.add(7)
3 print(set_a)
Output
{1, 2, 3, 6, 7, 9}
set.update(sequence) adds multiple items to the set, and duplicates are avoided.
Code
PYTHON
1 set_a = {1, 3, 9}
2 set_a.update([2, 3])
3 print(set_a)
Output
{2, 1, 3, 9}
Code
PYTHON
1 set_a = {1, 3, 9}
2 set_a.discard(3)
3 print(set_a)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 4/5
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
Output
{1, 9}
Code
PYTHON
1 set_a = {1, 3, 9}
2 set_a.remove(5)
3 print(set_a)
Output
KeyError: 5
Operations on Sets
clear()
len()
Iterating
Membership Check
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 5/5
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Set Operations
Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Union
Code
PYTHON
1 set_a = {4, 2, 8}
2 set_b = {1, 2}
3 union = set_a | set_b
4 print(union)
Output
{1, 2, 4, 8}
Code
PYTHON
1 set_a = {4, 2, 8}
2 list_a = [1, 2]
3 union = set_a.union(list_a)
4 print(union)
Output
{1, 2, 4, 8}
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 1/9
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
Intersection
Intersection of two sets is a set containing common elements of both sets.
Code
PYTHON
1 set_a = {4, 2, 8}
2 set_b = {1, 2}
3 intersection = set_a & set_b
4 print(intersection)
Output
{2}
Code
PYTHON
1 set_a = {4, 2, 8}
2 list_a = [1, 2]
3 intersection = set_a.intersection(list_a)
4 print(intersection)
Output
{2}
Difference
Difference of two sets is a set containing all the elements in the first set but not second.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 2/9
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 set_a = {4, 2, 8}
2 set_b = {1, 2}
3 diff = set_a - set_b
4 print(diff)
Output
{8, 4}
Code
PYTHON
1 set_a = {4, 2, 8}
2 tuple_a = (1, 2)
3 diff = set_a.difference(tuple_a)
4 print(diff)
Output
{8, 4}
Symmetric Difference
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 3/9
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
Symmetric difference of two sets is a set containing all elements which are not common to both sets.
Code
PYTHON
1 set_a = {4, 2, 8}
2 set_b = {1, 2}
3 symmetric_diff = set_a ^ set_b
4 print(symmetric_diff)
Output
{8, 1, 4}
Code
PYTHON
1 set_a = {4, 2, 8}
2 set_b = {1, 2}
3 diff = set_a.symmetric_difference(set_b)
4 print(diff)
Output
{8, 1, 4}
Set Comparisons
Set comparisons are used to validate whether one set fully exists within another
issubset()
issuperset()
isdisjoint()
Subset
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 4/9
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
set2.issubset(set1) Returns True if all elements of second set are in first set. Else, False
Example - 1
Code
PYTHON
1 set_1 = {'a', 1, 3, 5}
2 set_2 = {'a', 1}
3 is_subset = set_2.issubset(set_1)
4 print(is_subset)
Output
T
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 5/9
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
True
Example - 2
Code
PYTHON
1 set_1 = {4, 6}
2 set_2 = {2, 6}
3 is_subset = set_2.issubset(set_1)
4 print(is_subset)
Output
False
SuperSet
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 6/9
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
set1.issuperset(set2) Returns True if all elements of second set are in first set. Else, False
Example - 1
Code
PYTHON
1 set_1 = {'a', 1, 3, 5}
2 set_2 = {'a', 1}
3 is_superset = set_1.issuperset(set_2)
4 print(is_superset)
Output
True
Example - 2
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 7/9
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 set_1 = {4, 6}
2 set_2 = {2, 6}
3 is_superset = set_1.issuperset(set_2)
4 print(is_superset)
Output
False
Disjoint Sets
set1.isdisjoint(set2) Returns True when they have no common elements. Else, False
Code
PYTHON
1 set_a = {1, 2}
2 set_b = {3, 4}
3 is_disjoint = set_a.isdisjoint(set_b)
4 print(is_disjoint)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 8/9
1/23/22, 9:17 PM Revolutionizing the Job Market | NxtWave
True
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=9d7b8f7a-5ee1-4126-b032-b2b8f57b775… 9/9
1/23/22, 9:21 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Code
PYTHON
1 list_a = [5, "Six", [8, 6], 8.2]
2 print(list_a[2])
Output
[8, 6]
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc01996… 1/4
1/23/22, 9:21 PM Revolutionizing the Job Market | NxtWave
Example - 1
Code
PYTHON
1 list_a = [5, "Six", [8, 6], 8.2]
2 print(list_a[2][0])
Output
Example - 2
Code
PYTHON
1 list_a = ["Five", "Six"]
2 print(list_a[0][1])
Output
String Formatting
Code
PYTHON
1 name = input()
2 age = int(input())
3 msg = ("Hi " + name + ". You are "+ str(age) + " years old.")
4 print(msg)
Add Placeholders
Add placeholders
{}
Code
PYTHON
1 name = "Raju"
2 age = 10
3 msg = "Hi {}. You are {} years old."
4 print(msg.format(name, age))
Output
Number of Placeholders
Code
PYTHON
1 name = "Raju"
2 age = 10
3 msg = "Hi {}. You are {} years old {}."
4 print(msg.format(name, age))
Output
Numbering Placeholders
Code
PYTHON
1 name = input()
2 age = int(input())
3 msg = "Hi {0}. You are {1} years old."
4 print(msg.format(name, age))
Output
i j ld
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc01996… 3/4
1/23/22, 9:21 PM Revolutionizing the Job Market | NxtWave
Hi Raju. You are 10 years old.
Code
PYTHON
1 name = input()
2 age = int(input())
3 msg = "Hi {1}. You are {0} years old."
4 print(msg.format(name, age))
Output
Naming Placeholder
Code
PYTHON
1 name = input()
2 age = int(input())
3 msg = "Hi {name}. You are {age} years old."
4 print(msg.format(name=name, age=age))
Output
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc01996… 4/4
1/23/22, 9:22 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Dictionaries
Creating a Dictionary
Code
PYTHON
1 dict_a = {
2 "name": "Teja",
3 "age": 15
4 }
Code
PYTHON
1 dict_a = {
2 "name": "Teja",
3 "age": 15
4 }
Code
PYTHON
1 dict_a = { "name": "Teja",
2 "age": 15 }
3 print(type(dict_a))
4 print(dict_a)
Output
<class 'dict'>
{'name': 'Teja','age': 15}
Immutable Keys
Code
PYTHON
1 dict_a = {
2 "name": "Teja",
3 "age": 15,
4 "roll_no": 15
5 }
Code - 1
PYTHON
1 dict_a = dict()
2 print(type(dict_a))
3 print(dict_a)
Output
<class 'dict'>
{}
Code - 2
PYTHON
1 dict a {}
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc0199… 2/11
1/23/22, 9:22 PM Revolutionizing the Job Market | NxtWave
1 dict_a = {}
2 print(type(dict_a))
3 print(dict_a)
Output
<class 'dict'>
{}
Accessing Items
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a['name'])
Output
Teja
The
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a.get('name'))
Output
Teja
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc0199… 3/11
1/23/22, 9:22 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a.get('city'))
Output
None
KeyError
[] to access the key-value, KeyError is raised in case a key is not found in the
dictionary.
Code
PYTHON
1 dict_a = {'name': 'Teja','age': 15 }
2 print(dict_a['city'])
Output
KeyError: 'city'
Quick Tip
If we use the square brackets [] , KeyError is raised in case a key is not found in the dictionary. On the
other hand, the get() method returns None if the key is not found.
Membership Check
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 result = 'name' in dict_a
6 print(result)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc0199… 4/11
1/23/22, 9:22 PM Revolutionizing the Job Market | NxtWave
p ( )
Output
True
Operations on Dictionaries
Code
PYTHON
1 dict_a = {'name': 'Teja','age': 15 }
2 dict_a['city'] = 'Goa'
3 print(dict_a)
Output
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 dict_a['age'] = 24
6 print(dict_a)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc0199… 5/11
1/23/22, 9:22 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 del dict_a['age']
6 print(dict_a)
Output
{'name': 'Teja'}
Dictionary Views
They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view
reflects these changes.
Dictionary Methods
dict.keys()
returns dictionary Keys
dict.values()
returns dictionary Values
dict.items()
returns dictionary items(key-value) pairs
Getting Keys
The
keys() method returns a view object of the type dict_keys that holds a list of all keys.
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a.keys())
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc0199… 6/11
1/23/22, 9:22 PM Revolutionizing the Job Market | NxtWave
Output
dict_keys(['name', 'age'])
Getting Values
The
values()method returns a view object that displays a list of all the values in the
dictionary.
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a.values())
Output
dict_values(['Teja', 15])
Getting Items
The
items()method returns a view object that displays a list of dictionary's (key, value)
tuple pairs.
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(dict_a.items())
Output
Example - 1
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 for key in dict_a.keys():
6 print(key)
Output
name
age
Example - 2
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 keys_list = list(dict_a.keys())
6 print(keys_list)
Output
['name', 'age']
Example - 3
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 for value in dict_a.values():
6 print(value)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc0199… 8/11
1/23/22, 9:22 PM Revolutionizing the Job Market | NxtWave
Teja
15
Example - 4
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 for key, value in dict_a.items():
6 pair = "{} {}".format(key,value)
7 print(pair)
Output
name Teja
age 15
keys(), values() & items() are called Dictionary Views as they provide a dynamic
view on the dictionary’s items.
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 view = dict_a.keys()
6 print(view)
7 dict_a['roll_no'] = 10
8 print(view)
Output
dict_keys(['name', 'age'])
dict_keys(['name', 'age', 'roll_no'])
Converting to Dictionary
Code
PYTHON
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc0199… 9/11
1/23/22, 9:22 PM Revolutionizing the Job Market | NxtWave
PYTHON
1 list_a = [
2 ("name","Teja"),
3 ["age",15],
4 ("roll_no",15)
5 ]
6 dict_a = dict(list_a)
7 print(dict_a)
Output
Code
PYTHON
1 list_a = ["name", "Teja", 15]
2 dict_a = dict(list_a)
3 print(dict_a)
Output
Type of Keys
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc019… 10/11
1/23/22, 9:22 PM Revolutionizing the Job Market | NxtWave
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc019… 11/11
1/23/22, 9:24 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Dictionary Methods
copy()
get()
update()
fromkeys() and more..
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 dict_b = dict_a
6 dict_b['age'] = 20
7 print(dict_a)
8 print(id(dict_a))
9 print(id(dict_b))
Output
Copy of Dictionary
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 dict_b = dict_a.copy()
6 dict_b['age'] = 20
7 print(dict_a)
8 print(id(dict_a))
9 print(id(dict b))
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc01996… 1/6
1/23/22, 9:24 PM Revolutionizing the Job Market | NxtWave
9 print(id(dict_b))
Output
Copy of List
Code
PYTHON
1 list_a = ['Teja', 15]
2 list_b = list_a.copy()
3 list_b.extend([20])
4 print(list_a)
5 print(id(list_a))
6 print(id(list_b))
Output
['Teja', 15]
139631861316032
139631860589504
Operations on Dictionaries
len()
clear()
Membership Check
Code
PYTHON
1 dict_a = {
2 'name': 'Teja',
3 'age': 15
4 }
5 print(len(dict_a)) # length of dict_a
6 if 'name' in dict_a: # Membership Check
7 print("True")
8 dict_a.clear() # clearing dict_a
9 print(dict_a)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc01996… 2/6
1/23/22, 9:24 PM Revolutionizing the Job Market | NxtWave
True
{}
Iterating
Code
PYTHON
1 dict_a = {'name': 'Teja', 'age': 15}
2 for k in dict_a.keys():
3 if k == 'name':
4 del dict_a[k]
5 print(dict_a)
Output
max(*args) max(1,2,3..)
min(*args) min(1,2,3..)
Code
PYTHON
1 def more_args(*args):
2 print(args)
3
4 more_args(1, 2, 3, 4)
5 more_args()
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc01996… 3/6
1/23/22, 9:24 PM Revolutionizing the Job Market | NxtWave
Output
(1, 2, 3, 4)
()
Unpacking as Arguments
unpack it with
* while passing.
Code
PYTHON
1 def greet(arg1="Hi", arg2="Ram"):
2 print(arg1 + " " + arg2)
3
4 data = ["Hello", "Teja"]
5 greet(*data)
Output
Hello Teja
Code
PYTHON
1 def more_args(**kwargs):
i (k )
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc01996… 4/6
1/23/22, 9:24 PM Revolutionizing the Job Market | NxtWave
2 print(kwargs)
3
4 more_args(a=1, b=2)
5 more_args()
Output
{'a': 1, 'b': 2}
{}
Iterating
kwargs is a dictionary. We can iterate over them like any other dictionary.
Code
PYTHON
1 def more_args(**kwargs):
2 for i, j in kwargs.items():
3 print('{}:{}'.format(i,j))
4
5 more_args(a=1, b=2)
Output
a:1
b:2
Unpacking as Arguments
Code - 1
PYTHON
1 def greet(arg1="Hi", arg2="Ram"):
2 print(arg1 + " " + arg2)
3
4 data = {'arg1':'Hello', 'arg2':'Teja'}
5 greet(**data)
Output
Hello Teja
Code - 2
PYTHON
1 def greet(arg1="Hi", arg2="Ram"):
2 print(arg1 + " " + arg2)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc01996… 5/6
1/23/22, 9:24 PM Revolutionizing the Job Market | NxtWave
3
4 data = {'msg':'Hello', 'name':'Teja'}
5 greet(**data)
Output
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=ed539263-1317-4e4c-ab36-9b10bc01996… 6/6
1/23/22, 9:25 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Introduction to OOP
Good Software
Before jumping into Object Oriented Programming, let’s understand the word Software.
The ease of changing or making changes to the software is referred as its softness.
A good software should keep the users happy, by delivering what they need.
A good software should also keep the developers happy. Ease of making changes (softness) keeps developers
happy. So is should be:
Easy to understand and make changes.
Easy to fix bugs and add new features within the scope.
Object-Oriented Programming System (OOPS) is a way of approaching, designing, developing software that is easy to
change.
Note
Keep in mind that building software differs from solving the coding questions (that you are doing in practice).
A fundamental difference is that you move on to the next problem once you solve a coding problem. But with
software, once you build it, you are often required to add new features and fix bugs that need you to make
changes to the code written by you or your colleagues. So unlike the coding questions, with software, you have
to keep working with the same code for a long time.
Therefore, ease of understanding (code-readability) and ease of making changes (code-maintainability) to the
code become crucial in software development.
The techniques and concepts you learn in this topic are developed over time based on software developers'
experiences to make working code easier.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 1/3
1/23/22, 9:25 PM Revolutionizing the Job Market | NxtWave
OOPs
Object-Oriented Programming is a way of approaching, designing and developing software, so that the components
of the software and the interactions between them resembles real-life objects and their interactions.
Proper usage of OOPS concepts helps us build well-organized systems that are easy to use and extend.
In Object Oriented Programming, we model software after real-life objects. To be good at modeling software after
real-life objects, we should be able to properly describe them.
The following description is a bad way of describing, as the information of an object scattered and unorganized.
Organized Description
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 2/3
1/23/22, 9:25 PM Revolutionizing the Job Market | NxtWave
Object 1 is a car
Object 1 has
Four tyres
Four seats
Four doors
and so on ...
Object 1 can
Sound horn
Move
Expand
The above description shows a simple framework where we describe object by specifying the properties that the
object has and actions that the object can do.
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 3/3
1/23/22, 9:27 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Sometimes, the objects that we are describing are so similar that only values of the properties differ.
Object 3 is a Mobile
Properties
camera : 13 MP
storage : 16 GB
battery life : 21 Hrs
ram : 3 GB
and so on ...
Object 4 is a Mobile
Properties
Expand
In this case, the objects that we describe have completely the same set of properties like camera, storage, etc.
Template
For objects that are very similar to each other (objects that have the same set of actions and properties), we can
create a standard Form or Template that can be used to describe different objects in that category.
Mobile Template
Model :
Camera:
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 1/6
1/23/22, 9:27 PM Revolutionizing the Job Market | NxtWave
Camera:
Storage:
Does it have a Face Unlock? Yes | No
Filled Template
Bundling Data
While modeling real-life objects with object oriented programming, we ensure to bundle related information
together to clearly separate information of different objects.
Defining a Class
class
Special Method
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 2/6
1/23/22, 9:27 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera = camera
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera = camera
5 def make_call(self, number):
6 print("calling..")
model and camera are the properties and values are which passed to the __init__
method.
Action
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera = camera
5 def make_call(self, number):
6 print("calling..")
PYTHON
1 def make_call(self, number):
2 print("calling..")
In OOP terminology, properties are referred as attributes actions are referred as methods
Using a Class
Instance of Class
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 3/6
1/23/22, 9:27 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera= camera
5
6 mobile_obj = Mobile(
7 "iPhone 12 Pro",
8 "12 MP")
9 print(mobile_obj)
Class Object
An object is simply a collection of attributes and methods that act on those data.
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera= camera
5
6 mobile_obj = Mobile(
7 "iPhone 12 Pro",
8 "12 MP")
9 print(mobile_obj)
Similar to functions, Methods also support positional, keyword & default arguments and also return values.
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera= camera
5 def make_call(self,number):
6 return "calling..{}".format(number)
Code
PYTHON
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 4/6
1/23/22, 9:27 PM Revolutionizing the Job Market | NxtWave
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera= camera
5 def make_call(self,number):
6 print("calling..{}".format(number))
7
8 mobile_obj = Mobile("iPhone 12 Pro", "12 MP")
9 mobile_obj.make_call(9876543210)
Output
calling..9876543210
Multiple Instances
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera= camera
5 def make_call(self,number):
6 print("calling..{}".format(number))
7
8 mobile_obj1 = Mobile("iPhone 12 Pro", "12 MP")
9 print(id(mobile_obj1))
10 mobile_obj2 = Mobile("Galaxy M51", "64 MP")
Expand
Output
139685004996560
139685004996368
Type of Object
The class from which object is created is considered to be the type of object.
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, camera):
3 self.model = model
4 self.camera = camera
5
6 obj_1 = Mobile("iPhone 12 Pro", "12 MP")
7 print(type(obj_1))
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 5/6
1/23/22, 9:27 PM Revolutionizing the Job Market | NxtWave
Output
<class '__main__.Mobile'>
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 6/6
1/23/22, 9:27 PM Revolutionizing the Job Market | NxtWave
. (dot) character.
Code
PYTHON
1 class Mobile:
2 def __init__(self, model, storage):
3 self.model = model
4 self.storage = storage
5
6
7 obj = Mobile("iPhone 12 Pro", "128GB")
8 print(obj.model)
Output
iPhone 12 Pro
Code
PYTHON
1 class Mobile:
2 def __init__(self, model):
3 self.model = model
4
5 def get_model(self):
6 print(self.model)
7
8
9 obj_1 = Mobile("iPhone 12 Pro")
10 obj_1.get_model()
Output
iPhone 12 Pro
Updating Attributes
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 1/3
1/23/22, 9:27 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 class Mobile:
2 def __init__(self, model):
3 self.model = model
4
5 def update_model(self, model):
6 self.model = model
7
8
9 obj_1 = Mobile("iPhone 12")
10 print(obj_1.model)
Expand
Output
iPhone 12
iPhone 12 Pro
Modeling Class
Code
PYTHON
1 class Cart:
2 def __init__(self):
3 self.items = {}
4 self.price_details = {"book": 500, "laptop": 30000}
5
6 def add_item(self, item_name, quantity):
7 self.items[item_name] = quantity
8
9 def remove_item(self, item_name):
10 del self.items[item_name]
Expand
Output
31500
['book']
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 2/3
1/23/22, 9:27 PM Revolutionizing the Job Market | NxtWave
1000
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 3/3
1/23/22, 9:28 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Users can add different items to their shopping cart and checkout.
The total value of the cart should be more than a minimum amount (Rs. 100/-) for the checkout.
During Offer Sales, all users get a flat discount on their cart and the minimum cart value will be Rs. 200/-.
Attributes
Instance Attributes
Class Attributes
Instance Attributes
Attributes whose value can differ for each instance of class are modeled as instance attributes.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4… 1/11
1/23/22, 9:28 PM Revolutionizing the Job Market | NxtWave
Class Attributes
Attributes whose values stay common for all the objects are modelled as Class Attributes.
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6 def add_item(self,..):
7 self.items[item_name] = quantity
8 def display_items(self):
9 print(items)
10 C t()
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4… 2/11
1/23/22, 9:28 PM Revolutionizing the Job Market | NxtWave
10 a = Cart()
Expand
Output
Self
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6 def add_item(self,item_name, quantity):
7 self.items[item_name] = quantity
8 def display_items(self):
9 print(self)
10
Expand
Output
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6 def add_item(self, item_name,quantity):
7 self.items[item_name] = quantity
8 def display_items(self):
9 print(self.items)
10 a = Cart()
Expand
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4… 3/11
1/23/22, 9:28 PM Revolutionizing the Job Market | NxtWave
{"book": 3}
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6 def add_item(self, item_name,quantity):
7 self.items[item_name] = quantity
8 def display_items(self):
9 print(self.items)
10 a = Cart()
Expand
Output
{'book': 3}
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6 def add_item(self, item_name,quantity):
7 self.items[item_name] = quantity
8 def display_items(self):
9 print(self.items)
10 print(Cart.items)
Output
Example 1
Code
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4… 4/11
1/23/22, 9:28 PM Revolutionizing the Job Market | NxtWave
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6
7 print(Cart.min_bill)
Output
100
Example 2
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def __init__(self):
5 self.items = {}
6 def print_min_bill(self):
7 print(Cart.min_bill)
8
9 a = Cart()
10 a.print_min_bill()
Output
100
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 def print_min_bill(self):
5 print(Cart.min_bill)
6 a = Cart()
7 b = Cart()
8 Cart.min_bill = 200
9 print(a.print_min_bill())
10 print(b.print_min_bill())
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4… 5/11
1/23/22, 9:28 PM Revolutionizing the Job Market | NxtWave
Output
200
200
Method
Instance Methods
Class Methods
Static Methods
Instance Methods
Instance methods can access all attributes of the instance and have self as a parameter.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4… 6/11
1/23/22, 9:28 PM Revolutionizing the Job Market | NxtWave
Example 1
Code
PYTHON
1 class Cart:
2 def __init__(self):
3 self.items = {}
4 def add_item(self, item_name,quantity):
5 self.items[item_name] = quantity
6 def display_items(self):
7 print(self.items)
8
9 a = Cart()
10 a.add_item("book", 3)
Expand
Output
{'book': 3}
Example 2
Code
PYTHON
1 class Cart:
2 def __init__(self):
3 self.items = {}
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4… 7/11
1/23/22, 9:28 PM Revolutionizing the Job Market | NxtWave
3 self.items {}
4 def add_item(self, item_name,quantity):
5 self.items[item_name] = quantity
6 self.display_items()
7 def display_items(self):
8 print(self.items)
9
10 a = Cart()
Expand
Output
{'book': 3}
Class Methods
Methods which need access to class attributes but not instance attributes are marked as Class Methods.
For class methods, we send
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 @classmethod
5 def update_flat_discount(cls,
6 new_flat_discount):
7 cls.flat_discount = new_flat_discount
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4… 8/11
1/23/22, 9:28 PM Revolutionizing the Job Market | NxtWave
8
9 Cart.update_flat_discount(25)
10 print(Cart.flat_discount)
Output
25
Code
PYTHON
1 class Cart:
2 flat_discount = 0
3 min_bill = 100
4 @classmethod
5 def update_flat_discount(cls, new_flat_discount):
6 cls.flat_discount = new_flat_discount
7
8 @classmethod
9 def increase_flat_discount(cls, amount):
10 new_flat_discount = cls.flat_discount + amount
Expand
Output
50
Static Method
We might need some generic methods that don’t need access to either instance or class attributes. These type of
methods are called Static Methods.
Usually, static methods are used to create utility functions which make more sense to be part of the class.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4… 9/11
1/23/22, 9:28 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 class Cart:
2
3 @staticmethod
4 def greet():
5 print("Have a Great Shopping")
6
7 Cart.greet()
Output
No cls or self as
self as parameter cls as parameter
parameters
Need decorator Need decorator
No decorator required
@classmethod @staticmethod
Can be accessed through Can be accessed Can be accessed
object(instance of class) through class through class
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f… 10/11
1/23/22, 9:28 PM Revolutionizing the Job Market | NxtWave
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f… 11/11
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Inheritance
Products
Lets model e-commerce site having different products like Electronics, Kids Wear, Grocery, etc.
Electronic Item
Grocery Item
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 1/8
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
All these products Electronics, Kids Wear, Grocery etc.. have few common attributes & methods.
Also, each product has specific attributes & methods of its own.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 2/8
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
Electronic Item & Grocery Item will have all attributes & methods which are common to all products.
Lets Separate the common attributes & methods as Product
Modelling Classes
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 3/8
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
Reusability
Clear Separation
More Organized
Inheritance
Inheritance is a mechanism by which a class inherits attributes and methods from another class.
ElectronicItem inherit the attributes & methods from Product instead of defining them
again.
Super Class
Code
PYTHON
1 class Product:
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 4/8
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
Expand
Output
Product: Shoes
Price: 500
Deal Price: 250
You Saved: 250
Ratings: 3.5
Sub Class
The subclass automatically inherits all the attributes & methods from its superclass.
Example 1
Code
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
Expand
Output
Product: TV
Price: 45000
Deal Price: 40000
You Saved: 5000
Ratings: 3.5
Example 2
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 5/8
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
Expand
Output
Product: milk
Price: 25
Deal Price: 20
You Saved: 5
Ratings: 3
Example 3
Code
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
Expand
Output
24
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 6/8
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
Expand
Output
Code
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
Expand
Output
Product: TV
Price: 45000
Deal Price: 40000
You Saved: 5000
Ratings: 3.5
We can call methods defined in superclass from the methods in the subclass.
Code
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 7/8
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
PYTHON
1 class Product:
2 def __init__(self, name, price, deal_price, ratings):
3 self.name = name
4 self.price = price
5 self.deal_price = deal_price
6 self.ratings = ratings
7 self.you_save = price - deal_price
8 def display_product_details(self):
9 print("Product: {}".format(self.name))
10 print("Price: {}".format(self.price))
Expand
Output
Product: TV
Price: 45000
Deal Price: 40000
You Saved: 5000
Ratings: 3.5
Warranty 24 months
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 8/8
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Inheritance - Part 2
How would you design and implement placing order with the details of all the products
bought?
Composition
Code
PYTHON
48 total_bill += price
49 print("Total Bill: {}".format(total_bill))
50
51 milk = GroceryItem("Milk",40, 25, 3.5)
52 tv = ElectronicItem("TV",45000, 40000, 3.5)
53 order = Order("Prime Delivery", "Hyderabad")
54 order.add_item(milk, 2)
55 order.add_item(tv, 1)
56 order.display_order_details()
57 order.display_total_bill()
Expand
Output
You Saved: 15
Ratings: 3.5
Quantity: 2
Product: TV
Price: 45000
Deal Price: 40000
You Saved: 5000
Ratings: 3.5
Quantity: 1
Total Bill: 40050
Expand
Overriding Methods
Sometimes, we require a method in the instances of a sub class to behave differently from the method in instance of a
superclass.
Code
PYTHON
1 class Product:
2
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 1/5
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
Output
Because
Super
super() allows us to call methods of the superclass (Product) from the subclass.
Instead of writing and methods to access and modify warranty we can override
__init__
Code
PYTHON
1 class Product:
2
3 def __init__(self, name, price, deal_price, ratings):
4 self.name = name
5 self.price = price
6 self.deal_price = deal_price
7 self.ratings = ratings
8 self.you_save = price - deal_price
9
10 def display_product_details(self):
Expand
Output
Product: Laptop
Price: 45000
Deal Price: 40000
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 2/5
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
You Saved: 5000
Ratings: 3.5
Warranty 10 months
MultiLevel Inheritance
PYTHON
1 class Product:
2 pass
3
4 class ElectronicItem(Product):
5 pass
6
7 class Laptop(ElectronicItem):
8 pass
Prefer modeling with inheritance when the classes have an IS-A relationship.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 3/5
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
Prefer modeling with inheritance when the classes have an HAS-A relationship.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 4/5
1/23/22, 9:29 PM Revolutionizing the Job Market | NxtWave
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=b6025dfc-a6e3-4225-ad36-ad07ca8d9f4e… 5/5
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Standard Library
Built-in Functions
1. print()
2. max()
3. min()
Standard Library
Python provides several such useful values (constants), classes and functions.
1. collections
2. random
3. datetime
To use a functionality defined in a module we need to import that module in our program.
PYTHON
1 import module_name
Math Module
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 1/8
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
math module provides us to access some common math functions and constants.
Code
PYTHON
1 import math
2 print(math.factorial(5))
3 print(math.pi)
Output
120
3.141592653589793
Importing module
Code
PYTHON
1 import math as m1
2 print(m1.factorial(5))
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 2/8
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
120
Code
PYTHON
1 from math import factorial
2 print(factorial(5))
Output
120
Aliasing Imports
Code
PYTHON
1 from math import factorial as fact
2 print(fact(5))
Output
120
Random module
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 3/8
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Randint
randint() is a function in random module which returns a random integer in the given
interval.
Code
PYTHON
1 import random
2 random_integer = random.randint(1, 10)
3 print(random_integer)
Output
Choice
choice() is a function in random module which returns a random element from the
sequence.
Code
PYTHON
1 import random
2 random ele = random.choice(["A","B","C"])
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 4/8
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
2 random_ele random.choice([ A , B , C ])
3 print(random_ele)
Output
To know more about Python Standard Library, go through the authentic python documentation
- https://docs.python.org/3/library/
Map
map()applies a given function to each item of a sequence (list, tuple etc.) and returns a
sequence of the results.
Example - 1
Code
PYTHON
1 def square(n):
2 return n * n
3 numbers = [1, 2, 3, 4]
4 result = map(square, numbers)
5 numbers_square = list(result)
6 print(numbers square)
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 5/8
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
p ( _ q )
Output
[1, 4, 9, 16]
Example - 2
Code
PYTHON
1 numbers = list(map(int, input().split()))
2 print(numbers)
Input
1 2 3 4
Output
[1, 2, 3, 4]
Filter
method filters the elements of a given sequence based on the result of given
filter()
function.
C d
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 6/8
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 def is_positive_number(num):
2 return num > 0
3
4 list_a = [1, -2, 3, -4]
5 positive_nums = filter(is_positive_number, list_a)
6 print(list(positive_nums))
Output
[1, 3]
Reduce
Code
PYTHON
1 from functools import reduce
2
3 def sum_of_num(a, b):
4 return a+b
5
6 list_a = [1, 2, 3, 4]
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 7/8
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Output
10
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 8/8
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Object
Strings, Integers, Floats, Lists, Functions, Module etc. are all objects.
Identity of an Object
Whenever an object is created in Python, it will be given a unique identifier (id).This unique id can be different
for each time you run the program.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 1/10
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Every object that you use in a Python Program will be stored in Computer Memory
The unique id will be related to the location where the object is stored in the Computer Memory.
Name of an Object
Namespaces
A namespace is a collection of currently defined names along with information about the object that the name
references.
It ensures that names are unique and won’t lead to any conflict.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 2/10
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Namespaces allow us to have the same name referring different things in different namespaces.
Code
PYTHON
1 def greet_1():
2 a = "Hello"
3 print(a)
4 print(id(a))
5
6 def greet_2():
7 a = "Hey"
8 print(a)
9 print(id(a))
10
Expand
Output
Namespace - 1
Hello
140639382368176
Namespace - 2
Hey
140639382570608
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 3/10
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
140639382570608
Types of namespaces
As Python executes a program, it creates namespaces as necessary and forgets them when they are no longer needed.
1. Built-in
2. Global
3. Local
Built-in Namespace
Created when we start executing a Python program and exists as long as the program is running.
This is the reason that built-in functions like id(), print() etc. are always available to us from any part of the
program.
Global Namespace
This namespace includes all names defined directly in a module (outside of all functions).
It is created when the module is loaded, and it lasts until the program ends.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 4/10
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Local Namespace
A new local namespace is created when a function is called, which lasts until the function returns.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 5/10
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Scope of a Name
The scope of a name is the region of a program in which that name has meaning.
Python searches for a name from the inside out, looking in the
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 6/10
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Global variables
Example 1
Code
PYTHON
1 x = "Global Variable"
2 print(x)
3
4 def foo():
5 print(x)
6
7 foo()
Output
Global Variable
Global Variable
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 7/10
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Global Variable
Example 2
Code
PYTHON
1 def foo():
2 print(x)
3
4 x = "Global Variable"
5
6 foo()
Output
Global Variable
Local Variables
This variable name will be part of the Local Namespace which will be created when the function is called and lasts until
the function returns.
Code
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 8/10
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
PYTHON
1 def foo():
2 x = "Local Variable"
3 print(x)
4
5 foo()
6 print(x)
Output
Local Variable
NameError: name 'x' is not defined
As,
Local Import
Code
PYTHON
1 def foo():
2 import math
3 print(math.pi)
4
5 foo()
6 print(math.pi)
Output
3.141592653589793
NameError: name 'math' is not defined
Code
PYTHON
1 x = "Global Variable"
2
3 def foo():
4 x = "Local Variable"
5 print(x)
6
7 print(x)
8 foo()
9 print(x)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 9/10
1/23/22, 9:30 PM Revolutionizing the Job Market | NxtWave
Global Variable
Local Variable
Global Variable
global keyword is used to define a name to refer to the value in Global Namespace.
Code
PYTHON
1 x = "Global Variable"
2
3 def foo():
4 global x
5 x = "Global Change"
6 print(x)
7
8 print(x)
9 foo()
10 print(x)
Output
Global Variable
Global Change
Global Change
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed7323… 10/10
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
1. Syntax Errors
2. Exceptions
Syntax Errors
Syntax errors are parsing errors which occur when the code is not adhering to Python Syntax.
Code
PYTHON
1 if True print("Hello")
Output
When there is a syntax error, the program will not execute even if that part of code is not used.
Code
PYTHON
1 print("Hello")
2
3 def greet():
4 print("World"
Output
Notice that in the above code, the syntax error is inside the
Exceptions
Even when a statement or expression is syntactically correct, it may cause an error when an attempt is made to
execute it.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 1/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
Example Scenario
Example 1
Division Example
Code
PYTHON
1 def divide(a, b):
2 return a / b
3
4 divide(5, 0)
Output
Example 2
Code
PYTHON
1
2 def divide(a, b):
3 return a / b
4
5 divide("5", "10")
Output
Example 3
Consider the following code, which is used to update the quantity of items in store.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 2/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
Code
PYTHON
1 class Store:
2 def __init__(self):
3 self.items = {
4 "milk" : 20, "bread" : 30, }
5
6 def add_item(self, name, quantity):
7 self.items[name] += quantity
8
9 s = Store()
10 s.add_item('biscuits', 10)
Output
KeyError: 'biscuits'
What happens when your code runs into an exception during execution?
End-User Applications
When you develop applications that are directly used by end-users, you need to handle different possible
Reusable Modules
When you develop modules that are used by other developers, you should raise exceptions for different scenarios
so that other developers can handle them.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 3/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
Let’s consider we are creating an app that allows users to transfer money between them.
Example 1
Code
PYTHON
1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
6 def get_balance(self):
7 return self.balance
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
Expand
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 4/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
Example 2
Code
PYTHON
5
6 def get_balance(self):
7 return self.balance
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
11 self.balance -= amount
12 else:
13 print("Insufficient Funds")
14
Expand
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 5/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
Raising Exceptions
When your code enters an unexpected state, raise an exception to communicate it.
Built-in Exceptions
You can use the built-in exception classes with raise keyword to raise an exception in the program.
Code
PYTHON
1 raise ValueError("Unexpected Value!!")
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 6/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
ValueError:Unexpected Value!!
Example 1
Code
PYTHON
25 user_2 = BankAccount("002")
26 user_1.deposit(25)
27 user_2.deposit(100)
28
29 print("User 1 Balance: {}/-".format(user_1.get_balance()))
30 print("User 2 Balance: {}/-".format(user_2.get_balance()))
31 transfer_amount(user_1, user_2, 50)
32 print("Transferring 50/- from User 1 to User 2")
33 print("User 1 Balance: {}/-".format(user_1.get_balance()))
34 print("User 2 Balance: {}/-".format(user_2.get_balance()))
Expand
Output
Handling Exceptions
Python provides a way to catch the exceptions that were raised so that they can be properly handled.
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 7/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
Whenever an exception occurs at some line in try block, the execution stops at that line and jumps to except
block.
PYTHON
1 try:
2 # Write code that
3 # might cause exceptions.
4 except:
5 # The code to be run when
6 # there is an exception.
Transfer Amount
Example 1
Code
PYTHON
1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
5
6 def get_balance(self):
7 return self.balance
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
Expand
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 8/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
False
Transferring 50/- from User 1 to User 2
User 1 Balance: 25/-
User 2 Balance: 100/-
Summary
Reusable Modules
While developing reusable modules, we need to raise Exceptions to stop our code from being used in a bad way.
End-User Applications
While developing end-user applications, we need to handle Exceptions so that application will not crash when
used.
We can specifically mention the name of exception to catch all exceptions of that specific type.
Syntax
PYTHON
1 try:
2 # Write code that
3 # might cause exceptions.
4 except Exception:
5 # The code to be run when
6 # there is an exception.
Example 1
Code
PYTHON
1 try:
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
8 except:
9 print("Unhandled Exception")
Input
5
0
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed73235… 9/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
Denominator can't be 0
Example 2
Code
PYTHON
1 try:
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
8 except:
9 print("Unhandled Exception")
Input
12
a
Output
Unhandled Exception
Syntax
PYTHON
1 try:
2 # Write code that
3 # might cause exceptions.
4 except Exception as e:
5 # The code to be run when
6 # there is an exception.
Code
PYTHON
1 class BankAccount:
2 def __init__(self, account_number):
3 self.account_number = str(account_number)
4 self.balance = 0
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed7323… 10/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
5
6 def get_balance(self):
7 return self.balance
8
9 def withdraw(self, amount):
10 if self.balance >= amount:
Expand
Output
We can write multiple exception blocks to handle different types of exceptions differently.
Syntax
PYTHON
1 try:
2 # Write code that
3 # might cause exceptions.
4 except Exception1:
5 # The code to be run when
6 # there is an exception.
7 except Exception2:
8 # The code to be run when
9 # there is an exception.
Example 1
Code
PYTHON
1 try:
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
8 except ValueError:
9 print("Input should be an integer")
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed7323… 11/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
10 except:
Expand
Input
5
0
Output
Denominator can't be 0
Example 2
Code
PYTHON
1 try:
2 a = int(input())
3 b = int(input())
4 c = a/b
5 print(c)
6 except ZeroDivisionError:
7 print("Denominator can't be 0")
8 except ValueError:
9 print("Input should be an integer")
10 except:
Expand
Input
12
a
Output
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed7323… 12/13
1/23/22, 9:31 PM Revolutionizing the Job Market | NxtWave
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed7323… 13/13
1/23/22, 9:32 PM Revolutionizing the Job Market | NxtWave
Cheat Sheet
Datetime
Python has a built-in datetime module which provides convenient objects to work with dates and times.
Code
PYTHON
1 import datetime
Datetime classes
date class
time class
datetime class
timedelta class
Representing Date
A date object can be used to represent any valid date (year, month and day).
Code
PYTHON
1 import datetime
2
3 date_object = datetime.date(2019, 4, 13)
4 print(date_object)
Output
2019-04-13
Date Object
Code
PYTHON
1 from datetime import date
2 date_obj = date(2022, 2, 31)
3 print(date_obj)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 1/7
1/23/22, 9:32 PM Revolutionizing the Job Market | NxtWave
Today’s Date
Class method
Code
PYTHON
1 import datetime
2
3 date_object = datetime.date.today()
4 print(date_object)
Output
2021-02-05
Code
PYTHON
1 from datetime import date
2
3 date_object = date(2019, 4, 13)
4 print(date_object.year)
5 print(date_object.month)
6 print(date_object.day)
Output
2019
4
13
A time object can be used to represent any valid time (hours, minutes and seconds).
Code
PYTHON
1 from datetime import time
2
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 2/7
1/23/22, 9:32 PM Revolutionizing the Job Market | NxtWave
2
3 time_object = time(11, 34, 56)
4 print(time_object)
Output
11:34:56
Code
PYTHON
1 from datetime import time
2
3 time_object = time(11, 34, 56)
4 print(time_object)
5 print(time_object.hour)
6 print(time_object.minute)
7 print(time_object.second)
Output
11:34:56
11
34
56
Datetime
Example - 1
Code
PYTHON
1 from datetime import datetime
2
3 date_time_obj = datetime(2018, 11, 28, 10, 15, 26)
4 print(date_time_obj.year)
5 print(date_time_obj.month)
6 print(date_time_obj.hour)
7 print(date_time_obj.minute)
Output
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 3/7
1/23/22, 9:32 PM Revolutionizing the Job Market | NxtWave
2018
11
10
15
Example - 2
It gives the current date and time
Code
PYTHON
1 import datetime
2
3 datetime_object = datetime.datetime.now()
4 print(datetime_object)
Output
2021-02-05 09:26:08.077473
DateTime object
Code
PYTHON
1 from datetime import datetime
2 date_time_obj = datetime(2018, 11, 28)
3 print(date_time_obj)
Output
2018-11-28 00:00:00
Formatting Datetime
strftime(format) method to format the datetime into any required format like
mm/dd/yyyy
dd-mm-yyyy
Sunday, Monday,
%A Weekday as full name
...
Hour (24-hour clock) as a zero-padded decimal
%H 00, 01, …, 23
number
Hour (12-hour clock) as a zero-padded decimal
%I 01, 02, …, 12
number
%p AM or PM AM, PM
Code
PYTHON
1 from datetime import datetime
2
3 now = datetime.now()
4 formatted_datetime_1 = now.strftime("%d %b %Y %I:%M:%S %p")
5 print(formatted_datetime_1)
6
7 formatted_datetime_2 = now.strftime("%d/%m/%Y, %H:%M:%S")
8 print(formatted_datetime_2)
Output
Parsing Datetime
strptime() creates a datetime object from a given string representing date and time.
Code
PYTHON
1 from datetime import datetime
2
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 5/7
1/23/22, 9:32 PM Revolutionizing the Job Market | NxtWave
2
3 date_string = "28 November, 2018"
4 print(date_string)
5
6 date_object = datetime.strptime(date_string, "%d %B, %Y")
7 print(date_object)
Output
28 November, 2018
2018-11-28 00:00:00
Example 1
Code
PYTHON
1 from datetime import timedelta
2
3 delta = timedelta(days=365, hours=4)
4 print(delta)
Output
Example 2
Code
PYTHON
1 from datetime import timedelta, datetime
2 delta = timedelta(days=365)
3 current_datetime = datetime.now()
4 print(current_datetime)
5 next_year_datetime = current_datetime + delta
6 print(next_year_datetime)
Output
2021-02-05 09:28:30.239095
2022-02-05 09:28:30.239095
Code
PYTHON
1 import datetime
2
3 dt1 = datetime.datetime(2021, 2, 5)
4 dt2 = datetime.datetime(2022, 1, 1)
5 duration = dt2 - dt1
6 print(duration)
7 print(type(duration))
Output
Submit Feedback
https://learning.ccbp.in/tech-foundations/course?c_id=a6454e48-d030-4d49-8920-253198052232&t_id=7f553143-459d-43df-a3fb-4749ed732353… 7/7