0% found this document useful (0 votes)
77 views335 pages

Python Mastery for Educators Guide

The document 'Mastering Python for the Modern Educator' by Anshu Goyal provides a comprehensive guide to Python programming, covering its features, applications, and syntax. It includes sections on Python's history, comparison with C++, and various programming concepts such as data types, control flow, functions, and modules. The document is designed for educators and learners looking to master Python and its applications in modern technology.

Uploaded by

karthik katakam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views335 pages

Python Mastery for Educators Guide

The document 'Mastering Python for the Modern Educator' by Anshu Goyal provides a comprehensive guide to Python programming, covering its features, applications, and syntax. It includes sections on Python's history, comparison with C++, and various programming concepts such as data types, control flow, functions, and modules. The document is designed for educators and learners looking to master Python and its applications in modern technology.

Uploaded by

karthik katakam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Mastering Python for the Modern Educator

By Anshu Goyal
TABLE OF CONTENT

Mastering Python for the Modern Educator


By Anshu Goyal
TABLE OF CONTENT
About the Author
Copyright Page
Copyright © 2024 by Anshu Goyal
Python Tutorial
What is Python?
Why to Learn Python?
Python Online Compiler
Careers with Python
Characteristics of Python
Applications of Python
Features of Python
Target Audience
Prerequisites
Python - Overview
Pythonic Code Style
The Zen of Python
Python - History
History of Python
Who Invented Python?
Python 0.9.0
Python 1.0
Python 2.0
Python 3.0
EOL for Python 2.x
Current Version of Python
What's New in Python 3.11?
Frequently Asked Questions About Python History
1. Who created Python?
2. Why Python is called Python?
3. When was Python's first version released?
4. What was the first version of Python?
5. When was Python 3.0 version released?
Python - Features
Easy to Learn
Dynamically Typed
Interactive
Multi-paradigm
Standard Library
Open Source and Cross Platform
GUI Applications
Database Connectivity
Extensible
Active Developer Community
Python vs C++
What is Python?
Features
Python Example
Output
What is C++?
Features
C++ Example
Output
Comparison Between Python and C++ across Various Aspects
Compiled vs Interpreted
Cross platform
Portability
Speed of Development
Easy to Learn
Static vs Dynamic Typing
OOP Concepts
Garbage Collection
Application Areas
Difference Between Python and C++
Python - Hello World Program
Hello World Program in Python
Steps
Different Ways to Write and Execute Hello World Program
Using Python Interpreter Command Prompt Mode
Example
Example
Using Python Interpreter Script Mode
Using Shebang #! in Linux Scripts
FAQs
1. Why the first program is called Hello World?
2. Installation of Python is required to run Hello World program?
3. How do I run a Python program without installing it?
4. First Program Vs Hello World Program in Python?
5. Which is/are the method to print Hello World or any message?
Python - Application Areas
Data Science
Machine Learning
Computer Vision and Image processing
Embedded Systems and IoT
Job Scheduling and Automation
Desktop GUI Applications
Console-based Applications
CAD Applications
Game Development
Python Interpreter and Its Modes
Python Interpreter
Python Interpreter - Interactive Mode
Python Interpreter - Scripting Mode
Python Interpreter - Using Shebang #!
Interactive Python - IPython
Python - Environment Setup
Local Environment Setup
Downloading Python
Install Python on Ubuntu Linux
Install Python on other Linux
Using Yum Command
Install Python on Windows
Macintosh Installation
Setting up PATH
Setting path at Unix/Linux
Setting path at Windows
Python Environment Variables
Running Python
Interactive Interpreter
Script from the Command-line
Integrated Development Environment
Python - Virtual Environment
Python Virtual Environment
What is Virtual Environment in Python?
Activating Virtual Environment
Checking If Python is Running Inside a Virtual Environment?
Deactivating Virtual Environment
Python - Syntax
Python - Syntax
First Python Program
Python - Interactive Mode Programming
Python - Script Mode Programming
Python Reserved Words
Python Lines and Indentation
Python Multi-Line Statements
Quotations in Python
Comments in Python
Using Blank Lines in Python Programs
Waiting for the User
Multiple Statements on a Single Line
Multiple Statement Groups as Suites
Command Line Arguments in Python
Python - Variables
Python Variables
Memory Addresses
Example to Create Python Variables
Printing Python Variables
Example to Print Python Variables
Deleting Python Variables
Example
Getting Type of a Variable
Example: Printing Variables Type
Casting Python Variables
Example
Case-Sensitivity of Python Variables
Python Variables - Multiple Assignment
Python Variables - Naming Convention
Example
Example
Example
Python Local Variables
Example
Python Global Variables
Example
Constants in Python
Python vs C/C++ Variables
Python - Data Types
Python Data Types
Types of Data Types in Python
Example of Numeric Data Types
2. Python String Data Type
Example of String Data Type
3. Python Sequence Data Types
(a) Python List Data Type
Example of List Data Type
(b) Python Tuple Data Type
Example of Tuple data Type
(c) Python Range Data Type
Example of Range Data Type
4. Python Binary Data Types
(a) Python Bytes Data Type
Example of Bytes Data Type
(b) Python Bytearray Data Type
Example of Bytearray Data Type
(c) Python Memoryview Data Type
Example of Memoryview Data Type
5. Python Dictionary Data Type
Example of Dictionary Data Type
6. Python Set Data Type
Example of Set
7. Python Boolean Data Type
Example of Boolean Data Type
8. Python None Type
Example of None Type
Getting Data Type
Example
Setting Data Type
Example
Primitive and Non-primitive Data Types
1. Primitive Types
2. Non-primitive Types
Python Data Type Conversion
Example
Data Type Conversion Functions
Python - Type Casting
Python Type Casting
Python Implicit Casting
Python int() Function
String to Integer
Binary String to Integer
Octal String to Integer
Hexa-Decimal String to Integer
Python float() Function
Python str() Function
Integer to string
Float to String
Conversion of Sequence Types
Data Type Conversion Functions
Python - Unicode System
What is Unicode System?
Character Encoding
Example
Example
Example
Example
Python - Literals
What are Python Literals?
Different Types of Python Literals
1. Decimal Literal
2. Octal Literal
3. Hexadecimal Literal
Example
Python Float Literal
Example of Float Literal
Example of Float Scientific Notation Literal
Python Complex Literal
Example of Complex Type Literal
Python String Literal
Example of String Literal
Example of String Literal With Double Quoted Inside String
Python List Literal
Example of List Type Literal
Python Tuple Literal
Example of Tuple Type Literal
Example of Tuple Type Literal Without Parenthesis
Python Dictionary Literal
Example of Dictionary Type Literal
Python - Operators
Python Operators
Types of Python Operators
Example of Python Arithmetic Operators
Python Comparison Operators
Example of Python Comparison Operators
Python Assignment Operators
Example of Python Assignment Operators
Python Bitwise Operators
Example of Python Bitwise Operators
Python Logical Operators
Example of Python Logical Operators
Python Membership Operators
Example of Python Membership Operators
Python Identity Operators
Example of Python Identity Operators
Python Operators Precedence
Python Arithmetic Operators
Types of Arithmetic Operators
Example to add two integer numbers
Example to add integer and float numbers
Example to add two complex numbers
Subtraction Operator
Example to subtract two integer numbers
Example to subtract integer and float numbers
Example to subtract complex numbers
Multiplication Operator
Example to multiply two integers
Example to multiply integer and float numbers
Example to multiply complex numbers
Division Operator
Example to divide two numbers
Example to divide two float numbers
Example to divide complex numbers
Modulus Operator
Example for modulus operation on integers
Example for modulus operation on floats
Exponent Operator
Example of exponent operator
Floor Division Operator
Example of floor division operator
Precedence and Associativity of Arithmetic Operators
Arithmetic Operators with Complex Numbers
Addition and subtraction of complex numbers
Multiplication of complex numbers
Division of complex numbers
Python Comparison Operators
Different Comparison Operators in Python
Example
Example
Example
Comparison of Complex umbers
Example
Example
**Comparison of Booleans**
**Example**
**Comparison of Sequence Types**
**Example**
**Example**
**Example**
**Comparison of Dictionary Objects**
**Example**
**Python Assignment Operator**
**Example of Assignment Operator in Python**
**Augmented Assignment Operators in Python**
**Example**
**Augmented Addition Operator (+=)**
**Augmented Subtraction Operator (-=)**
**Augmented Multiplication Operator (*=)**
**Augmented Division Operator (/=)**
**Augmented Modulus Operator (%=)**
**Augmented Exponent Operator (=)****
**Augmented Floor division Operator (//=)**
**Python Logical Operators**
**Example**
**Logical "and" Operator**
**Logical "and" Operator Truth Table**
**Logical "or" Operator Truth Table**
**Logical "not" Operator**
**Logical "not" Operator Truth Table**
**How the Python interpreter evaluates the logical operators?**
**Python Logical Operators Examples**
**Example 1: Logical Operators With Boolean Conditions**
**Example 2: Logical Operators With Non- Boolean Conditions**
**Example 3: Logical Operators With Strings and Tuples**
**Example 4: Logical Operators To Compare Sequences (Lists)**
**Python Bitwise Operators**
**Python Bitwise AND Operator (&)**
**Example of Bitwise AND Operator in Python**
**Example of Bitwise OR Operator in Python**
**Python Bitwise XOR Operator (^)**
**Example of Bitwise XOR Operator in Python**
**Python Bitwise NOT Operator (~)**
**Example of Bitwise NOT Operator in Python**
**Python Bitwise Left Shift Operator (<<)**
**Example of Bitwise Left Shift Operator in Python**
**Python Bitwise Right Shift Operator (>>)**
**Example of Bitwise Right Shift Operator in Python**
**Python Membership Operators**
**Types of Python Membership Operators**
**The 'in' Operator**
**Example of Python Membership "in" Operator**
**The 'not in' Operator**
**Example of Python Membership "not in" Operator**
**Example**
**Membership Operator with Sets**
**Membership Operator with Dictionaries**
**Python Identity Operators**
**Python 'is' Operator**
**Example of Python Identity 'is' Operator**
**Example of Python Identity 'is not' Operator**
**Python Identity Operators Examples with Explanations**
**Example 1**
**Example 2**
**Example 3**
**Python Operator Precedence**
**Python Operator Precedence Table**
**Python Comments**
**Example**
**Single Line Comments in Python**
**Example: Standalone Single-Line Comment**
**Example: Inline Single-Line Comment**
**Consecutive Single-Line Comments**
**Multi Line Comment Using Triple Quoted Strings**
**Using Comments for Documentation**
**Python Docstrings**
**Accessing Docstrings**
**Provide User Input in Python**
**Python User Input Functions**
**The raw_input() Function**
**Taking Numeric Input in Python**
**The print() Function**
**Python - Number Types**
**Python − Integer Numbers**
**Binary Numbers in Python**
**Octal Numbers in Python**
**Hexa-decimal Numbers in Python**
**Python − Complex Numbers**
**Number Type Conversion**
**Theoretic and Representation Functions**
**Power and Logarithmic Functions**
**Trigonometric Functions**
**Angular conversion Functions**
**Mathematical Constants**
**Hyperbolic Functions**
**Special Functions**
**Random Number Functions**
**Built-in Mathematical Functions**
**Python Booleans (bool)**
**Example**
**Example**
**Python Boolean Expression**
**Example**
**Python - Control Flow**
**Decision Making Statements**
**The if Statements**
**Example**
**The match Statement**
**Example**
**Loops or Iteration Statements**
**The for Loop**
**Example**
**The while Loop**
**Example**
**The break Statement**
**Example**
**The continue Statement**
**Example**
**Python - Decision Making**
**Types of Decision Making Statements in Python**
**Single Statement Suites**
**Example**
**Example**
**Nested if statements**
**Example**
**Python If Statement**
**Syntax of the if Statement**
**Example of Python if Statement**
**Python if else Statement**
**Syntax of if-else Statement**
**Flowchart of if-else Statement**
**Python if-else Statement Example**
**Python if elif else Statement**
**Syntax of Python if elif else Statement**
**How if elif else Works?**
**Example**
**Python if elif else Statement Example**
**Syntax of Nested if Statement**
**Flowchart of Nested if Statement**
**Nested if Statement with else Condition**
**Syntax**
**Example**
Python match-case Statement
Syntax
Example
Combined Cases in Match Statement
Example
Example
Using "if" in "Case" Clause
Example
Python Loops
Flowchart of a Loop
Python Loop Control Statements
Syntax of Python for Loop
Flowchart of Python for Loop
Example
Python for Loop with Tuples
Example
Python for Loop with Lists
Example
Python for Loop with Range Objects
Syntax
Example
Python for Loop with Dictionaries
Example
Example
Example
Using else Statement with For Loop
Example
Python - For Else Loop
Flowchart of For Else Loop
Syntax of For Else Loop
Example of For Else Loop
For-Else Construct without break statement
Example
Example
For-Else with break statement and if conditions
Example
Python while Loop
Syntax of while Loop
Flowchart of While loop
Example 1
Example 2
Python Infinite while Loop
Example
Flowchart of While loop with else Statement
Example
Single Statement Suites
Example
Python break Statement
Syntax of break Statement
break Statement with for loop
Example
break Statement with while loop
Example
break Statement with Nested Loops
Example
Python continue Statement
Syntax of continue Statement
Python continue Statement with for Loop
Example
Python continue Statement with while Loop
Example: Checking Prime Factors
Python pass Statement
Syntax of pass Statement
Example of pass Statement
Dumpy Infinite Loop with pass Statement
Example
Example
Python Nested for Loop
Python Nested for Loop Syntax
Python Nested for Loop Example
Python Nested while Loop
Python Nested while Loop Syntax
Python Nested while Loop Example
Types of Python Functions
Defining a Python Function
Syntax to Define a Python Function
Example to Define a Python Function
Example to Call a Python Function
Pass by Reference vs Value
Example
Example
Example
Python Function Arguments
Example
Types of Python Function Arguments
Positional or Required Arguments
Example
Keyword Arguments
Example 1
Example 2
Default Arguments
Example
Positional-only arguments
Example
Keyword-only arguments
Example
Arbitrary or Variable-length Arguments
Example
Order of Python Function Arguments
Python Function with Return Value
Example
The Anonymous Functions
Syntax
Example
Scope of Variables
Global vs. Local variables
Example
Python Default Arguments
Example of Default Arguments
Mutable Objects as Default Argument
Example
Keyword Arguments
Calling Function With Keyword Arguments
Example
Example
Example
Keyword-Only Arguments
Example of Keyword-Only Arguments
Using Keyword-Only argument in User-Defined Method
Example
Example
Positional Arguments
Positional Arguments Examples
Example 1
Example 2
Example 3
Example 4
Positional Only Arguments
Example
Positional-Only Arguments Examples
Example 1
Example 2
Example 3
Arbitrary Arguments (*args)
Arbitrary Arguments Example
Example
Arbitrary Keyword Arguments (**kwargs)
Example
Multiple Arguments With Arbitrary Keyword Arguments
Example
Types of Scope for Variables in Python
Local Variables
Example
Example
Nonlocal Variables
Example
Namespace and Scope of Python Variables
Python globals() Function
Example
Python locals() Function
Example
Namespace Conflict in Python
Example
Example
Example
Example
Function Annotations
Example
Function Annotations With Return Type
Example
Example
Function Annotations With Default Arguments
Example 1
Example 2
Example 3
Example 4
Python Modules
Example of Python Module
Python Built-in Modules
Creating a Python Module
The import Statement
The from ... import Statement
The from...import * Statement
The import ... as Statement
Locating Modules
The PYTHONPATH Variable
Namespaces and Scoping
Example
Module Attributes
Example
The nameAttribute
The dir( ) Function
The reload() Function
Packages in Python
Built-in Functions in Python?
How to Use Built-in Function in Python?
Example of Using Built-in Functions
Built-in Mathematical Functions
Advantages of Using Built-in Functions
Frequently Asked Questions about Built-in Functions
How do I handle errors with built-in functions?
Can we extend the functionality of built-in functions?
Can I create my built-in functions?
How do I use built-in functions?
Creating Python Strings
Example
Accessing Values in Strings
Escape Characters
String Special Operators
String Formatting Operator
Double Quotes in Python Strings
Example
Triple Quotes
Example
Python Multiline Strings
Example
Arithmetic Operators with Strings
Getting Type of Python Strings
Example
Built-in String Methods
Built-in Functions with Strings
Python String Indexing
Example
Python String Negative & Positive Indexing
Example
Example
Example
Python String Slicing With Negative Indexing
Example
Default Values of Indexes with String Slicing
Example
Example
Example
Example
Return Type of String Slicing
Example
Converting a String to a List
Example
Using the Array Module
Example
Example
Concatenate Strings in Python
String Concatenation using '+' operator
Example
Example
String Concatenation By Multiplying
Example
String Concatenation With '+' and '*' Operators
Example
Using % operator
Example
Using format() method
Example
Example
Using String Template class
Example
Escape Character
Example
Example
Escape Characters in Python
Case Conversion Methods
Alignment Methods
Boolean String Methods
Find and Replace Methods
Translation Methods
Example 1
Example 2
Example 3
Exercise Programs
QUESTIONS
What is Python?
Introduction to Python
Key Features of Python:
Popular Uses of Python:
Variables and Data Types: Questions
Questions and Answers
1. What is the result of adding an integer and a string?
2. How do you check the type of a variable in Python?
3. What is the difference between a list and a tuple?
4. How can you concatenate two strings in Python?
5. What is the output of the following code snippet?
6. How do you convert a float to an integer?
7. What will be the result of the following operation?
8. How do you check if a variable is of type list?
9. What is the difference between `==` and `is` in Python?
10. How do you create a dictionary in Python?
11. How do you convert a string to a float in Python?
12. What is the output of the following code?
13. How can you extract the integer part of a float?
14. What is the result of the following code?
15. How do you create an empty list in Python?
16. What will the following code output?
17. How do you check if a variable is of type integer?
18. How do you access the first element of a list?
19. What is the difference between a string and a list in Python?
20. How do you remove an item from a list by its value?
21. How do you find the type of a variable in Python?
22. What will the following code output?
23. How do you create a tuple with a single element?
24. What is the output of this code?
25. How do you check if a variable is a string?
26. How do you convert a list to a string?
27. What is the output of the following code?
28. How do you check if a variable is a number?
29. How do you convert an integer to a string?
30. What will the following code output?
31. How do you create a dictionary with integer keys and string values?
32. What will be the output of the following code?
33. How do you check if a variable is of type float?
34. What is the output of this code?
35. How do you convert a list of numbers to a list of strings?
36. What will be the result of the following code?
37. How do you convert a string to an integer?
38. What will be the output of the following code?
39. How do you find the length of a string?
40. What is the result of this code?
41. How do you concatenate two strings?
42. What will be the output of this code?
43. How do you convert a list of strings to a list of integers?
44. What is the output of the following code?
45. How do you create a tuple with a single element?
46. What will be the result of this code?
47. How do you check if a value is of type boolean?
48. What is the result of this code?
49. How do you create a set in Python?
50. What is the output of the following code?
51. How do you create a dictionary with default values?
52. How do you remove a key-value pair from a dictionary?
53. What is the result of this code?
54. How do you format a string with variable values?
55. What will be the output of this code?
56. How do you create a list of squares of numbers from 1 to 5?
57. What is the result of the following code?
58. How do you create a list from a string where each character is an element?
59. What will be the output of this code?
60. How do you create an empty set?
61. How do you check if a variable is of type integer?
62. How do you concatenate two strings?
63. What will be the result of the following code?
64. How do you create a tuple with a single element?
65. How do you convert a string to an integer?
66. What is the output of this code?
67. How do you create a list of numbers from 1 to 10?
68. How do you check if a value is in a list?
69. How do you convert a list of characters into a string?
70. What is the output of this code?
71. How do you find the type of a variable?
72. How do you create a list of tuples with paired elements?
73. How do you check the length of a string?
74. How do you remove duplicates from a list?
75. How do you sort a list in ascending order?
76. How do you find the maximum value in a list?
77. How do you split a string into a list of words?
78. How do you count the occurrences of a specific character in a string?
79. How do you reverse a list?
80. How do you find the index of a specific item in a list?
81. How do you create a dictionary with keys and values?
82. How do you get a list of all the keys in a dictionary?
83. How do you get a list of all the values in a dictionary?
84. How do you remove a key-value pair from a dictionary?
85. How do you merge two dictionaries?
86. How do you check if a key exists in a dictionary?
87. How do you iterate over a dictionary's keys and values?
88. How do you create a set in Python?
89. How do you add an element to a set?
90. How do you remove an element from a set?
91. How do you check if a set contains a specific element?
92. How do you clear all elements from a set?
93. How do you find the length of a set?
94. How do you perform a union operation on two sets?
95. How do you perform an intersection operation on two sets?
96. How do you perform a difference operation on two sets?
97. How do you perform a symmetric difference operation on two sets?
98. How do you check if one set is a subset of another?
99. How do you check if one set is a superset of another?
100. How do you remove duplicates from a list while preserving the original order?
101. How do you create a list with a fixed number of elements initialized to zero?
102. How do you find the index of the first occurrence of an element in a list?
103. How do you remove an element by value from a list?
104. How do you insert an element at a specific position in a list?
105. How do you reverse the order of elements in a list?
106. How do you sort a list in ascending order?
107. How do you create a tuple with elements?
108. How do you access an element in a tuple by index?
109. How do you concatenate two tuples?
110. How do you create a dictionary with keys and values?
111. How do you access a value in a dictionary by its key?
112. How do you add a new key-value pair to an existing dictionary?
113. How do you remove a key-value pair from a dictionary?
114. How do you get all the keys from a dictionary?
115. How do you get all the values from a dictionary?
116. How do you check if a key exists in a dictionary?
117. How do you create an empty dictionary?
118. How do you merge two dictionaries into one?
119. How do you create a set in Python?
120. How do you add an element to a set?
121. How do you remove an element from a set?
122. How do you check if an element exists in a set?
123. How do you get the length of a set?
124. How do you clear all elements from a set?
125. How do you find the intersection of two sets?
126. How do you find the union of two sets?
127. How do you find the difference between two sets?
128. How do you find the symmetric difference between two sets?
129. How do you create a set from a list?
130. How do you check if a set is a subset of another set?
131. How do you convert a string to an integer?
132. What is the result of dividing an integer by a float in Python?
133. How do you create a list of squares of numbers from 1 to 10?
134. How do you use the modulus operator in Python?
135. How do you use the power operator in Python?
136. How do you concatenate two strings in Python?
137. How do you find the length of a list in Python?
Control Structures
138. How do you use an `if` statement to check if a number is positive?
139. How do you use an `if-else` statement to determine if a number is even or odd?
140. How do you use a `for` loop to iterate over a list?
141. How do you use a `while` loop to print numbers from 1 to 5?
142. How do you handle errors using `try` and `except`?
143. How do you use `finally` to ensure code executes regardless of an error?
Functions and Modules
144. How do you define a function in Python?
145. How do you return multiple values from a function?
146. How do you use default arguments in a function?
147. How do you use keyword arguments in a function?
148. How do you import a module in Python?
149. How do you create your own module in Python?
Advanced Topics
150. How do you define a class in Python?
151. How do you inherit from a parent class in Python?
152. How do you read from a file in Python?
153. How do you write to a file in Python?
154. How do you install and use third-party libraries in Python?
Data Management
155. How do you connect to a SQLite database in Python?
156. How do you execute a SQL query using Python?
157. What is the SQL command to select all columns from a table?
158. How do you filter records in SQL using a `WHERE` clause?
159. How do you load a CSV file into a Pandas DataFrame?
160. How do you calculate the mean of a column in a Pandas DataFrame?
Web Development
161. How do you create a simple Flask application?
162. How do you add a new route in Flask?
Variables and Data Types
165. What are the basic data types in Python?
166. How do you convert a string to an integer in Python?
Operators
167. What is the result of using the `+` operator with strings?
168. How do you find the length of a list in Python?
Strings and Lists
169. How do you access the first character of a string in Python?
170. How do you create a list of the first 10 even numbers?
Conditional Statements
171. How do you write an `if` statement in Python?
172. How do you write an `if-else` statement in Python?
Loops
173. How do you write a `for` loop in Python?
174. How do you write a `while` loop in Python?
Error Handling
175. How do you handle exceptions in Python?
Functions and Modules
176. How do you define a function in Python?
177. How do you import a module in Python?
Object-Oriented Programming
178. How do you define a class in Python?
179. How do you create an instance of a class in Python?
File Handling
180. How do you read a file in Python?
181. How do you write to a file in Python?
Introduction to Databases
182. What is a database in Python?
183. How do you perform a simple SQL query in Python?
Control Structures
184. How do you use `if` statements in Python?
185. How do you use `for` loops in Python?
186. How do you handle errors using `try-except`?
Functions and Modules
187. How do you pass arguments to a function in Python?
188. How do you use modules in Python?
Object-Oriented Programming
189. How do you define a class in Python with attributes?
190. How do you create a method within a class in Python?
File Handling
191. How do you handle file paths in Python?
192. How do you read a file line by line in Python?
Introduction to Databases
193. How do you connect to a SQLite database in Python?
194. How do you create a table in a SQLite database?
SQL Basics
195. How do you insert data into a SQLite table?
196. How do you query data from a SQLite table?
Data Analysis with Pandas
197. How do you read a CSV file into a Pandas DataFrame?
198. How do you filter data in a Pandas DataFrame?
Introduction to Web Frameworks
199. What is Flask used for in web development?
200. How do you make a GET request to an API in Python?
Introduction to Web APIs
201. How do you post data to an API using Python?
202. How do you handle JSON data in Python?
Web Development Basics
203. What is a RESTful API?
204. How do you handle form data in a Flask web application?
Advanced Topics
205. How do you implement a class in Python?
206. How do you handle exceptions in Python?
207. How do you work with environment variables in Python?
208. How do you perform file I/O operations in Python?
209. How do you connect to a database in Python?
Data Management
210. What is SQL and how is it used with Python?
211. How do you use Pandas for data analysis in Python?
Web Development
212. What is Flask and how do you use it to create a web application?
213. How do you handle user authentication in Django?
214. How do you make a REST API request in Python using the `requests` library?
215. What is the purpose of a virtual environment in Python?
216. How do you use `pip` to install packages?
217. How do you create a simple API with Flask?
218. How do you debug a Python application?
Advanced Topics
219. What is Object-Oriented Programming (OOP) and how is it implemented in Python?
220. How do you handle file operations in Python?
221. How do you work with external libraries in Python?
Data Management
222. How do you perform basic SQL queries using SQLite in Python?
223. What are some common libraries used for data analysis in Python?
Web Development
224. How do you set up a basic Django project?
225. How do you make an API request using the `requests` library?
Data Management
226. How do you perform data analysis with Pandas?
227. What are SQL basics you need to know?
228. How do you connect to a SQL database using Python?
Web Development
229. What is the purpose of web frameworks like Flask and Django?
230. How do you handle user authentication in a Flask application?
Data Management (Continued)
231. How do you perform basic SQL operations in a database?
232. How do you handle errors in a Python program?
Functions and Modules
233. How do you define a function in Python?
234. How do you import and use modules in Python?
235. How do you create a module in Python?
236. How do you define a function with default arguments?
Advanced Topics
237. What is Object-Oriented Programming (OOP) in Python?
238. How do you implement inheritance in Python?
239. What is polymorphism in Python?
240. How do you implement encapsulation in Python?
Project 1: Basic Calculator
Question:
Project 2: To-Do List
Question:
Project 3: Number Guessing Game
Question:
Project 4: Simple Password Generator
Question:
Project 5: BMI Calculator
Question:
Project 6: Prime Number Checker
Question:
Project 7: Currency Converter
Question:
Project 8: Text File Reader
Question:
Project 9: Email Validator
Question:
Project 10: Rock, Paper, Scissors Game
Question:
Project 11: Simple Quiz
Question:
Project 12: Number Guessing Game
Question:
Project 13: Contact Book
Question:
Project 14: To-Do List
Question:
Project 15: Basic Calculator
Question:
Project 16: Temperature Converter
Question:
Project 17: Palindrome Checker
Question:
Project 18: Simple Bank Account
Question:
Project 19: Countdown Timer
Question:
Project 20: Random Password Generator
Question:
Project 21: Contact Book
Question:
Project 22: Unit Converter
Question:
Project 23: Todo List Application
Question:
Project 24: Basic Calculator
Question:
Project 25: Weather App
Question:
Project 26: Quiz Game
Question:
Project 27: Expense Tracker
Question:
Project 28: Digital Diary
Question:
Project 29: Password Generator
Question:
Project 30: Number Guessing Game
Question:
Project 31: Currency Converter
Question:
Project 32: Task Manager
Question:
Project 33: Calendar Application
Question:
Project 34: Recipe Book
Question:
Project 35: Alarm Clock
Question:
Project 36: Weather Dashboard
Question:
Project 37: Personal Budget Tracker
Question:
Project 38: Habit Tracker
Question:
Project 39: Simple Chatbot
Question:
Project 40: Markdown to HTML Converter
Question:
Project 41: Password Generator
Question:
Project 42: Contact Book
Question:
Project 43: Expense Tracker
Question:
Project 44: Online Quiz
Question:
Project 45: To-Do List Manager
Question:
Project 46: URL Shortener
Question:
Project 47: Currency Converter
Question:
Project 48: Calendar Event Organizer
Question:
Project 49: Simple Email Sender
Question:
Project 50: Basic Calculator
Question:
Project 51: Binary Search Algorithm
Question:
Project 52: Simple Password Generator
Question:
Project 53: Sudoku Solver
Question:
Project 54: Markdown to HTML Converter
Question:
Project 55: Quiz Application
Question:
Project 56: Weather Information Fetcher
Question:
Project 57: Expense Tracker
Question:
Project 58: Simple Chatbot
Question:
Project 59: Email Sender
Question:
Project 60: URL Shortener
Question:
Project 61: Personal Diary
Question:
Project 62: Random Password Generator
Question:
Project 63: Unit Converter
Question:
Project 64: Tic-Tac-Toe Game
Question:
Project 65: Email Sender
Question:
Project 66: URL Shortener
Question:
Project 67: Expense Tracker
Question:
Project 68: Currency Converter
Question:
Project 69: Stopwatch
Question:
Project 70: Alarm Clock
Question:
Project 71: To-Do List
Question:
Project 72: Simple Calculator
Question:
Project 73: Weather App
Question:
Project 74: Quiz Game
Question:
Project 75: Simple Chatbot
Question:
Project 76: Fibonacci Sequence Generator
Question:
Project 77: Palindrome Checker
Question:
Project 78: Prime Number Checker
Question:
Project 79: Word Frequency Counter
Question:
Project 80: Simple To-Do List
Question:
Project 81: Simple Bank Account
Question:
Project 82: Basic Todo List with File I/O
Question:
Project 83: Simple Budget Tracker
Question:
Project 84: Number Guessing Game
Question:
Project 85: Basic Contact Book
Question:
Project 86: Currency Converter
Question:
Project 87: Simple Calculator
Question:
Project 88: Prime Number Checker
Question:
Project 89: Temperature Converter
Question:
Project 90: Simple Quiz Game
Question:
Project 91: Simple Stopwatch
Question:
Project 92: Basic To-Do List with Persistence
Question:
Project 93: Simple Number Guessing Game
Question:
Project 94: Simple File Reader
Question:
Project 95: Basic Unit Converter
Question:
Project 96: Simple Expense Tracker
Question:
Project 97: Simple Interest Calculator
Question:
Project 98: Basic Temperature Converter
Question:
Project 99: Simple Calculator with GUI
Question:
Project 100: Simple Contact Book
Question:
A Note to My Readers

About the Author


Anshu Goyal is a dedicated computer science educator with a passion for making technology accessible and understandable to everyone. With a deep
understanding of programming, web development, data science, and cybersecurity, Anshu has built a reputation for creating comprehensive, easy-to-follow
learning materials.

Anshu holds advanced knowledge in Python programming, Java, SQL, and web development technologies, and has hands-on experience with
educational software, data management systems, and digital tools for both teaching and automation. Over the years, Anshu has designed multiple educational
courses, tutorials, and books, aimed at empowering students and professionals alike.

Apart from teaching, Anshu actively explores the ever-evolving world of technology, including AI, machine learning, and cybersecurity, ensuring that
the content provided is always up-to-date and relevant.

In addition to his teaching career, Anshu is a passionate advocate for educational accessibility and works towards creating tools that make learning more
interactive, engaging, and effective. His dedication to the tech community and innovative mindset have allowed him to share valuable insights through
platforms like Udemy, YouTube, and his personal website.

When he’s not immersed in the world of computers, Anshu enjoys hiking, cooking, and exploring new technologies in his spare time.

Connect with Anshu Goyal:

Website: Anshu Goyal - Personal


LinkedIn: Anshu Goyal - LinkedIn

Udemy: Anshu Goyal - Udemy


Copyright Page
Copyright © 2024 by Anshu Goyal
All rights reserved.

No part of this publication may be reproduced, distributed, or transmitted in any form or by any means, including photocopying, recording, or any
information storage and retrieval system, without the prior written permission of the author, except for brief quotations used in critical reviews or articles.
Unauthorized use or reproduction of any part of this book is prohibited and may result in legal action.

This book is protected by international copyright laws, and any unauthorized use, reproduction, or distribution of this material is strictly prohibited.

For permission requests, please contact the author at:


Email: codemasteranshu@[Link]

Disclaimer: The information in this book is provided "as is." While every effort has been made to ensure the accuracy of the content, the author makes
no representations or warranties regarding the accuracy, completeness, or suitability of the information provided for any particular purpose. The author and
publisher shall not be liable for any damages arising from the use of this book.

Python Tutorial
Today, Python is one of the most popular programming languages. Although it is a general-purpose language, it is used in various areas of applications
such as Machine Learning, Artificial Intelligence, web development, IoT, and more.

This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After
completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world
class Software Engineer.

This Python tutorial is based on the latest Python 3.11.2 version.

What is Python?
Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-level programming language. Python is dynamically-typed
and garbage-collected programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under
the GNU General Public License (GPL).

Python supports multiple programming paradigms, including Procedural, Object Oriented and Functional programming language. Python design
philosophy emphasizes code readability with the use of significant indentation.

This tutorial gives a complete understanding of Python programming language starting from basic conceopts to advanced concepts. This tutorial will
take you through simple and practical approaches while learning Python Programming language.

Today, Python is very high in demand and all the major companies are looking for great Python Programmers to develop websites, software components,
and applications or to work with Data Science, AI, and ML technologies. When we are developing this tutorial in 2022, there is a high shortage of Python
Programmers where as market demands more number of Python Programmers due to it's application in Machine Learning, Artificial Intelligence etc.

Today a Python Programmer with 3-5 years of experience is asking for around $150,000 annual package and this is the most demanding programming
language in America. Though it can vary depending on the location of the Job. It's impossible to list all of the companies using Python, to name a few big
companies are:

Google

Intel

NASA

PayPal
Facebook

IBM

Amazon
Netflix

Pinterest
Uber

Many more...

So, you could be the next potential employee for any of these major companies. We have developed a great learning material for you to learn Python
Programming which will help you prepare for the technical interviews and certification exams based on Python. So, start learning Python using this simple
and effective tutorial from anywhere and anytime absolutely at your pace.

Why to Learn Python?


Python is consistently rated as one of the world's most popular programming languages. Python is fairly easy to learn, so if you are starting to learn any
programming language then Python could be your great choice. Today various Schools, Colleges and Universities are teaching Python as their primary
programming language. There are many other good reasons which makes Python as the top choice of any programmer:

Python is Open Source which means its available free of cost.


Python is simple and so easy to learn

Python is versatile and can be used to create many different things.


Python has powerful development libraries include AI, ML etc.

Python is much in demand and ensures high salary

Python is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development
Domain. I will list down some of the key advantages of learning Python:

Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is
similar to PERL and PHP.

Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.

Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects.

Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.

Python Online Compiler


Our Python programming tutorial provides various examples to explain different concepts. We have provided Online Python Compiler/Interpreter. You
can Edit and Execute almost all the examples directly from your browser without the need to set up your development environment.

Below code box allows you to change the value of the code. Try to change the value inside print() and run it again to verify the result.

1 # This is my first Python program.


2 # This will print 'Hello, World!' as the output
3
4 print ("Hello, World!");

Careers with Python


If you know Python nicely, then you have a great career ahead. Here are just a few of the career options where Python is a key skill:

Game developer
Web designer

Python developer
Full-stack developer

Machine learning engineer


Data scientist
Data analyst

Data engineer
DevOps engineer

Software engineer
Many more other roles

Characteristics of Python
Following are important characteristics of Python Programming −

It supports functional and structured programming methods as well as OOP.

It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.

It supports automatic garbage collection.

It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Applications of Python
Python is a general purpose programming language known for its readability. It is widely applied in various fields.

In Data Science, Python libraries like Numpy, Pandas, and Matplotlib are used for data analysis and visualization.
Python frameworks like Django, and Pyramid, make the development and deployment of Web Applications easy.

This programming language also extends its applications to computer vision and image processing.
It is also favored in many tasks like Automation , Job Scheduling, GUI development, etc.

Features of Python
The latest release of Python is 3.x. As mentioned before, Python is one of the most widely used language over the web. I'm going to list few of them
here:

Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language quickly.

Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.

A broad standard library − Python's bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactive testing and debugging of snippets of code.

Portable − Python can run on a wide variety of hardware platforms and has the same interface on all platforms.

Extendable − You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be
more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and ported to many system calls, libraries and windows systems, such as
Windows MFC, Macintosh, and the X Window system of Unix.

Scalable − Python provides a better structure and support for large programs than shell scripting.

Target Audience
This tutorial has been prepared for the beginners to help them understand the basics to advanced concepts of Python programming language. After
completing this tutorial, you will find yourself at a great level of expertise in Python programming, from where you can take yourself to the next levels.
Prerequisites
Although it is a beginners tutorial, we assume that the readers have a reasonable exposure to any programming environment and knowledge of basic
concepts such as variables, commands, syntax, etc.

Python - Overview
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords
frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is
similar to PERL and PHP.

Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects.

Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.

Python is an open-source and cross-platform programming language. It is available for use under Python Software Foundation License (compatible to
GNU General Public License) on all the major operating system platforms Linux, Windows and Mac OS.

To facilitate new features and to maintain that readability, the Python Enhancement Proposal (PEP) process was developed. This process allows anyone
to submit a PEP for a new feature, library, or other addition.

The design philosophy of Python emphasizes on simplicity, readability and unambiguity. Python is known for its batteries included approach as Python
software is distributed with a comprehensive standard library of functions and modules.

Python's design philosophy is documented in the Zen of Python . It consists of nineteen aphorisms such as −

Beautiful is better than ugly

Explicit is better than implicit


Simple is better than complex

Complex is better than complicated

To obtain the complete Zen of Python document, type import this in the Python Shell −

1 >>>import this

This will produce following 19 aphorisms -

1 Beautiful is better than ugly.


2 Explicit is better than implicit.
3 Simple is better than complex.
4 Complex is better than complicated.
5 Flat is better than nested.
6 Sparse is better than dense.
7 Readability counts.
8 Special cases aren't special enough to break the rules.
9 Although practicality beats purity.
10 Errors should never pass silently.
11 Unless explicitly silenced.
12 In the face of ambiguity, refuse the temptation to guess.
13 There should be one-- and preferably only one --obvious way to do it.
14 Although that way may not be obvious at first unless you're Dutch.
15 Now is better than never.
16 Although never is often better than *right* now.
17 If the implementation is hard to explain, it's a bad idea.
18 If the implementation is easy to explain, it may be a good idea.
19 Namespaces are one honking great idea -- let's do more of those!

Python supports imperative, structured as well as object-oriented programming methodology. It provides features of functional programming as well.
Pythonic Code Style
Python leaves you free to choose to program in an object-oriented, procedural, functional, aspect-oriented, or even logic-oriented way. These freedoms
make Python a great language to write clean and beautiful code.

Pythonic Code Style is actually more of a design philosophy and suggests to write a code which is :

Clean

Simple

Beautiful

Explicit

Readable

The Zen of Python


The Zen of Python is about code that not only works, but is Pythonic. Pythonic code is readable, concise, and maintainable.

Python - History
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer
Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL).

For many uninitiated people, the word Python is related to a species of snake. Rossum though attributes the choice of the name Python to a popular
comedy series Monty Python's Flying Circus on BBC.

Being the principal architect of Python, the developer community conferred upon him the title of Benevolent Dictator for Life (BDFL). However, in
2018, Rossum relinquished the title. Thereafter, the development and distribution of the reference implementation of Python is handled by a nonprofit
organization Python Software Foundation .

Who Invented Python?


Python was invented by a Dutch Programmer Guido Van Rossum in the late 1980s. And, Python's first version (0.9.0) was released in 1991.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Evolution of Python – The Major Python Releases

Following are the important stages in the history of Python −

Python 0.9.0
Python's first published version is 0.9. It was released in February 1991. It consisted of support for core object-oriented programming principles.
Python 1.0
In January 1994, version 1.0 was released, armed with functional programming tools, features like support for complex numbers etc.

Python 2.0
Next major version − Python 2.0 was launched in October 2000. Many new features such as list comprehension, garbage collection and Unicode support
were included with it.

Python 3.0
Python 3.0, a completely revamped version of Python was released in December 2008. The primary objective of this revamp was to remove a lot of
discrepancies that had crept in Python 2.x versions. Python 3 was backported to Python 2.6. It also included a utility named as python2to3 to facilitate
automatic translation of Python 2 code to Python 3.

EOL for Python 2.x


Even after the release of Python 3, Python Software Foundation continued to support the Python 2 branch with incremental micro versions till 2019.
However, it decided to discontinue the support by the end of year 2020, at which time Python 2.7.17 was the last version in the branch.

Current Version of Python


Meanwhile, more and more features have been incorporated into Python's 3.x branch. As of date, Python 3.11.2 is the current stable version, released in
February 2023.

What's New in Python 3.11?


One of the most important features of Python's version 3.11 is the significant improvement in speed. According to Python's official documentation, this
version is faster than the previous version (3.10) by up to 60%. It also states that the standard benchmark suite shows a 25% faster execution rate.

Python 3.11 has a better exception messaging. Instead of generating a long traceback on the occurrence of an exception, we now get the exact
expression causing the error.

As per the recommendations of PEP 678, the add_note() method is added to the BaseException class. You can call this method inside the except
clause and pass a custom error message.
It also adds the cbroot() function in the maths module. It returns the cube root of a given number.
A new module tomllib is added in the standard library. TOML (Tom's Obvious Minimal Language) can be parsed with tomlib module function.

Frequently Asked Questions About Python History

1. Who created Python?


Python created by Guido Van Rossum, a Dutch Programmer.
2. Why Python is called Python?
Python does not have any relation to Snake. The name of the Python programming language was inspired by a British Comedy Group Monty Python.

3. When was Python's first version released?


Python's first version was released in February 1991.

4. What was the first version of Python?


Python's first version was Python 0.9.0

5. When was Python 3.0 version released?


Python 3.0 version was released in December 2018.

Python - Features
Python is a feature-rich, high-level, interpreted, interactive, and object-oriented scripting language. Python is a versatile and very popular programming
language due to its features such as readability, simplicity, extensive libraries, and many more. In this tutorial, we will learn about the various features of
Python that make it a powerful and versatile programming language.

Python's most important features are as follows:

Easy to Learn

Dynamically Typed
Interpreter Based

Interactive
Multi-paradigm
Standard Library

Open Source and Cross Platform

GUI Applications
Database Connectivity

Active Developer Community


Extensible

Easy to Learn
This is one of the most important reasons for the popularity of Python. Python has a limited set of keywords. Its features such as simple syntax, usage of
indentation to avoid clutter of curly brackets and dynamic typing that doesn't necessitate prior declaration of variable help a beginner to learn Python quickly
and easily.

Dynamically Typed
Python is a dynamically typed programming language. In Python, you don't need to specify the variable time at the time of the variable declaration. The
types are specified at the runtime based on the assigned value due to its dynamically typed feature.
Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Interpreter Based

Instructions in any programming languages must be translated into machine code for the processor to execute them. Programming languages are either
compiler based or interpreter based.

In case of a compiler, a machine language version of the entire source program is generated. The conversion fails even if there is a single erroneous
statement. Hence, the development process is tedious for the beginners. The C family languages (including C, C++, Java, C# etc) are compiler based.

Python is an interpreter based language. The interpreter takes one instruction from the source code at a time, translates it into machine code and executes
it. Instructions before the first occurrence of error are executed. With this feature, it is easier to debug the program and thus proves useful for the beginner
level programmer to gain confidence gradually. Python therefore is a beginner-friendly language.

Interactive
Standard Python distribution comes with an interactive shell that works on the principle of REPL (Read – Evaluate – Print – Loop). The shell presents a
Python prompt >>>. You can type any valid Python expression and press Enter. Python interpreter immediately returns the response and the prompt comes
back to read the next expression.

1 >>> 2*3+1
2 7
3 >>> print ("Hello World")
4 Hello World

The interactive mode is especially useful to get familiar with a library and test out its functionality. You can try out small code snippets in interactive
mode before writing a program.

Multi-paradigm
Python is a completely object-oriented language. Everything in a Python program is an object. However, Python conveniently encapsulates its object
orientation to be used as an imperative or procedural language – such as C. Python also provides certain functionality that resembles functional programming.
Moreover, certain third-party tools have been developed to support other programming paradigms such as aspect-oriented and logic programming.

Standard Library
Even though it has a very few keywords (only Thirty Five), Python software is distributed with a standard library made of large number of modules and
packages. Thus Python has out of box support for programming needs such as serialization, data compression, internet data handling, and many more. Python
is known for its batteries included approach.

Some of the Python's popular modules are:

NumPy

Pandas
Matplotlib

Tkinter

Math

Open Source and Cross Platform


Python's standard distribution can be downloaded from [Link] without any restrictions. You can download pre-compiled
binaries for various operating system platforms. In addition, the source code is also freely available, which is why it comes under open source category.

Python software (along with the documentation) is distributed under Python Software Foundation License. It is a BSD style permissive software license
and compatible to GNU GPL (General Public License).

Python is a cross-platform language. Pre-compiled binaries are available for use on various operating system platforms such as Windows, Linux, Mac
OS, Android OS. The reference implementation of Python is called CPython and is written in C. You can download the source code and compile it for your
OS platform.
A Python program is first compiled to an intermediate platform independent byte code. The virtual machine inside the interpreter then executes the byte
code. This behaviour makes Python a cross-platform language, and thus a Python program can be easily ported from one OS platform to other.

GUI Applications
Python's standard distribution has an excellent graphics library called TKinter. It is a Python port for the vastly popular GUI toolkit called TCL/Tk. You
can build attractive user-friendly GUI applications in Python. GUI toolkits are generally written in C/C++. Many of them have been ported to Python.
Examples are PyQt, WxWidgets, PySimpleGUI etc.

Database Connectivity
Almost any type of database can be used as a backend with the Python application. DB-API is a set of specifications for database driver software to let
Python communicate with a relational database. With many third party libraries, Python can also work with NoSQL databases such as MongoDB.

Extensible
The term extensibility implies the ability to add new features or modify existing features. As stated earlier, CPython (which is Python's reference
implementation) is written in C. Hence one can easily write modules/libraries in C and incorporate them in the standard library. There are other
implementations of Python such as Jython (written in Java) and IPython (written in C#). Hence, it is possible to write and merge new functionality in these
implementations with Java and C# respectively.

Active Developer Community


As a result of Python's popularity and open-source nature, a large number of Python developers often interact with online forums and conferences.
Python Software Foundation also has a significant member base, involved in the organization's mission to " Promote, Protect, and Advance the Python
Programming Language "

Python also enjoys a significant institutional support. Major IT companies Google, Microsoft, and Meta contribute immensely by preparing
documentation and other resources.

Apart from the above-mentioned features, Python has another big list of good features, few are listed below −

It supports functional and structured programming methods as well as OOP.

It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.

It supports automatic garbage collection.

It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

Python vs C++
Python is a general-purpose, high-level programming language. Python is used for web development, Machine Learning, and other cutting-edge software
development. Python is suitable for both new and seasoned C++ and Java programmers. Guido Van Rossam has created Python in 1989 at Netherlands'
National Research Institute. Python was released in 1991.

C++ is a middle-level, case-sensitive, object-oriented programming language. Bjarne Stroustrup created C++ at Bell Labs. C++ is a platform-
independent programming language that works on Windows, Mac OS, and Linux. C++ is near to hardware, allowing low-level programming. This provides a
developer control over memory, improved performance, and dependable software.

Read through this article to get an overview of C++ and Python and how these two programming languages are different from each other.
What is Python?
Python is currently one of the most widely used programming languages. It is an interpreted programming language that operates at a high level. When
compared to other languages, the learning curve for Python is much lower, and it is also quite straightforward to use.

Python is the programming language of choice for professionals working in fields such as Artificial Intelligence, Machine Learning (ML), Data Science,
the Internet of Things (IoT), etc., because it excels at both scripting applications and as standalone programmes.

In addition to this, Python is the language of choice because it is easy to learn. Because of its excellent syntax and readability, the amount of money
spent on maintenance is decreased. The modularity of the programme and the reusability of the code both contribute to its support for a variety of packages
and modules.

Using Python, we can perform −

Web development
Data analysis and machine learning

Automation and scripting


Software testing and many more

Features
Here is a list of some of the important features of Python −

Easy to learn − Python has a simple structure, few keywords, and a clear syntax. This makes it easy for the student to learn quickly. Code written in
Python is easier to read and understand.
Easy to maintain − The source code for Python is pretty easy to keep up with.

A large standard library − Most of Python's library is easy to move around and works on UNIX, Windows, Mac.

Portable − Python can run on a wide range of hardware platforms, and all of them have the same interface.

Python Example
Take a look at the following simple Python program −

1 a = int(input("Enter value for a"))


2 b = int(input("Enter value for b"))
3
4 print("The number you have entered for a is ", a)
5 print("The number you have entered for b is ", b)

In our example, we have taken two variables "a" and "b" and assigning some value to those variables. Note that in Python, we don’t need to declare
datatype for variables explicitly, as the PVM will assign datatype as per the user’s input.

The input() function is used to take input from the user through keyboard.
In Python, the return type of input() is string only, so we have to convert it explicitly to the type of data which we require. In our example, we have
converted to int type explicitly through int( ) function.
print() is used to display the output.

Output
On execution, this Python code will produce the following output −

1 Enter value for a 10


2 Enter value for b 20
3
4 The number you have entered for a is 10
5 The number you have entered for b is 20
What is C++?
C++ is a statically typed, compiled, multi-paradigm, general-purpose programming language with a steep learning curve. Video games, desktop apps,
and embedded systems use it extensively. C++ is so compatible with C that it can build practically all C source code without any changes. Object-oriented
programming makes C++ a better-structured and safer language than C.

Features
Let’s see some features of C++ and the reason of its popularity.

Middle-level language − It's a middle-level language since it can be used for both systems development and large-scale consumer applications like
Media Players, Photoshop, Game Engines, etc.

Execution Speed − C++ code runs quickly. Because it's compiled and uses procedures extensively. Garbage collection, dynamic typing, and other
modern features impede program execution.
Object-oriented language − Object-oriented programming is flexible and manageable. Large apps are possible. Growing code makes procedural
code harder to handle. C++'s key advantage over C.

Extensive Library Support − C++ has a vast library. Third-party libraries are supported for fast development.

C++ Example
Let’s understand the syntax of C++ through an example written below.

1 #include
2 using namespace std;
3
4 int main() {
5 int a, b;
6 cout << "Enter The value for variable a \n";
7 cin >> a;
8 cout << "Enter The value for variable b";
9 cin >> b;
10 cout << "The value of a is "<< a << "and" << b;
11 return 0;
12 }

In our example, we are taking input for two variables "a" and "b" from the user through the keyboard and displaying the data on the console.

Output
On execution, it will produce the following output −

1 Enter The value for variable a


2 10
3 Enter The value for variable b
4 20
5 The value of a is 10 and 20

Comparison Between Python and C++ across Various Aspects


Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this tutorial, we
shall take a closure look at their characteristic features which differentiate one from another.
Compiled vs Interpreted
Like C, C++ is also a compiler-based language. A compiler translates the entire code in a machine language code specific to the operating system in use
and processor architecture.

Python is interpreter-based language. The interpreter executes the source code line by line.

Cross platform
When a C++ source code such as [Link] is compiled on Linux, it can be only run on any other computer with Linux operating system. If required to
run on other OS, it needs to be compiled.

Python interpreter doesn't produce compiled code. Source code is converted to byte code every time it is run on any operating system without any
changes or additional steps.

Portability
Python code is easily portable from one OS to other. C++ code is not portable as it must be recompiled if the OS changes.

Speed of Development
C++ program is compiled to the machine code. Hence, its execution is faster than interpreter based language.

Python interpreter doesn't generate the machine code. Conversion of intermediate byte code to machine language is done on each execution of program.

If a program is to be used frequently, C++ is more efficient than Python.

Easy to Learn
Compared to C++, Python has a simpler syntax. Its code is more readable. Writing C++ code seems daunting in the beginning because of complicated
syntax rule such as use of curly braces and semicolon for sentence termination.

Python doesn't use curly brackets for marking a block of statements. Instead, it uses indents. Statements of similar indent level mark a block. This makes
a Python program more readable.

Static vs Dynamic Typing


C++ is a statically typed language. The type of variables for storing data need to be declared in the beginning. Undeclared variables can't be used. Once a
variable is declared to be of a certain type, value of only that type can be stored in it.

Python is a dynamically typed language. It doesn't require a variable to be declared before assigning it a value. Since, a variable may store any type of
data, it is called dynamically typed.

OOP Concepts
Both C++ and Python implement object oriented programming concepts. C++ is closer to the theory of OOP than Python. C++ supports the concept of
data encapsulation as the visibility of the variables can be defined as public, private and protected.

Python doesn't have the provision of defining the visibility. Unlike C++, Python doesn't support method overloading. Because it is dynamically typed, all
the methods are polymorphic in nature by default.

C++ is in fact an extension of C. One can say that additional keywords are added in C so that it supports OOP. Hence, we can write a C type procedure
oriented program in C++.
Python is completely object oriented language. Python's data model is such that, even if you can adapt a procedure oriented approach, Python internally
uses object-oriented methodology.

Garbage Collection
C++ uses the concept of pointers. Unused memory in a C++ program is not cleared automatically. In C++, the process of garbage collection is manual.
Hence, a C++ program is likely to face memory related exceptional behavior.

Python has a mechanism of automatic garbage collection. Hence, Python program is more robust and less prone to memory related issues.

Application Areas
Because C++ program compiles directly to machine code, it is more suitable for systems programming, writing device drivers, embedded systems and
operating system utilities.

Python program is suitable for application programming. Its main area of application today is data science, machine learning, API development etc.

Difference Between Python and C++


The following table summarizes the differences between Python and C++ −

Criteria Python C++

Execution Python is an interpreted-based programming language. Python C++ is a compiler-based programming language. C++ programs
programs are interpreted by an interpreter. are compiled by a compiler.

Typing Python is a dynamic-typed language. C++ is a static-typed language.

Portability Python is a highly portable language, code written and executed C++ is not a portable language, code written and executed on a
on a system can be easily run on another system. system cannot be run on another system without making changes.

Garbage Python provides a garbage collection feature. You do not need to C++ does not provide garbage collection. You have to take care of
collection worry about the memory management. It is automatic in Python. freeing memories. It is manual in C++.

Syntax Python's syntaxes are very easy to read, write, and understand. C++'s syntaxes are tedious.

Performance Python's execution performance is slower than C++'s. C++ codes are faster than Python codes.

Application Python's application areas are machine learning, web applications, C++'s application areas are embedded systems, device drivers,
areas and more. and more.

Python - Hello World Program


This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of Python
built-in print() function to print the string.

Hello World Program in Python


Printing "Hello World" is the first program in Python. This program will not take any user input, it will just print text on the output screen. It is used to
test if the software needed to compile and run the program has been installed correctly.
Steps
The following are the steps to write a Python program to print Hello World –

Step 1: Install Python. Make sure that Python is installed on your system or not. If Python is not installed, then install it from here:
[Link]
Step 2: Choose Text Editor or IDE to write the code.

Step 3: Open Text Editor or IDE, create a new file, and write the code to print Hello World.

Step 4: Save the file with a file name and extension ".py".

Step 5: Compile/Run the program.

1 # Python code to print "Hello World"


2 print ("Hello World")

In the above code, we wrote two lines. The first line is the Python comment that will be ignored by the Python interpreter, and the second line is the
print() statement that will print the given message ("Hello World") on the output screen.

Output-

1 Hello World

Different Ways to Write and Execute Hello World Program

Using Python Interpreter Command Prompt Mode


It is very easy to display the Hello World message using the Python interpreter. Launch the Python interpreter from a command terminal of your
Windows Operating System and issue the print statement from the Python prompt as follows −

Example

1 PS C:\> pyhton
2 Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32
3 Type "help", "copyright", "credits" or "license" for more information.
4
5 >>> print ("Hello World")
6 Hello World

Similarly, Hello World message is printed on Linux System.

Example

1 $ python3
2 Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
3 Type "help", "copyright", "credits" or "license" for more information.
4
5 >>> print ("Hello World")
6 Hello World

Using Python Interpreter Script Mode


Python interpreter also works in scripted mode. Open any text editor, enter the following text and save as [Link]

print ("Hello World")

For Windows OS, open the command prompt terminal (CMD) and run the program as shown below −

C:\>python [Link]

This will display the following output


1 Hello World

To run the program from Linux terminal

$ python3 [Link]

This will display the following output

1 Hello World

Using Shebang #! in Linux Scripts


In Linux, you can convert a Python program into a self executable script. The first statement in the code should be a shebang #! . It must contain the
path to Python executable. In Linux, Python is installed in /usr/bin directory, and the name of the executable is python3. Hence, we add this statement to
[Link] file

Open Compiler

#!/usr/bin/python3

print ("Hello World")

You also need to give the file executable permission by using the chmod +x command

1 $ chmod +x [Link]

Then, you can run the program with following command line −

1 $ ./[Link]

This will display the following output

1 Hello World

FAQs

1. Why the first program is called Hello World?


It is just a simple program to test the basic syntax and compiler/interpreter configuration of Python programming language.

2. Installation of Python is required to run Hello World program?


Yes. Python installation is required to run Hello World program.

3. How do I run a Python program without installing it?


TutorialsPoint developed an online environment where you can run your codes. You can use the Python online compiler to run your Python programs.

4. First Program Vs Hello World Program in Python?


There is no difference. The first program of Python is generally known as the Hello World program.
5. Which is/are the method to print Hello World or any message?
You can use the following methods –

print() method
[Link]() method by importing the sys module
Using python-f string

Python - Application Areas


Python is a general-purpose programming language. It is suitable for the development of a wide range of software applications. Over the last few years
Python has been the preferred language of choice for developers in the following application areas −

Data Science
Machine Learning
Web Development
Computer Vision and Image processing
Embedded Systems and IoT
Job Scheduling and Automation
Desktop GUI Applications
Console-based Applications
CAD Applications
Game Development

Let's look into these application areas in more detail:

Data Science
Python's recent meteoric rise in the popularity charts is largely due to its Data science libraries. Python has become an essential skill for data scientists. Today,
real time web applications, mobile applications and other devices generate huge amount of data. Python's data science libraries help companies generate
business insights from this data.

Libraries like NumPy, Pandas, and Matplotlib are extensively used to apply mathematical algorithms to the data and generate visualizations. Commercial and
community Python distributions like Anaconda and ActiveState bundle all the essential libraries required for data science.

Machine Learning
Python libraries such as Scikit-learn and TensorFlow help in building models for prediction of trends like customer satisfaction, projected values of stocks etc.
based upon the past data. Machine learning applications include (but not restricted to) medical diagnosis, statistical arbitrage, basket analysis, sales prediction
etc.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.## Web
Development

Python's web frameworks facilitate rapid web application development. Django, Pyramid, Flask are very popular among the web developer community. etc.
make it very easy to develop and deploy simple as well as complex web applications.

Latest versions of Python provide asynchronous programming support. Modern web frameworks leverage this feature to develop fast and high performance
web apps and APIs.

Computer Vision and Image processing


OpenCV is a widely popular library for capturing and processing images. Image processing algorithms extract information from images, reconstruct image
and video data. Computer Vision uses image processing for face detection and pattern recognition. OpenCV is a C++ library. Its Python port is extensively
used because of its rapid development feature.

Some of the application areas of computer vision are robotics, industrial surveillance, automation, and biometrics etc.
Embedded Systems and IoT
Micropython ([Link] a lightweight version especially for microcontrollers like Arduino. Many automation products, robotics, IoT, and
kiosk applications are built around Arduino and programmed with Micropython. Raspberry Pi is also very popular alow cost single board computer used for
these type of applications.

Job Scheduling and Automation


Python found one of its first applications in automating CRON (Command Run ON) jobs. Certain tasks like periodic data backups, can be written in Python
scripts scheduled to be invoked automatically by operating system scheduler.

Many software products like Maya embed Python API for writing automation scripts (something similar to Excel micros).

Desktop GUI Applications


Python is a great option for building ergonomic, attractive, and user-friendly desktop GUI applications. Several graphics libraries, though built in C/C++,
have been ported to Python. The popular Qt graphics toolkit is available as a PyQt package in Python. Similarly, WxWidgets has been ported to Python as
WxPython. Python's built-in GUI package, TKinter is a Python interface to the Tk Graphics toolkit.

Here is a select list of Python GUI libraries:

Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python's standard library.
wxPython − This is the Python interface for the wxWidgets GUI toolkit. BitTorrent Client application has been built with wxPython functionality.
PyQt – Qt is one of the most popular GUI toolkits. It has been ported to Python as a PyQt5 package. Notable desktop GUI apps that use PyQt include
QGIS, Spyder IDE, Calibre Ebook Manager, etc.
PyGTK − PyGTK is a set of wrappers written in Python and C for GTK + GUI library. The complete PyGTK tutorial is available here.
PySimpleGUI − PySimpleGui is an open-source, cross-platform GUI library for Python. It aims to provide a uniform API for creating desktop GUIs based
on Python's Tkinter, PySide, and WxPython toolkits.
Jython − Jython is a Python port for Java, which gives Python scripts seamless access to the Java GUI libraries on the local machine.

Console-based Applications
Python is often employed to build CLI (command-line interface) applications. Such scripts can be used to run scheduled CRON jobs such as taking database
backups etc. There are many Python libraries that parse the command line arguments. The argparse library comes bundled with Python’s standard library. You
can use Click (part of Flask framework) and Typer (included in FastAPI framework) to build console interfaces to the web-based applications built by the
respective frameworks. Textual is a rapid development framework to build apps that run inside a terminal as well as browsers.

CAD Applications
CAD engineers can take advantage of Python's versatility to automate repetitive tasks such as drawing shapes and generating reports.

Autodesk Fusion 360 is a popular CAD software, which has a Python API that allows users to automate tasks and create custom tools. Similarly, SolidWorks
has a built-in Python shell that allows users to run Python scripts inside the software.

CATIA is another very popular CAD software. Along with a VBScript, certain third-party Python libraries that can be used to control CATIA.

Game Development
Some popular gaming apps have been built with Python. Examples include BattleField2, The Sims 4, World of Tanks, Pirates of the Caribbean, and more.
These apps are built with one of the following Python libraries.

Pygame is one of the most popular Python libraries used to build engaging computer games. Pygame is an open-source Python library for making multimedia
applications like games built on top of the excellent SDL library. It is a cross-platform library, which means you can build a game that can run on any
operating system platform.

Another library Kivy is also widely used to build desktop as well as mobile-based games. Kivy has a multi-touch interface. It is an open-source and cross-
platform Python library for rapid development of game applications. Kivy runs on Linux, Windows, OS X, Android, iOS, and Raspberry Pi.

PyKyra library is based on both SDL (Software and Documentation Localisation) and the Kyra engine. It is one of the fastest game development frameworks.
PyKyra supports MPEG , MP3, Ogg Vorbis, Wav, etc., multimedia formats.
Python Interpreter and Its Modes
Python Interpreter
Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the executable ([Link])
is found in the installation folder (for example C:\python311 ).

This tutorial will teach you How Python Interpreter Works in interactive and scripted mode. Python code is executed by one statement at a time method.
Python interpreter has two components. The translator checks the statement for syntax. If found correct, it generates an intermediate byte code. There is a
Python virtual machine which then converts the byte code in native binary and executes it. The following diagram illustrates the mechanism:

Python interpreter has an interactive mode and a scripted mode.

Python Interpreter - Interactive Mode


When launched from a command line terminal without any additional options, a Python prompt >>> appears and the Python interpreter works on the
principle of REPL (Read, Evaluate, Print, Loop) . Each command entered in front of the Python prompt is read, translated and executed. A typical
interactive session is as follows.

>>> price = 100


>>> qty = 5
>>> total = price*qty
>>> total
500
>>> print ("Total = ", total)
Total = 500

To close the interactive session, enter the end-of-line character (ctrl+D for Linux and ctrl+Z for Windows). You may also type quit() in front of the Python
prompt and press Enter to return to the OS prompt.

>>> quit()

The interactive shell available with standard Python distribution is not equipped with features like line editing, history search, auto-completion etc. You can
use other advanced interactive interpreter software such as IPython and bpython to have additional functionalities.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.

Python Interpreter - Scripting Mode


Instead of entering and obtaining the result of one instruction at a time as in the interactive environment, it is possible to save a set of instructions in a text
file, make sure that it has .py extension, and use the name as the command line parameter for Python command.

Save the following lines as [Link] , with the use of any text editor such as vim on Linux or Notepad on Windows.

Open Compiler

print ("My first program")


price = 100
qty = 5
total = price*qty
print ("Total = ", total)

When we execute above program on a Windows machine, it will produce following result:

1 C:\Users\Acer>python [Link]
2 My first program
3 Total = 500
Note that even though Python executes the entire script in one go, but internally it is still executed in line by line fashion.

In case of any compiler-based language such as Java, the source code is not converted in byte code unless the entire code is error-free. In Python, on the other
hand, statements are executed until first occurrence of error is encountered.

Let us introduce an error purposefully in the above code.

Open Compiler

print ("My first program")


price = 100
qty = 5
total = prive*qty #Error in this statement
print ("Total = ", total)

Note the misspelt variable prive instead of price . Try to execute the script again as before −

1 C:\Users\Acer>python [Link]
2 My first program
3 Traceback (most recent call last):
4 File "C:\Python311\[Link]", line 4, in <module>
5 total = prive*qty
6 ^^^^^
7 NameError: name 'prive' is not defined. Did you mean: 'price'?

Note that the statements before the erroneous statement are executed and then the error message appears. Thus it is now clear that Python script is executed in
interpreted manner.

Python Interpreter - Using Shebang #!


In addition to executing the Python script as above, the script itself can be a selfexecutable in Linux, like a shell script. You have to add a shebang line on top
of the script. The shebang indicates which executable is used to interpret Python statements in the script. Very first line of the script starts with #! And
followed by the path to Python executable.

Modify the [Link] script as follows −

Open Compiler

#! /usr/bin/python3.11

print ("My first program")


price = 100
qty = 5
total = price*qty
print ("Total = ", total)

To mark the script as self-executable, use the chmod command

$ chmod +x [Link]

You can now execute the script directly, without using it as a command-line argument.

$ ./[Link]

Interactive Python - IPython


IPython (stands for Interactive Python ) is an enhanced and powerful interactive environment for Python with many functionalities compared to the
standard Python shell. IPython was originally developed by Fernando Perez in 2001.

IPython has the following important features −

IPython's object introspection ability to check properties of an object during runtime.


Its syntax highlighting proves to be useful in identifying the language elements such as keywords, variables etc.
The history of interactions is internally stored and can be reproduced.
Tab completion of keywords, variables and function names is one of the most important features.
IPython's Magic command system is useful for controlling Python environment and performing OS tasks.
It is the main kernel for Jupyter notebook and other front-end tools of Project Jupyter.

Install IPython with PIP installer utility.

pip3 install ipython


Launch IPython from command-line

C:\Users\Acer>ipython
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type 'copyright', 'credits' or 'license' for more information
IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]:

Instead of the regular >>> prompt as in standard interpreter, you will notice two major IPython prompts as explained below −

In[1] appears before any input expression.


Out[1]appears before the Output appears.

In [1]: price = 100


In [2]: quantity = 5
In [3]: total = price*quantity
In [4]: total
Out[4]: 500
In [5]:

Tab completion is one of the most useful enhancements provided by IPython. IPython pops up appropriate list of methods as you press tab key after dot in
front of object.

IPython provides information (introspection) of any object by putting ? in front of it. It includes docstring , function definitions and constructor details of
class. For example to explore the string object var defined above, in the input prompt enter var?.

In [5]: var = "Hello World"


In [6]: var?
Type: str
String form: Hello World
Length: 11
Docstring:
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to [Link]().
errors defaults to 'strict'.

IPython's magic functions are extremely powerful. Line magics let you run DOS commands inside IPython. Let us run the dir command from within IPython
console

In [8]: !dir *.exe


Volume in drive F has no label.
Volume Serial Number is E20D-C4B9

Directory of F:\Python311

07-02-2023 16:55 103,192 [Link]


07-02-2023 16:55 101,656 [Link]
2 File(s) 204,848 bytes
0 Dir(s) 105,260,306,432 bytes free

Jupyter notebook is a web-based interface to programming environments of Python, Julia, R and many others. For Python, it uses IPython as its main kernel.

Python - Environment Setup


First step in the journey of learning Python is to install it on your machine. Today most computer machines, especially having Linux OS, have Python pre-
installed. However, it may not be the latest version.

Python is available on a wide variety of platforms including Linux and Mac OS X. Let's understand how to set up our Python environment.

Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)


Win 9x/NT/2000
Macintosh (Intel, PPC, 68K)
OS/2
DOS (multiple versions)
PalmOS
Nokia mobile phones
Windows CE
Acorn/RISC OS
BeOS
Amiga
VMS/OpenVMS
QNX
VxWorks
Psion

Python has also been ported to the Java and .NET virtual machines

Local Environment Setup


Open a terminal window and type "python" to find out if it is already installed and which version is installed. If Python is already installed then you will get a
message something like as follows:

1 $ python
2 Python 3.11.2 (main, Feb 8 2023, 14:49:24) [GCC 9.4.0] on linux
3 Type "help", "copyright", "credits" or "license" for more information.
4
5 >>>

Downloading Python
The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python [Link]

You can download Python documentation from [Link] The documentation is available in HTML, PDF, and PostScript formats.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Installing Python

Python distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Python.

If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more
flexibility in terms of choice of features that you require in your installation.

Here is a quick overview of installing Python on various platforms −

Install Python on Ubuntu Linux


To check whether Python is already installed, open the Linux terminal and enter the following command −

$ python3.11 --version

In Ubuntu Linux, the easiest way to install Python is to use apt – Advanced Packaging Tool . It is always recommended to update the list of packages in all
the configured repositories.

$ sudo apt update

Even after the update, the latest version of Python may not be available for install, depending upon the version of Ubuntu you are using. To overcome this,
add the deadsnakes repository.

$ sudo apt-get install software-properties-common


$ sudo add-apt-repository ppa:deadsnakes/ppa

Update the package list again.

$ sudo apt update

To install the latest Python 3.11 version, enter the following command in the terminal −

$ sudo apt-get install python3.11

Check whether it has been properly installed.


$ python3
Python 3.11.2 (main, Feb 8 2023, 14:49:24) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> print ("Hello World")


Hello World

>>>

Install Python on other Linux


Here are the simple steps to install Python on Unix/Linux machine.

Open a Web browser and go to [Link]


Follow the link to download zipped source code available for Unix/Linux.
Download and extract files.
Editing the Modules/Setup file if you want to customize some options.

Now issue the following commands:

1 $ run ./configure script


2 $ make
3 $ make install

This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.

Using Yum Command


Red Hat Enterprise Linux (RHEL 8) does not install Python 3 by default. We usually use yum command on CentOS and other related variants. The procedure
for installing Python-3 on RHEL 8 is as follows:

1 $ sudo yum install python3

Install Python on Windows


It should be noted that Python's version 3.10 onwards cannot be installed on Windows 7 or earlier operating systems.

The recommended way to install Python is to use the official installer. A link to the latest stable version is given on the home page itself. It is also found at
[Link]

You can find embeddable packages and installers for 32 as well as 64-bit architecture.

Let us download 64-bit Windows installer −

([Link]

Double click on the file where it has been downloaded to start the installation.
Although you can straight away proceed by clicking the Install Now button, it is advised to choose the installation folder with a relatively shorter path, and
tick the second check box to update the PATH variable.

Accept defaults for rest of the steps in this installation wizard to complete the installation.

Open the Window Command Prompt terminal and run Python to check the success of installation.

C:\Users\Acer>python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Python's standard library has an executable module called IDLE – short for Integrated Development and Learning Environment . Find it from Window
start menu and launch.
IDLE contains Python shell (interactive interpreter) and a customizable multi-window text editor with features such as syntax highlighting, smart indent, auto
completion etc. It is cross-platform so works the same on Windows, MacOS and Linux. It also has a debugger with provision to set breakpoints, stepping, and
viewing of global and local namespaces.

Here are the steps to install Python on Windows machine.

Open a Web browser and go to [Link]


Follow the link for the Windows installer [Link] file where XYZ is the version you need to install.
To use this installer [Link] , the Windows system must support Microsoft Installer 2.0. Save the installer file to your local machine and then run
it to find out if your machine supports MSI.
Run the downloaded file. This brings up the Python install wizard, which is really easy to use. Just accept the default settings, wait until the install is
finished, and you are done.

Macintosh Installation
Recent Macs come with Python installed, but it may be several years out of date. See [Link] for instructions on getting the
current version along with extra tools to support development on the Mac. For older Mac OS's before Mac OS X 10.3 (released in 2003), MacPython is
available.

Jack Jansen maintains it and you can have full access to the entire documentation at his website − [Link] You can find
complete installation details for Mac OS installation.

Setting up PATH
Programs and other executable files can be in many directories, so operating systems provide a search path that lists the directories that the OS searches for
executables.

The path is stored in an environment variable, which is a named string maintained by the operating system. This variable contains information available to the
command shell and other programs.

The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive; Windows is not).

In Mac OS, the installer handles the path details. To invoke the Python interpreter from any particular directory, you must add the Python directory to your
path.

Setting path at Unix/Linux


To add the Python directory to the path for a particular session in Unix −

In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.
In the bash shell (Linux) − type export PATH="$PATH:/usr/local/bin/python" and press Enter.
In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press Enter.
Note − /usr/local/bin/python is the path of the Python directory
Setting path at Windows
To add the Python directory to the path for a particular session in Windows −

At the command prompt − type path %path%;C:\Python and press Enter.

Note − C:\Python is the path of the Python directory

Python Environment Variables


Here are important environment variables, which can be recognized by Python −

[Link]. Variable & Description

1 PYTHONPATHIt has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program.
It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by
the Python installer.

2 PYTHONSTARTUPIt contains the path of an initialization file containing Python source code. It is executed every time you start the
interpreter. It is named as .[Link] in Unix and it contains commands that load utilities or modify PYTHONPATH.

3 PYTHONCASEOKIt is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to
any value to activate it.

4 PYTHONHOMEIt is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to
make switching module libraries easy.

Running Python
There are three different ways to start Python −

Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window.

Enter python the command line.

Start coding right away in the interactive interpreter.

1 $python # Unix/Linux
2 or
3 python% # Unix/Linux
4 or
5 C:> python # Windows/DOS

Here is the list of all the available command line options −

[Link]. Option & Description

1 -dIt provides debug output.

2 -OIt generates optimized bytecode (resulting in .pyo files).

3 -SDo not run import site to look for Python paths on startup.

4 -vverbose output (detailed trace on import statements).

5 -Xdisable class-based built-in exceptions (just use strings); obsolete starting with version 1.6.

6 -c cmdrun Python script sent in as cmd string

7 filerun Python script from given file


Script from the Command-line
A Python script can be executed at command line by invoking the interpreter on your application, as in the following −

1 $python [Link] # Unix/Linux


2
3 or
4
5 python% [Link] # Unix/Linux
6
7 or
8
9 C: >python [Link] # Windows/DOS

Note − Be sure the file permission mode allows execution.

Integrated Development Environment


You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python.

Unix − IDLE is the very first Unix IDE for Python.


Windows − PythonWin is the first Windows interface for Python and is an IDE with a GUI.
Macintosh − The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or
BinHex'd files.

If you are not able to set up the environment properly, then you can take help from your system admin. Make sure the Python environment is properly set up
and working perfectly fine.

We have provided Python Online Compiler/Interpreter which helps you to Edit and Execute the code directly from your browser. Try to click the icon to
run the following Python code to print conventional "Hello, World!".

Below code box allows you to change the value of the code. Try to change the value inside print() and run it again to verify the result.

Open Compiler

# This is my first Python program.


# This will print 'Hello, World!' as the output

print ("Hello, World!");

Python - Virtual Environment


Python Virtual Environment
Python virtual environments create a virtual installation of Python inside a project directory. Users can then install and manage Python packages for each
project. This allows users to be able to install packages and modify their Python environment without fear of breaking packages installed in other
environments.

What is Virtual Environment in Python?


A Python virtual environment is:

Considered as disposable.
Used to contain a specific Python interpreter and software libraries and binaries which are needed to support a project.
Contained in a directory, conventionally either named venv or .venv in the project directory.
Not considered as movable or copyable.

When you install Python software on your computer, it is available for use from anywhere in the filesystem. This is a system-wide installation.
While developing an application in Python, one or more libraries may be required to be installed using the pip utility (e.g., pip3 install somelib ). Moreover,
an application (let us say App1) may require a particular version of the library − say somelib 1.0 . At the same time another Python application (for example
App2) may require newer version of same library say somelib 2.0 . Hence by installing a new version, the functionality of App1 may be compromised
because of conflict between two different versions of same library.

This conflict can be avoided by providing two isolated environments of Python in the same machine. These are called virtual environment. A virtual
environment is a separate directory structure containing isolated installation having a local copy of Python interpreter, standard library and other modules.

The following figure shows the purpose of advantage of using virtual environment. Using the global Python installation, more than one virtual environments
are created, each having different version of the same library, so that conflict is avoided.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Creation of Virtual Environments in Python using venv

This functionality is supported by venv module in standard Python distribution. Use following commands to create a new virtual environment.

C:\Users\Acer>md\pythonapp
C:\Users\Acer>cd\pythonapp
C:\pythonapp>python -m venv myvenv

Here, myvenv is the folder in which a new Python virtual environment will be created showing following directory structure −

Directory of C:\pythonapp\myvenv
22-02-2023 09:53 <DIR> .
22-02-2023 09:53 <DIR> ..
22-02-2023 09:53 <DIR> Include
22-02-2023 09:53 <DIR> Lib
22-02-2023 09:53 77 [Link]
22-02-2023 09:53 <DIR> Scripts

The utilities for activating and deactivating the virtual environment as well as the local copy of Python interpreter will be placed in the scripts folder.

Directory of C:\pythonapp\myvenv\scripts
22-02-2023 09:53 <DIR> .
22-02-2023 09:53 <DIR> ..
22-02-2023 09:53 2,063 activate
22-02-2023 09:53 992 [Link]
22-02-2023 09:53 19,611 Activate.ps1
22-02-2023 09:53 393 [Link]
22-02-2023 09:53 106,349 [Link]
22-02-2023 09:53 106,349 [Link]
22-02-2023 09:53 106,349 [Link]
22-02-2023 09:53 242,408 [Link]
22-02-2023 09:53 232,688 [Link]

Activating Virtual Environment


To enable this new virtual environment, execute [Link] in Scripts folder.

C:\pythonapp>myvenv\scripts\activate
(myvenv) C:\pythonapp>

Note the name of the virtual environment in the parentheses. The Scripts folder contains a local copy of Python interpreter. You can start a Python session in
this virtual environment.
Checking If Python is Running Inside a Virtual Environment?
To confirm whether this Python session is in virtual environment check the [Link] .

(myvenv) C:\pythonapp>python
Python 3.10.1 (tags/v3.10.1:2cd268a, Dec 6 2021, 19:10:37) [MSC v.1929
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> [Link]
['', 'C:\\Python310\\[Link]', 'C:\\Python310\\DLLs',
'C:\\Python310\\lib', 'C:\\Python310', 'C:\\pythonapp\\myvenv',
'C:\\pythonapp\\myvenv\\lib\\site-packages']
>>>

The scripts folder of this virtual environment also contains pip utilities. If you install a package from PyPI, that package will be active only in current virtual
environment.

Deactivating Virtual Environment


To deactivate this environment, run [Link] .

Python - Syntax
Python - Syntax
The Python syntax defines a set of rules that are used to create a Python Program. The Python Programming Language Syntax has many similarities to Perl,
C, and Java Programming Languages. However, there are some definite differences between the languages.

First Python Program


Let us execute a Python program to print "Hello, World!" in two different modes of Python Programming. (a) Interactive Mode Programming (b) Script Mode
Programming.

Python - Interactive Mode Programming


We can invoke a Python interpreter from command line by typing python at the command prompt as following −

$ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Here >>> denotes a Python Command Prompt where you can type your commands. Let's type the following text at the Python prompt and press the Enter −

>>> print ("Hello, World!")

If you are running older version of Python, like Python 2.4.x, then you would need to use print statement without parenthesis as in print "Hello, World!" .
However in Python version 3.x, this produces the following result −

1 Hello, World!
Python - Script Mode Programming
We can invoke the Python interpreter with a script parameter which begins the execution of the script and continues until the script is finished. When the
script is finished, the interpreter is no longer active.

Let us write a simple Python program in a script which is simple text file. Python files have extension .py . Type the following source code in a [Link] file −

Open Compiler

print ("Hello, World!")

We assume that you have Python interpreter path set in PATH variable. Now, let's try to run this program as follows −

$ python3 [Link]

This produces the following result −

1 Hello, World!

Let us try another way to execute a Python script. Here is the modified [Link] file −

Open Compiler

#!/usr/bin/python3

print ("Hello, World!")

We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −

$ chmod +x [Link] # This is to make file executable


$./[Link]

This produces the following result −

1 Hello, World!

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python Identifiers

A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores and digits (0 to 9).

Python does not allow punctuation characters such as @, $, and % within identifiers.

Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python.

Here are naming conventions for Python identifiers −

Python Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is private identifier.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.

Python Reserved Words


The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All
the Python keywords contain lowercase letters only.

and as assert

break class continue

def del elif

else except False

finally for from

global if import

in is lambda
and as assert

None nonlocal not

or pass raise

return True try

while with yield

Python Lines and Indentation


Python programming provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line
indentation , which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example −

if True:
print ("True")
else:
print ("False")

However, the following block generates an error −

Open Compiler

if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False")

Thus, in Python all the continuous lines indented with same number of spaces would form a block. The following example has various statement blocks −

Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are without braces.

import sys

try:
# open file stream
file = open(file_name, "w")
except IOError:
print "There was an error writing to", file_name
[Link]()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
file_text = raw_input("Enter text: ")
if file_text file_finish:
# close the file
[Link]
break
[Link](file_text)
[Link]("\n")
[Link]()
file_name = raw_input("Enter filename: ")
if len(file_name) 0:
print "Next time please enter something"
[Link]()
try:
file = open(file_name, "r")
except IOError:
print "There was an error reading file"
[Link]()
file_text = [Link]()
[Link]()
print file_text
Python Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character () to denote that the line should
continue. For example −

total = item_one + \
item_two + \
item_three

Statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example following statement works well in
Python −

days = ['Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday']

Quotations in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines. For example, all the following are legal −

word = 'word'
print (word)

sentence = "This is a sentence."


print (sentence)

paragraph = """This is a paragraph. It is


made up of multiple lines and sentences."""
print (paragraph)

Comments in Python
A comment is a programmer-readable explanation or annotation in the Python source code. They are added with the purpose of making the source code easier
for humans to understand, and are ignored by Python interpreter

Just like most modern languages, Python supports single-line (or end-of-line) and multi-line (block) comments. Python comments are very much similar to
the comments available in PHP, BASH and Perl Programming languages.

A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and
the Python interpreter ignores them.

Open Compiler

# First comment
print ("Hello, World!") # Second comment

This produces the following result −

1 Hello, World!

You can type a comment on the same line after a statement or expression −

name = "Madisetti" # This is again comment

You can comment multiple lines as follows −

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Following triple-quoted string is also ignored by Python interpreter and can be used as a multiline comments:

'''
This is a multiline
comment.
'''
Using Blank Lines in Python Programs
A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it.

In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement.

Waiting for the User


The following line of the program displays the prompt, the statement saying “Press the enter key to exit”, and waits for the user to take action −

#!/usr/bin/python

raw_input("\n\nPress the enter key to exit.")

Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user presses the key, the program ends. This is a nice trick to keep a
console window open until the user is done with an application.

Multiple Statements on a Single Line


The semicolon ( ; ) allows multiple statements on the single line given that neither statement starts a new code block. Here is a sample snip using the
semicolon −

Open Compiler

import sys; x = 'foo'; [Link](x + '\n')

Multiple Statement Groups as Suites


A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and
class require a header line and a suite.

Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more lines which make up the suite. For
example −

if expression :
suite
elif expression :
suite
else :
suite

Command Line Arguments in Python


Many programs can be run to provide you with some basic information about how they should be run. Python enables you to do this with -h −

$ python3 -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit

[ etc. ]

You can also program your script in such a way that it should accept various options. Command Line Arguments is an advanced topic and should be studied a
bit later once you have gone through rest of the Python concepts.
Python - Variables
Python Variables
Python variables are the reserved memory locations used to store values with in a Python Program. This means that when you create a variable you reserve
some space in the memory.

Based on the data type of a variable, Python interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning
different data types to Python variables, you can store integers, decimals or characters in these variables.

Memory Addresses
Data items belonging to different data types are stored in computer's memory. Computer's memory locations are having a number or address, internally
represented in binary form. Data is also stored in binary form as the computer works on the principle of binary representation. In the following diagram, a
string May and a number 18 is shown as stored in memory locations.

If you know the assembly language, you will covert these data items and the memory address, and give a machine language instruction. However, it is not
easy for everybody. Language translator such as Python interpreter performs this type of conversion. It stores the object in a randomly chosen memory
location. Python's built-in id() function returns the address where the object is stored.

>>> "May"
May
>>> id("May")
2167264641264

>>> 18
18
>>> id(18)
140714055169352

Once the data is stored in the memory, it should be accessed repeatedly for performing a certain process. Obviously, fetching the data from its ID is
cumbersome. High level languages like Python make it possible to give a suitable alias or a label to refer to the memory location.

In the above example, let us label the location of May as month, and location in which 18 is stored as age. Python uses the assignment operator (=) to bind an
object with the label.

>>> month="May"
>>> age=18

The data object (May) and its name (month) have the same id(). The id() of 18 and age are also same.
>>> id(month)
2167264641264
>>> id(age)
140714055169352

The label is an identifier. It is usually called as a variable. A Python variable is a symbolic name that is a reference or pointer to an object.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Creating Python Variables

Python variables do not need explicit declaration to reserve memory space or you can say to create a variable. A Python variable is created automatically
when you assign a value to it. The equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For
example −

Example to Create Python Variables


This example creates different types (an integer, a float, and a string) of variables.

counter = 100 # Creates an integer variable


miles = 1000.0 # Creates a floating point variable
name = "Zara Ali" # Creates a string variable

Printing Python Variables


Once we create a Python variable and assign a value to it, we can print it using print() function. Following is the extension of previous example and shows
how to print different variables in Python:

Example to Print Python Variables


This example prints variables.

Open Compiler

counter = 100 # Creates an integer variable


miles = 1000.0 # Creates a floating point variable
name = "Zara Ali" # Creates a string variable

print (counter)
print (miles)
print (name)

Here, 100, 1000.0 and "Zara Ali" are the values assigned to counter , miles , and name variables, respectively. When running the above Python program, this
produces the following result −

1 100
2 1000.0
3 Zara Ali

Deleting Python Variables


You can delete the reference to a number object by using the del statement. The syntax of the del statement is −

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example −

del var
del var_a, var_b
Example
Following examples shows how we can delete a variable and if we try to use a deleted variable then Python interpreter will throw an error:

Open Compiler

counter = 100
print (counter)

del counter
print (counter)

This will produce the following result:

1 100
2 Traceback (most recent call last):
3 File "[Link]", line 7, in <module>
4 print (counter)
5 NameError: name 'counter' is not defined

Getting Type of a Variable


You can get the data type of a Python variable using the python built-in function type() as follows.

Example: Printing Variables Type


Open Compiler

x = "Zara"
y = 10
z = 10.10

print(type(x))
print(type(y))
print(type(z))

This will produce the following result:

1 <class 'str'>
2 <class 'int'>
3 <class 'float'>

Casting Python Variables


You can specify the data type of a variable with the help of casting as follows:

Example
This example demonstrates case sensitivity of variables.

Open Compiler

x = str(10) # x will be '10'


y = int(10) # y will be 10
z = float(10) # z will be 10.0

print( "x =", x )


print( "y =", y )
print( "z =", z )

This will produce the following result:


1 x = 10
2 y = 10
3 z = 10.0

Case-Sensitivity of Python Variables


Python variables are case sensitive which means Age and age are two different variables:

Open Compiler

age = 20
Age = 30

print( "age =", age )


print( "Age =", Age )

This will produce the following result:

1 age = 20
2 Age = 30

Python Variables - Multiple Assignment


Python allows to initialize more than one variables in a single statement. In the following case, three variables have same value.

>>> a=10
>>> b=10
>>> c=10

Instead of separate assignments, you can do it in a single assignment statement as follows −

>>> a=b=c=10
>>> print (a,b,c)
10 10 10

In the following case, we have three variables with different values.

>>> a=10
>>> b=20
>>> c=30

These separate assignment statements can be combined in one. You need to give comma separated variable names on left, and comma separated values on the
right of = operator.

>>> a,b,c = 10,20,30


>>> print (a,b,c)
10 20 30

Let's try few examples in script mode: −

Open Compiler

a = b = c = 100

print (a)
print (b)
print (c)

This produces the following result:

1 100
2 100
3 100

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to
multiple variables. For example −

Open Compiler

a,b,c = 1,2,"Zara Ali"


print (a)
print (b)
print (c)

This produces the following result:

1 1
2 2
3 Zara Ali

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "Zara Ali" is assigned to the
variable c.

Python Variables - Naming Convention


Every Python variable should have a unique name like a, b, c. A variable name can be meaningful like color, age, name etc. There are certain rules which
should be taken care while naming a Python variable:

A variable name must start with a letter or the underscore character


A variable name cannot start with a number or any special character like $, (, * % etc.
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Python variable names are case-sensitive which means Name and NAME are two different variables in Python.
Python reserved keywords cannot be used naming the variable.

If the name of variable contains multiple words, we should use these naming patterns −

Camel case − First letter is a lowercase, but first letter of each subsequent word is in uppercase. For example: kmPerHour, pricePerLitre
Pascal case − First letter of each word is in uppercase. For example: KmPerHour, PricePerLitre
Snake case − Use single underscore (_) character to separate words. For example: km_per_hour, price_per_litre

Example
Following are valid Python variable names:

Open Compiler

counter = 100
_count = 100
name1 = "Zara"
name2 = "Nuha"
Age = 20
zara_salary = 100000

print (counter)
print (_count)
print (name1)
print (name2)
print (Age)
print (zara_salary)

This will produce the following result:

1 100
2 100
3 Zara
4 Nuha
5 20
6 100000
Example
Following are invalid Python variable names:

Open Compiler

1counter = 100
$_count = 100
zara-salary = 100000

print (1counter)
print ($count)
print (zara-salary)

This will produce the following result:

1 File "[Link]", line 3


2 1counter = 100
3 ^
4 SyntaxError: invalid syntax

Example
Once you use a variable to identify a data object, it can be used repeatedly without its id() value. Here, we have a variables height and width of a rectangle.
We can compute the area and perimeter with these variables.

>>> width=10
>>> height=20
>>> area=width*height
>>> area
200
>>> perimeter=2*(width+height)
>>> perimeter
60

Use of variables is especially advantageous when writing scripts or programs. Following script also uses the above variables.

Open Compiler

#! /usr/bin/python3

width = 10
height = 20
area = widthheight
perimeter = 2(width+height)
print ("Area = ", area)
print ("Perimeter = ", perimeter)

Save the above script with .py extension and execute from command-line. The result would be −

1 Area = 200
2 Perimeter = 60

Python Local Variables


Python Local Variables are defined inside a function. We can not access variable outside the function.

A Python functions is a piece of reusable code and you will learn more about function in Python - Functions tutorial.

Example
Following is an example to show the usage of local variables:

Open Compiler

def sum(x,y):
sum = x + y
return sum
print(sum(5, 10))

This will produce the following result −

1 15

Python Global Variables


Any variable created outside a function can be accessed within any function and so they have global scope.

Example
Following is an example of global variables −

Open Compiler

x = 5
y = 10
def sum():
sum = x + y
return sum
print(sum())

This will produce the following result −

1 15

Constants in Python
Python doesn't have any formally defined constants, However you can indicate a variable to be treated as a constant by using all-caps names with
underscores. For example, the name PI_VALUE indicates that you don't want the variable redefined or changed in any way.

The naming convention using all-caps is sometimes referred to as screaming snake case - where the all-caps (screaming) and the underscores (snakes).

Python vs C/C++ Variables


The concept of variable works differently in Python than in C/C++. In C/C++, a variable is a named memory location. If a=10 and also b=10, both are two
different memory locations. Let us assume their memory address is 100 and 200 respectively.

If a different value is assigned to "a" - say 50, 10 in the address 100 is overwritten.

A Python variable refers to the object and not the memory location. An object is stored in memory only once. Multiple variables are really the multiple labels
to the same object.
The statement a=50 creates a new int object 50 in the memory at some other location, leaving the object 10 referred by "b".

Further, if you assign some other value to b, the object 10 remains unreferred.

Python's garbage collector mechanism releases the memory occupied by any unreferred object.

Python's identity operator is returns True if both the operands have same id() value.

>>> a=b=10
>>> a is b
True
>>> id(a), id(b)
(140731955278920, 140731955278920)

Python - Data Types


Python Data Types
Python data types are actually classes, and the defined variables are their instances or objects. Since Python is dynamically typed, the data type of a variable
is determined at runtime based on the assigned value.

In general, the data types are used to define the type of a variable. It represents the type of data we are going to store in a variable and determines what
operations can be done on it.

Each programming language has its own classification of data items. With these datatypes, we can store different types of data values.

Types of Data Types in Python


Python supports the following built-in data types −

Numeric Data Types


int
flot
complex
String Data Types
Sequence Data Types
list
tuple
range
Binary Data Types
bytes
bytearray
memoryview
Dictionary Data Type
Set Data Type
set
frozenset
Boolean Data Type
None Type

Python numeric data types store numeric values. Number objects are created when you assign a value to them. For example −

var1 = 1 # int data type


var2 = True # bool data type
var3 = 10.023 # float data type
var4 = 10+3j # complex data type

Python supports four different numerical types and each of them have built-in classes in Python library, called int, bool, float and complex respectively −

int (signed integers)


float (floating point real values)
complex (complex numbers)

A complex number is made up of two parts - real and imaginary . They are separated by '+' or '-' signs. The imaginary part is suffixed by 'j' which is the
imaginary number. The square root of -1 (−1−−−√−1), is defined as imaginary number. Complex number in Python is represented as x+yj, where x is the real
part, and y is the imaginary part. So, 5+6j is a complex number.

>>> type(5+6j)
<class 'complex'>

Here are some examples of numbers −

int float complex

10 0.0 3.14j

0O777 15.20 45.j

-786 -21.9 9.322e-36j

080 32.3+e18 .876j

0x17 -90. -.6545+0J

-0x260 -32.54e100 3e+26J

0x69 70.2-E12 4.53e-7j


Example of Numeric Data Types
Following is an example to show the usage of Integer, Float and Complex numbers:

Open Compiler

# integer variable.
a=100
print("The type of variable having value", a, " is ", type(a))

# float variable.
c=20.345
print("The type of variable having value", c, " is ", type(c))

# complex variable.
d=10+3j
print("The type of variable having value", d, " is ", type(d))

2. Python String Data Type


Python string is a sequence of one or more Unicode characters, enclosed in single, double or triple quotation marks (also called inverted commas). Python
strings are immutable which means when you perform an operation on strings, you always produce a new string object of the same type, rather than mutating
an existing string.

As long as the same sequence of characters is enclosed, single or double or triple quotes don't matter. Hence, following string representations are equivalent.

>>> 'TutorialsPoint'
'TutorialsPoint'
>>> "TutorialsPoint"
'TutorialsPoint'
>>> '''TutorialsPoint'''
'TutorialsPoint'

A string in Python is an object of str class. It can be verified with type() function.

>>> type("Welcome To TutorialsPoint")


<class 'str'>

A string is a non-numeric data type. Obviously, we cannot perform arithmetic operations on it. However, operations such as slicing and concatenation can be
done. Python's str class defines a number of useful methods for string processing. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with
indexes starting at 0 in the beginning of the string and working their way from -1 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator in Python.

Example of String Data Type


Open Compiler

str = 'Hello World!'

print (str) # Prints complete string


print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

This will produce the following result −

1 Hello World!
2 H
3 llo
4 llo World!
5 Hello World!Hello World!
6 Hello World!TEST
3. Python Sequence Data Types
Sequence is a collection data type. It is an ordered collection of items. Items in the sequence have a positional index starting with 0. It is conceptually similar
to an array in C or C++. There are following three sequence data types defined in Python.

List Data Type


Tuple Data Type
Range Data Type

Python sequences are bounded and iterable - Whenever we say an iterable in Python, it means a sequence data type (for example, a list).

(a) Python List Data Type


Python Lists are the most versatile compound data types. A Python list contains items separated by commas and enclosed within square brackets ([]). To some
extent, Python lists are similar to arrays in C. One difference between them is that all the items belonging to a Python list can be of different data type where
as C array can store elements related to a particular data type.

>>> [2023, "Python", 3.11, 5+6j, 1.23E-4]

A list in Python is an object of list class. We can check it with type() function.

>>> type([2023, "Python", 3.11, 5+6j, 1.23E-4])


<class 'list'>

As mentioned, an item in the list may be of any data type. It means that a list object can also be an item in another list. In that case, it becomes a nested list.

>>> [['One', 'Two', 'Three'], [1,2,3], [1.0, 2.0, 3.0]]

A list can have items which are simple numbers, strings, tuple, dictionary, set or object of user defined class also.

The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their
way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

Example of List Data Type


Open Compiler

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print (list) # Prints complete list


print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists

This produce the following result −

1 ['abcd', 786, 2.23, 'john', 70.2]


2 abcd
3 [786, 2.23]
4 [2.23, 'john', 70.2]
5 [123, 'john', 123, 'john']
6 ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

(b) Python Tuple Data Type


Python tuple is another sequence data type that is similar to a list. A Python tuple consists of a number of values separated by commas. Unlike lists, however,
tuples are enclosed within parentheses (...).

A tuple is also a sequence, hence each item in the tuple has an index referring to its position in the collection. The index starts from 0.

>>> (2023, "Python", 3.11, 5+6j, 1.23E-4)

In Python, a tuple is an object of tuple class. We can check it with the type() function.
>>> type((2023, "Python", 3.11, 5+6j, 1.23E-4))
<class 'tuple'>

As in case of a list, an item in the tuple may also be a list, a tuple itself or an object of any other Python class.

>>> (['One', 'Two', 'Three'], 1,2.0,3, (1.0, 2.0, 3.0))

To form a tuple, use of parentheses is optional. Data items separated by comma without any enclosing symbols are treated as a tuple by default.

>>> 2023, "Python", 3.11, 5+6j, 1.23E-4


(2023, 'Python', 3.11, (5+6j), 0.000123)

Example of Tuple data Type


Open Compiler

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print (tuple) # Prints the complete tuple


print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples

This produce the following result −

1 ('abcd', 786, 2.23, 'john', 70.2)


2 abcd
3 (786, 2.23)
4 (2.23, 'john', 70.2)
5 (123, 'john', 123, 'john')
6 ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed i.e. lists are mutable, while
tuples are enclosed in parentheses ( ( ) ) and cannot be updated (immutable). Tuples can be thought of as read-only lists.

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists −

Open Compiler

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

(c) Python Range Data Type


A Python range is an immutable sequence of numbers which is typically used to iterate through a specific number of items.

It is represented by the Range class. The constructor of this class accepts a sequence of numbers starting from 0 and increments to 1 until it reaches a
specified number. Following is the syntax of the function −

range(start, stop, step)

Here is the description of the parameters used −

start : Integer number to specify starting position, (Its optional, Default: 0)


stop : Integer number to specify ending position (It's mandatory)
step : Integer number to specify increment, (Its optional, Default: 1)
Example of Range Data Type
Following is a program which uses for loop to print number from 0 to 4 −

Open Compiler

for i in range(5):
print(i)

This produce the following result −

1 0
2 1
3 2
4 3
5 4

Now let's modify above program to print the number starting from 2 instead of 0 −

Open Compiler

for i in range(2, 5):


print(i)

This produce the following result −

1 2
2 3
3 4

Again, let's modify the program to print the number starting from 1 but with an increment of 2 instead of 1:

Open Compiler

for i in range(1, 5, 2):


print(i)

This produce the following result −

1 1
2 3

4. Python Binary Data Types


A binary data type in Python is a way to represent data as a series of binary digits, which are 0's and 1's. It is like a special language computers understand to
store and process information efficiently.

This type of data is commonly used when dealing with things like files, images, or anything that can be represented using just two possible values. So, instead
of using regular numbers or letters, binary sequence data types use a combination of 0s and 1s to represent information.

Python provides three different ways to represent binary data. They are as follows −

bytes
bytearray
memoryview

Let us discuss each of these data types individually −

(a) Python Bytes Data Type


The byte data type in Python represents a sequence of bytes. Each byte is an integer value between 0 and 255. It is commonly used to store binary data, such
as images, files, or network packets.

We can create bytes in Python using the built-in bytes() function or by prefixing a sequence of numbers with b .
Example of Bytes Data Type
In the following example, we are using the built-in bytes() function to explicitly specify a sequence of numbers representing ASCII values −

Open Compiler

# Using bytes() function to create bytes


b1 = bytes([65, 66, 67, 68, 69])
print(b1)

The result obtained is as follows −

1 b'ABCDE'

In here, we are using the "b" prefix before a string to automatically create a bytes object −

Open Compiler

# Using prefix 'b' to create bytes


b2 = b'Hello'
print(b2)

Following is the output of the above code −

1 b'Hello'

(b) Python Bytearray Data Type


The bytearray data type in Python is quite similar to the bytes data type, but with one key difference: it is mutable, meaning you can modify the values stored
in it after it is created.

You can create a bytearray using various methods, including by passing an iterable of integers representing byte values, by encoding a string, or by converting
an existing bytes or bytearray object. For this, we use bytearray() function.

Example of Bytearray Data Type


In the example below, we are creating a bytearray by passing an iterable of integers representing byte values −

Open Compiler

# Creating a bytearray from an iterable of integers


value = bytearray([72, 101, 108, 108, 111])
print(value)

The output obtained is as shown below −

1 bytearray(b'Hello')

Now, we are creating a bytearray by encoding a string using a "UTF-8" encoding −

Open Compiler

# Creating a bytearray by encoding a string


val = bytearray("Hello", 'utf-8')
print(val)

The result produced is as follows −

1 bytearray(b'Hello')
(c) Python Memoryview Data Type
In Python, a memoryview is a built-in object that provides a view into the memory of the original object, generally objects that support the buffer protocol,
such as byte arrays (bytearray) and bytes (bytes). It allows you to access the underlying data of the original object without copying it, providing efficient
memory access for large datasets.

You can create a memoryview using various methods. These methods include using the memoryview() constructor, slicing bytes or bytearray objects,
extracting from array objects, or using built-in functions like open() when reading from files.

Example of Memoryview Data Type


In the given example, we are creating a memoryview object directly by passing a supported object to the memoryview() constructor. The supported objects
generally include byte arrays (bytearray), bytes (bytes), and other objects that support the buffer protocol −

Open Compiler

data = bytearray(b'Hello, world!')


view = memoryview(data)
print(view)

Following is the output of the above code −

1 <memory at 0x00000186FFAA3580>

If you have an array object, you can create a memoryview using the buffer interface as shown below −

Open Compiler

import array
arr = [Link]('i', [1, 2, 3, 4, 5])
view = memoryview(arr)
print(view)

The output obtained is as shown below −

1 <memory at 0x0000017963CD3580>

You can also create a memoryview by slicing a bytes or bytearray object −

Open Compiler

data = b'Hello, world!'


# Creating a view of the last part of the data
view = memoryview(data[7:])
print(view)

The result obtained is as follows −

1 <memory at 0x00000200D9AA3580>

5. Python Dictionary Data Type


Python dictionaries are kind of hash table type. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand,
can be any arbitrary Python object.

Python dictionary is like associative arrays or hashes found in Perl and consist of key:value pairs. The pairs are separated by comma and put inside curly
brackets {}. To establish mapping between key and value, the semicolon':' symbol is put between the two.

>>> {1:'one', 2:'two', 3:'three'}

In Python, dictionary is an object of the built-in dict class. We can check it with the type() function.

>>> type({1:'one', 2:'two', 3:'three'})


<class 'dict'>

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
Example of Dictionary Data Type
Open Compiler

dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one']) # Prints value for 'one' key


print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print ([Link]()) # Prints all the keys
print ([Link]()) # Prints all the values

This produce the following result −

1 This is one
2 This is two
3 {'dept': 'sales', 'code': 6734, 'name': 'john'}
4 ['dept', 'code', 'name']
5 ['sales', 6734, 'john']

Python's dictionary is not a sequence. It is a collection of items but each item (key:value pair) is not identified by positional index as in string, list or tuple.
Hence, slicing operation cannot be done on a dictionary. Dictionary is a mutable object, so it is possible to perform add, modify or delete actions with
corresponding functionality defined in dict class. These operations will be explained in a subsequent chapter.

6. Python Set Data Type


Set is a Python implementation of set as defined in Mathematics. A set in Python is a collection, but is not an indexed or ordered collection as string, list or
tuple. An object cannot appear more than once in a set, whereas in List and Tuple, same object can appear more than once.

Comma separated items in a set are put inside curly brackets or braces {}. Items in the set collection can be of different data types.

>>> {2023, "Python", 3.11, 5+6j, 1.23E-4}


{(5+6j), 3.11, 0.000123, 'Python', 2023}

Note that items in the set collection may not follow the same order in which they are entered. The position of items is optimized by Python to perform
operations over set as defined in mathematics.

Python's Set is an object of built-in set class, as can be checked with the type() function.

>>> type({2023, "Python", 3.11, 5+6j, 1.23E-4})


<class 'set'>

A set can store only immutable objects such as number (int, float, complex or bool), string or tuple. If you try to put a list or a dictionary in the set collection,
Python raises a TypeError .

>>> {['One', 'Two', 'Three'], 1,2,3, (1.0, 2.0, 3.0)}


Traceback (most recent call last):
File "", line 1, in <module>
TypeError: unhashable type: 'list'

Hashing is a mechanism in computer science which enables quicker searching of objects in computer's memory. Only immutable objects are hashable .

Even if a set doesn't allow mutable items, the set itself is mutable. Hence, add/delete/update operations are permitted on a set object, using the methods in
built-in set class. Python also has a set of operators to perform set manipulation. The methods and operators are explained in latter chapters

Example of Set
set1 = {123, 452, 5, 6}
set2 = {'Java', 'Python', 'JavaScript'}

print(set1)
print(set2)

This will generate the following output −

1 {123, 452, 5, 6}
2 {'Python', 'JavaScript', 'Java'}
7. Python Boolean Data Type
Python boolean type is one of built-in data types which represents one of the two values either True or False . Python bool() function allows you to evaluate
the value of any expression and returns either True or False based on the expression.

A Boolean number has only two possible values, as represented by the keywords, True and False . They correspond to integer 1 and 0 respectively.

>>> type (True)


<class 'bool'>
>>> type(False)
<class 'bool'>

Example of Boolean Data Type


Following is a program which prints the value of boolean variables a and b −

Open Compiler

a = True
# display the value of a
print(a)

# display the data type of a


print(type(a))

This will produce the following result −

1 true
2 <class 'bool'>

Following is another program which evaluates the expressions and prints the return values −

Open Compiler

# Returns false as a is not equal to b


a = 2
b = 4
print(bool(a==b))

# Following also prints the same


print(a==b)

# Returns False as a is None


a = None
print(bool(a))

# Returns false as a is an empty sequence


a = ()
print(bool(a))

# Returns false as a is 0
a = 0.0
print(bool(a))

# Returns false as a is 10
a = 10
print(bool(a))

This produce the following result −

1 False
2 False
3 False
4 False
5 False
6 True
8. Python None Type
Python's none type is represented by the "nonetype." It is an object of its own data type. The nonetype represents the null type of values or absence of a
value.

Example of None Type


In the following example, we are assigning None to a variable x and printing its type, which will be nonetyoe −

Open Compiler

# Declaring a variable
# And, assigning a Null value (None)

x = None

# Printing its value and type


print("x = ", x)
print("type of x = ", type(x))

This produce the following result −

1 x = None
2 type of x = <class 'NoneType'>

Getting Data Type


To get the data types in Python, you can use the type() function. The type() is a built-in function that returns the class of the given object.

Example
In the following example, we are getting the type of the values and variables −

Open Compiler

# Getting type of values


print(type(123))
print(type(9.99))

# Getting type of variables


a = 10
b = 2.12
c = "Hello"
d = (10, 20, 30)
e = [10, 20, 30]

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

This produce the following result −

1 <class 'int'>
2 <class 'float'>
3 <class 'int'>
4 <class 'float'>
5 <class 'str'>
6 <class 'tuple'>
7 <class 'list'>
Setting Data Type
In Python, during declaring a variable or an object, you don't need to set the data types. Data type is set automatically based on the assigned value.

Example
The following example, demonstrating how a variable's data type is set based on the given value −

Open Compiler

# Declaring a variable
# And, assigning an integer value

x = 10

# Printing its value and type


print("x = ", x)
print("type of x = ", type(x))

# Now, assigning string value to


# the same variable
x = "Hello World!"

# Printing its value and type


print("x = ", x)
print("type of x = ", type(x))

This produce the following result −

1 x = 10
2 type of x = <class 'int'>
3 x = Hello World!
4 type of x = <class 'str'>

Primitive and Non-primitive Data Types


The above-explained data types can also be categorized as primitive and non-primitive.

1. Primitive Types
The primitive data types are the fundamental data types that are used to create complex data types (sometimes called complex data structures). There are
mainly four primitive data types, which are −

Integers
Floats
Booleans, and
Strings

2. Non-primitive Types
The non-primitive data types store values or collections of values. There are mainly four types of non-primitive types, which are −

Lists
Tuples
Dictionaries, and
Sets
Python Data Type Conversion
Sometimes, you may need to perform conversions between the built-in data types. To convert data between different Python data types, you simply use the
type name as a function.

Read: Python Type Casting

Example
Following is an example which converts different values to integer, floating point and string values respectively −

Open Compiler

print("Conversion to integer data type")


a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3.3") # c will be 3

print (a)
print (b)
print (c)

print("Conversion to floating point number")


a = float(1) # a will be 1.0
b = float(2.2) # b will be 2.2
c = float("3.3") # c will be 3.3

print (a)
print (b)
print (c)

print("Conversion to string")
a = str(1) # a will be "1"
b = str(2.2) # b will be "2.2"
c = str("3.3") # c will be "3.3"

print (a)
print (b)
print (c)

This produce the following result −

1 Conversion to integer data type


2 1
3 2
4 3
5 Conversion to floating point number
6 1.0
7 2.2
8 3.3
9 Conversion to string
10 1
11 2.2
12 3.3

Data Type Conversion Functions


There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted
value.

[Link]. Function & Description

1 Python int() functionConverts x to an integer. base specifies the base if x is a string.

2 Python long() functionConverts x to a long integer. base specifies the base if x is a string. This function has been deprecated.

3 Python float() functionConverts x to a floating-point number.

4 Python complex() functionCreates a complex number.


[Link]. Function & Description

5 Python str() functionConverts object x to a string representation.

6 Python repr() functionConverts object x to an expression string.

7 Python eval() functionEvaluates a string and returns an object.

8 Python tuple() functionConverts s to a tuple.

9 Python list() functionConverts s to a list.

10 Python set() functionConverts s to a set.

11 Python dict() functionCreates a dictionary. d must be a sequence of (key,value) tuples.

12 Python frozenset() functionConverts s to a frozen set.

13 Python chr() functionConverts an integer to a character.

14 Python unichr() functionConverts an integer to a Unicode character.

15 Python ord() functionConverts a single character to its integer value.

16 Python hex() functionConverts an integer to a hexadecimal string.

17 Python oct() functionConverts an integer to an octal string.

Python - Type Casting


Python Type Casting
From a programming point of view, a type casting refers to converting an object of one type into another. Here, we shall learn about type casting in Python
Programming.

Python Type Casting is a process in which we convert a literal of one data type to another data type. Python supports two types of casting − implicit and
explicit .

In Python there are different data types, such as numbers, sequences, mappings etc. There may be a situation where, you have the available data of one type
but you want to use it in another form. For example, the user has input a string but you want to use it as a number. Python's type casting mechanism let you do
that.

Python Implicit Casting


When any language compiler/interpreter automatically converts object of one type into other, it is called automatic or implicit casting . Python is a strongly
typed language. It doesn't allow automatic type conversion between unrelated data types. For example, a string cannot be converted to any number type.
However, an integer can be cast into a float. Other languages such as JavaScript is a weakly typed language, where an integer is coerced into a string for
concatenation.

Note that memory requirement of each data type is different. For example, an integer object in Python occupies 4 bytes of memory, while a float object needs
8 bytes because of its fractional part. Hence, Python interpreter doesn't automatically convert a float to int , because it will result in loss of data. On the other
hand, int can be easily converted into float by setting its fractional part to 0.

Implicit int to float casting takes place when any arithmetic operation on int and float operands is done.

Consider we have an ,int and one float variable

<<< a=10 # int object


<<< b=10.5 # float object

To perform their addition, 10 − the integer object is upgraded to 10.0. It is a float, but equivalent to its earlier numeric value. Now we can perform addition of
two floats.

<<< c=a+b
<<< print (c)
20.5
In implicit type casting, a Python object with lesser byte size is upgraded to match the bigger byte size of other object in the operation. For example, a
Boolean object is first upgraded to int and then to float, before the addition with a floating point object. In the following example, we try to add a Boolean
object in a float, pleae note that True is equal to 1, and False is equal to 0.

Open Compiler

a=True;
b=10.5;
c=a+b;

print (c);

This will produce the following result:

1 11.5

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python Explicit Casting

Although automatic or implicit casting is limited to int to float conversion, you can use Python's built-in functions int(), float() and str() to perform the
explicit conversions such as string to integer.

Python int() Function


Python's built-in int() function converts an integer literal to an integer object, a float to integer, and a string to integer if the string itself has a valid integer
literal representation.

Using int() with an int object as argument is equivalent to declaring an int object directly.

<<< a = int(10)
<<< a
10

is same as −

<<< a = 10
<<< a
10
<<< type(a)
<class 'int>

If the argument to int() function is a float object or floating point expression, it returns an int object. For example −

<<< a = int(10.5) #converts a float object to int


<<< a
10
<<< a = int(2*3.14) #expression results float, is converted to int
<<< a
6
<<< type(a)
<class 'int'>

The int() function also returns integer 1 if a Boolean object is given as argument.

<<< a=int(True)
<<< a
1
<<< type(a)
<class 'int'>

String to Integer
The int() function returns an integer from a string object, only if it contains a valid integer representation.

<<< a = int("100")
<<< a
100
<<< type(a)
<class 'int'>
<<< a = ("10"+"01")
<<< a = int("10"+"01")
<<< a
1001
<<< type(a)
<class 'int'>

However, if the string contains a non-integer representation, Python raises ValueError.

<<< a = int("10.5")
Traceback (most recent call last):
File "", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.5'
<<< a = int("Hello World")
Traceback (most recent call last):
File "", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello World'

The int() function also returns integer from binary, octal and hexa-decimal string. For this, the function needs a base parameter which must be 2, 8 or 16
respectively. The string should have a valid binary/octal/Hexa-decimal representation.

Binary String to Integer


The string should be made up of 1 and 0 only, and the base should be 2.

<<< a = int("110011", 2)
<<< a
51

The Decimal equivalent of binary number 110011 is 51.

Octal String to Integer


The string should only contain 0 to 7 digits, and the base should be 8.

<<< a = int("20", 8)
<<< a
16

The Decimal equivalent of octal 20 is 16.

Hexa-Decimal String to Integer


The string should contain only the Hexadecimal symbols i.e., 0-9 and A, B, C, D, E or F. Base should be 16.

<<< a = int("2A9", 16)


<<< a
681

Decimal equivalent of Hexadecimal 2A9 is 681. You can easily verify these conversions with calculator app in Windows, Ubuntu or Smartphones.

Following is an example to convert number, float and string into integer data type:

Open Compiler

a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3") # c will be 3

print (a)
print (b)
print (c)

This produce the following result −

1 1
2 2
3 3
Python float() Function
The float() is a built-in function in Python. It returns a float object if the argument is a float literal, integer or a string with valid floating point representation.

Using float() with an float object as argument is equivalent to declaring a float object directly

<<< a = float(9.99)
<<< a
9.99
<<< type(a)
<class 'float'>

is same as −

<<< a = 9.99
<<< a
9.99
<<< type(a)
<class 'float'>

If the argument to float() function is an integer, the returned value is a floating point with fractional part set to 0.

<<< a = float(100)
<<< a
100.0
<<< type(a)
<class 'float'>

The float() function returns float object from a string, if the string contains a valid floating point number, otherwise ValueError is raised.

<<< a = float("9.99")
<<< a
9.99
<<< type(a)
<class 'float'>
<<< a = float("1,234.50")
Traceback (most recent call last):
File "", line 1, in <module>
ValueError: could not convert string to float: '1,234.50'

The reason of ValueError here is the presence of comma in the string.

For the purpose of string to float conversion, the sceientific notation of floating point is also considered valid.

<<< a = float("1.00E4")
<<< a
10000.0
<<< type(a)
<class 'float'>
<<< a = float("1.00E-4")
<<< a
0.0001
<<< type(a)
<class 'float'>

Following is an example to convert number, float and string into float data type:

Open Compiler

a = float(1) # a will be 1.0


b = float(2.2) # b will be 2.2
c = float("3.3") # c will be 3.3

print (a)
print (b)
print (c)

This produce the following result −

1 1.0
2 2.2
3 3.3
Python str() Function
We saw how a Python obtains integer or float number from corresponding string representation. The str() function works the opposite. It surrounds an integer
or a float object with quotes (') to return a str object. The str() function returns the string representation of any Python object. In this section, we shall see
different examples of str() function in Python.

The str() function has three parameters. First required parameter (or argument) is the object whose string representation we want. Other two operators,
encoding and errors, are optional.

We shall execute str() function in Python console to easily verify that the returned object is a string, with the enclosing quotation marks (').

Integer to string
You can convert any integer number into a string as follows:

<<< a = str(10)
<<< a
'10'
<<< type(a)
<class 'str'>

Float to String
str() function converts floating point objects with both the notations of floating point, standard notation with a decimal point separating integer and fractional
part, and the scientific notation to string object.

<<< a=str(11.10)
<<< a
'11.1'
<<< type(a)
<class 'str'>
<<< a = str(2/5)
<<< a
'0.4'
<<< type(a)
<class 'str'>

In the second case, a division expression is given as argument to str() function. Note that the expression is evaluated first and then result is converted to string.

Floating points in scientific notations using E or e and with positive or negative power are converted to string with str() function.

<<< a=str(10E4)
<<< a
'100000.0'
<<< type(a)
<class 'str'>
<<< a=str(1.23e-4)
<<< a
'0.000123'
<<< type(a)
<class 'str'>

When Boolean constant is entered as argument, it is surrounded by (') so that True becomes 'True'. List and Tuple objects can also be given argument to str()
function. The resultant string is the list/tuple surrounded by (').

<<< a=str('True')
<<< a
'True'
<<< a=str([1,2,3])
<<< a
'[1, 2, 3]'
<<< a=str((1,2,3))
<<< a
'(1, 2, 3)'
<<< a=str({1:100, 2:200, 3:300})
<<< a
'{1: 100, 2: 200, 3: 300}'

Following is an example to convert number, float and string into string data type:

Open Compiler
a = str(1) # a will be "1"
b = str(2.2) # b will be "2.2"
c = str("3.3") # c will be "3.3"

print (a)
print (b)
print (c)

This produce the following result −

1 1
2 2.2
3 3.3

Conversion of Sequence Types


List, Tuple and String are Python's sequence types. They are ordered or indexed collection of items.

A string and tuple can be converted into a list object by using the list() function. Similarly, the tuple() function converts a string or list to a tuple.

We shall take an object each of these three sequence types and study their inter-conversion.

<<< a=[1,2,3,4,5] # List Object


<<< b=(1,2,3,4,5) # Tupple Object
<<< c="Hello" # String Object

### list() separates each character in the string and builds the list
<<< obj=list(c)
<<< obj
['H', 'e', 'l', 'l', 'o']

### The parentheses of tuple are replaced by square brackets


<<< obj=list(b)
<<< obj
[1, 2, 3, 4, 5]

### tuple() separates each character from string and builds a tuple of characters
<<< obj=tuple(c)
<<< obj
('H', 'e', 'l', 'l', 'o')

### square brackets of list are replaced by parentheses.


<<< obj=tuple(a)
<<< obj
(1, 2, 3, 4, 5)

### str() function puts the list and tuple inside the quote symbols.
<<< obj=str(a)
<<< obj
'[1, 2, 3, 4, 5]'

<<< obj=str(b)
<<< obj
'(1, 2, 3, 4, 5)'

Thus Python's explicit type casting feature allows conversion of one data type to other with the help of its built-in functions.

Data Type Conversion Functions


There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted
value.

[Link]. Function & Description

1 Python int() functionConverts x to an integer. base specifies the base if x is a string.

2 Python long() functionConverts x to a long integer. base specifies the base if x is a string.

3 Python float() functionConverts x to a floating-point number.


[Link]. Function & Description

4 Python complex() functionCreates a complex number.

5 Python str() functionConverts object x to a string representation.

6 Python repr() functionConverts object x to an expression string.

7 Python eval() functionEvaluates a string and returns an object.

8 Python tuple() functionConverts s to a tuple.

9 Python list() functionConverts s to a list.

10 Python set() functionConverts s to a set.

11 Python dict() functionCreates a dictionary. d must be a sequence of (key,value) tuples.

12 Python frozenset() functionConverts s to a frozen set.

13 Python chr() functionConverts an integer to a character.

14 Python unichr() functionConverts an integer to a Unicode character.

15 Python ord() functionConverts a single character to its integer value.

16 Python hex() functionConverts an integer to a hexadecimal string.

17 Python oct() functionConverts an integer to an octal string.

Python - Unicode System


What is Unicode System?
Software applications often require to display messages output in a variety in different languages such as in English, French, Japanese, Hebrew, or Hindi.
Python's string type uses the Unicode Standard for representing characters. It makes the program possible to work with all these different possible characters.

A character is the smallest possible component of a text. 'A', 'B', 'C', etc., are all different characters. So are 'È' and 'Í'. A unicode string is a sequence of code
points, which are numbers from 0 through 0x10FFFF (1,114,111 decimal). This sequence of code points needs to be represented in memory as a set of code
units, and code units are then mapped to 8-bit bytes.

Character Encoding
A sequence of code points is represented in memory as a set of code units, mapped to 8-bit bytes. The rules for translating a Unicode string into a sequence of
bytes are called a character encoding.

Three types of encodings are present, UTF-8, UTF-16 and UTF-32. UTF stands for Unicode Transformation Format .

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python's Unicode Support

Python 3.0 onwards has built-in support for Unicode. The str type contains Unicode characters, hence any string created using single, double or the triple-
quoted string syntax is stored as Unicode. The default encoding for Python source code is UTF-8.

Hence, string may contain literal representation of a Unicode character (3/4) or its Unicode value (\u00BE).

Example
Open Compiler

var = "3/4"
print (var)
var = "\u00BE"
print (var)
This above code will produce the following output −

1 3/4
2 ¾

Example
In the following example, a string '10' is stored using the Unicode values of 1 and 0 which are \u0031 and u0030 respectively.

Open Compiler

var = "\u0031\u0030"
print (var)

It will produce the following output −

1 10

Strings display the text in a human-readable format, and bytes store the characters as binary data. Encoding converts data from a character string to a series of
bytes. Decoding translates the bytes back to human-readable characters and symbols. It is important not

to confuse these two methods. encode is a string method, while decode is a method of the Python byte object.

Example
In the following example, we have a string variable that consists of ASCII characters. ASCII is a subset of Unicode character set. The encode() method is used
to convert it into a bytes object.

Open Compiler

string = "Hello"
tobytes = [Link]('utf-8')
print (tobytes)
string = [Link]('utf-8')
print (string)

The decode() method converts byte object back to the str object. The encodeing method used is utf-8.

1 b'Hello'
2 Hello

Example
In the following example, the Rupee symbol (₹) is stored in the variable using its Unicode value. We convert the string to bytes and back to str.

Open Compiler

string = "\u20B9"
print (string)
tobytes = [Link]('utf-8')
print (tobytes)
string = [Link]('utf-8')
print (string)

When you execute the above code, it will produce the following output −

1 ₹
2 b'\xe2\x82\xb9'
3 ₹
Python - Literals
What are Python Literals?
Python literals or constants are the notation for representing a fixed value in source code. In contrast to variables, literals (123, 4.3, "Hello") are static values
or you can say constants which do not change throughout the operation of the program or application. For example, in the following assignment statement.

x = 10

Here 10 is a literal as numeric value representing 10, which is directly stored in memory. However,

y = x*2

Here, even if the expression evaluates to 20, it is not literally included in source code. You can also declare an int object with built-in int() function. However,
this is also an indirect way of instantiation and not with literal.

x = int(10)

Different Types of Python Literals


Python provides following literals which will be explained this tutorial:

Integer Literal
Float Literal
Complex Literal
String Literal
List Literal
Tuple Literal
Dictionary Literal

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python Integer Literal

Any representation involving only the digit symbols (0 to 9) creates an object of int type. The object so declared may be referred by a variable using an
assignment operator.

Integer literals consist three different types of different literal values decimal, octal, and hexadecimal literals.

1. Decimal Literal
Decimal literals represent the signed or unsigned numbers. Digitals from 0 to 9 are used to create a decimal literal value.

Look at the below statement assigning decimal literal to the variable −

x = 10
y = -25
z = 0

2. Octal Literal
Python allows an integer to be represented as an octal number or a hexadecimal number. A numeric representation with only eight digit symbols (0 to 7) but
prefixed by 0o or 0O is an octal number in Python.

Look at the below statement assigning octal literal to the variable −

x = 0O34
3. Hexadecimal Literal
Similarly, a series of hexadecimal symbols (0 to 9 and a to f), prefixed by 0x or 0X represents an integer in Hexedecimal form in Python.

Look at the below statement assigning hexadecimal literal to the variable −

x = 0X1C

However, it may be noted that, even if you use octal or hexadecimal literal notation, Python internally treats them as of int type.

Example
Open Compiler

# Using Octal notation


x = 0O34
print ("0O34 in octal is", x, type(x))
# Using Hexadecimal notation
x = 0X1c
print ("0X1c in Hexadecimal is", x, type(x))

When you run this code, it will produce the following output −

1 0O34 in octal is 28 <class 'int'>


2 0X1c in Hexadecimal is 28 <class 'int'>

Python Float Literal


A floating point number consists of an integral part and a fractional part. Conventionally, a decimal point symbol (.) separates these two parts in a literal
representation of a float. For example,

Example of Float Literal


x = 25.55
y = 0.05
z = -12.2345

For a floating point number which is too large or too small, where number of digits before or after decimal point is more, a scientific notation is used for a
compact literal representation. The symbol E or e followed by positive or negative integer, follows after the integer part.

Example of Float Scientific Notation Literal


For example, a number 1.23E05 is equivalent to 123000.00. Similarly, 1.23e-2 is equivalent to 0.0123

Open Compiler

# Using normal floating point notation


x = 1.23
print ("1.23 in normal float literal is", x, type(x))
# Using Scientific notation
x = 1.23E5
print ("1.23E5 in scientific notation is", x, type(x))
x = 1.23E-2
print ("1.23E-2 in scientific notation is", x, type(x))

Here, you will get the following output −

1 1.23 in normal float literal is 1.23 <class 'float'>


2 1.23E5 in scientific notation is 123000.0 <class 'float''>
3 1.23E-2 in scientific notation is 0.0123 <class 'float''>
Python Complex Literal
A complex number comprises of a real and imaginary component. The imaginary component is any number (integer or floating point) multiplied by square
root of "-1"

(√ −1). In literal representation (−1−−−√−1) is representation by "j" or "J". Hence, a literal representation of a complex number takes a form x+yj.

Example of Complex Type Literal


Open Compiler

#Using literal notation of complex number


x = 2+3j
print ("2+3j complex literal is", x, type(x))
y = 2.5+4.6j
print ("2.5+4.6j complex literal is", x, type(x))

This code will produce the following output −

1 2+3j complex literal is (2+3j) <class 'complex'>


2 2.5+4.6j complex literal is (2+3j) <class 'complex'>

Python String Literal


A string object is one of the sequence data types in Python. It is an immutable sequence of Unicode code points. Code point is a number corresponding to a
character according to Unicode standard. Strings are objects of Python's built-in class 'str'.

String literals are written by enclosing a sequence of characters in single quotes ('hello'), double quotes ("hello") or triple quotes ('''hello''' or """hello""").

Example of String Literal


Open Compiler

var1='hello'
print ("'hello' in single quotes is:", var1, type(var1))
var2="hello"
print ('"hello" in double quotes is:', var1, type(var1))
var3='''hello'''
print ("''''hello'''' in triple quotes is:", var1, type(var1))
var4="""hello"""
print ('"""hello""" in triple quotes is:', var1, type(var1))

Here, you will get the following output −

1 'hello' in single quotes is: hello <class 'str'>


2 "hello" in double quotes is: hello <class 'str'>
3 ''''hello'''' in triple quotes is: hello <class 'str'>
4 """hello""" in triple quotes is: hello <class 'str'>

Example of String Literal With Double Quoted Inside String


If it is required to embed double quotes as a part of string, the string itself should be put in single quotes. On the other hand, if single quoted text is to be
embedded, string should be written in double quotes.

Open Compiler

var1='Welcome to "Python Tutorial" from TutorialsPoint'


print (var1)
var2="Welcome to 'Python Tutorial' from TutorialsPoint"
print (var2)

It will produce the following output −

1 Welcome to "Python Tutorial" from TutorialsPoint


2 Welcome to 'Python Tutorial' from TutorialsPoint
Python List Literal
List object in Python is a collection of objects of other data type. List is an ordered collection of items not necessarily of same type. Individual object in the
collection is accessed by index starting with zero.

Literal representation of a list object is done with one or more items which are separated by comma and enclosed in square brackets [].

Example of List Type Literal


Open Compiler

L1=[1,"Ravi",75.50, True]
print (L1, type(L1))

It will produce the following output −

1 [1, 'Ravi', 75.5, True] <class 'list'>

Python Tuple Literal


Tuple object in Python is a collection of objects of other data type. Tuple is an ordered collection of items not necessarily of same type. Individual object in
the collection is accessed by index starting with zero.

Literal representation of a tuple object is done with one or more items which are separated by comma and enclosed in parentheses ().

Example of Tuple Type Literal


Open Compiler

T1=(1,"Ravi",75.50, True)
print (T1, type(T1))

It will produce the following output −

1 [1, 'Ravi', 75.5, True] <class tuple>

Example of Tuple Type Literal Without Parenthesis


Default delimiter for Python sequence is parentheses, which means a comma separated sequence without parentheses also amounts to declaration of a tuple.

Open Compiler

T1=1,"Ravi",75.50, True
print (T1, type(T1))

Here too, you will get the same output −

1 [1, 'Ravi', 75.5, True] <class tuple>

Python Dictionary Literal


Like list or tuple, dictionary is also a collection data type. However, it is not a sequence. It is an unordered collection of items, each of which is a key-value
pair. Value is bound to key by the ":" symbol. One or more key:value pairs separated by comma are put inside curly brackets to form a dictionary object.
Example of Dictionary Type Literal
Open Compiler

capitals={"USA":"New York", "France":"Paris", "Japan":"Tokyo",


"India":"New Delhi"}
numbers={1:"one", 2:"Two", 3:"three",4:"four"}
points={"p1":(10,10), "p2":(20,20)}

print (capitals, type(capitals))


print (numbers, type(numbers))
print (points, type(points))

Key should be an immutable object. Number, string or tuple can be used as key. Key cannot appear more than once in one collection. If a key appears more
than once, only the last one will be retained. Values can be of any data type. One value can be assigned to more than one keys. For example,

staff={"Krishna":"Officer", "Rajesh":"Manager", "Ragini":"officer", "Anil":"Clerk", "Kavita":"Manager"}

Python - Operators
Python Operators
Python operators are special symbols used to perform specific operations on one or more operands. The variables, values, or expressions can be used as
operands. For example, Python's addition operator ( + ) is used to perform addition operations on two variables, values, or expressions.

The following are some of the terms related to Python operators :

Unary operators : Python operators that require one operand to perform a specific operation are known as unary operators.
Binary operators : Python operators that require two operands to perform a specific operation are known as binary operators.
Operands : Variables, values, or expressions that are used with the operator to perform a specific operation.

Types of Python Operators


Python operators are categorized in the following categories −

Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators

Let us have a look at all the operators one by one.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python Arithmetic Operators

Python Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, etc.

The following table contains all arithmetic operators with their symbols, names, and examples (assume that the values of a and b are 10 and 20, respectively)

Operator Name Example

+ Addition a + b = 30

- Subtraction a – b = -10

* Multiplication a * b = 200

/ Division b/a=2

% Modulus b%a=0
Operator Name Example

** Exponent ab =1020

// Floor Division 9//2 = 4

Example of Python Arithmetic Operators


Open Compiler

a = 21
b = 10
c = 0

c=a+b
print ("a: {} b: {} a+b: {}".format(a,b,c))

c=a-b
print ("a: {} b: {} a-b: {}".format(a,b,c) )

c=a b
print ("a: {} b: {} ab: {}".format(a,b,c))

c=a/b
print ("a: {} b: {} a/b: {}".format(a,b,c))

c=a%b
print ("a: {} b: {} a%b: {}".format(a,b,c))

a=2
b=3
c = ab
print ("a: {} b: {} ab: {}".format(a,b,c))

a = 10
b=5
c = a//b
print ("a: {} b: {} a//b: {}".format(a,b,c))

Output

1 a: 21 b: 10 a+b: 31
2 a: 21 b: 10 a-b: 11
3 a: 21 b: 10 a*b: 210
4 a: 21 b: 10 a/b: 2.1
5 a: 21 b: 10 a%b: 1
6 a: 2 b: 3 a**b: 8
7 a: 10 b: 5 a//b: 2

Python Comparison Operators


Python Comparison operators compare the values on either side of them and decide the relation among them. They are also called Relational operators.

The following table contains all comparison operators with their symbols, names, and examples (assume that the values of a and b are 10 and 20,
respectively) −

Operator Name Example

== Equal (a == b) is not true.

!= Not equal (a != b) is true.

> Greater than (a > b) is not true.

< Less than (a < b) is true.

>= Greater than or equal to (a >= b) is not true.


Operator Name Example

<= Less than or equal to (a <= b) is true.

Example of Python Comparison Operators


Open Compiler

a = 21
b = 10
if ( a == b ):
print ("Line 1 - a is equal to b")
else:
print ("Line 1 - a is not equal to b")

if ( a != b ):
print ("Line 2 - a is not equal to b")
else:
print ("Line 2 - a is equal to b")

if ( a < b ):
print ("Line 3 - a is less than b" )
else:
print ("Line 3 - a is not less than b")

if ( a > b ):
print ("Line 4 - a is greater than b")
else:
print ("Line 4 - a is not greater than b")

a,b=b,a #values of a and b swapped. a becomes 10, b becomes 21

if ( a <= b ):
print ("Line 5 - a is either less than or equal to b")
else:
print ("Line 5 - a is neither less than nor equal to b")

if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to b")

Output

1 Line 1 - a is not equal to b


2 Line 2 - a is not equal to b
3 Line 3 - a is not less than b
4 Line 4 - a is greater than b
5 Line 5 - a is either less than or equal to b
6 Line 6 - b is either greater than or equal to b

Python Assignment Operators


Python Assignment operators are used to assign values to variables. Following is a table which shows all Python assignment operators.

The following table contains all assignment operators with their symbols, names, and examples −

Operator Example Same As

= a = 10 a = 10

+= a += 30 a = a + 30

-= a -= 15 a = a - 15

*= a *= 10 a = a * 10

/= a /= 5 a=a/5
Operator Example Same As

%= a %= 5 a=a%5

**= a **= 4 a = a ** 4

//= a //= 5 a = a // 5

&= a &= 5 a=a&5

= a

^= a ^= 5 a=a^5

>>= a >>= 5 a = a >> 5

<<= a <<= 5 a = a << 5

Example of Python Assignment Operators


Open Compiler

a = 21
b = 10
c = 0
print ("a: {} b: {} c : {}".format(a,b,c))
c = a + b
print ("a: {} c = a + b: {}".format(a,c))

c += a
print ("a: {} c += a: {}".format(a,c))

c *= a
print ("a: {} c *= a: {}".format(a,c))

c /= a
print ("a: {} c /= a : {}".format(a,c))

c =2
print ("a: {} b: {} c : {}".format(a,b,c))
c %= a
print ("a: {} c %= a: {}".format(a,c))

c=a
print ("a: {} c = a: {}".format(a,c))

c //= a
print ("a: {} c //= a: {}".format(a,c))

Output

1 a: 21 b: 10 c : 0
2 a: 21 c = a + b: 31
3 a: 21 c += a: 52
4 a: 21 c *= a: 1092
5 a: 21 c /= a : 52.0
6 a: 21 b: 10 c : 2
7 a: 21 c %= a: 2
8 a: 21 c **= a: 2097152
9 a: 21 c //= a: 99864

Python Bitwise Operators


Python Bitwise operator works on bits and performs bit by bit operation. These operators are used to compare binary numbers.

The following table contains all bitwise operators with their symbols, names, and examples −
Operator Name Example

& AND a&b

OR

^ XOR a^b

~ NOT ~a

<< Zero fill left shift a << 3

>> Signed right shift a >> 3

Example of Python Bitwise Operators


Open Compiler

a = 20
b = 10

print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c=0

c = a & b;
print ("result of AND is ", c,':',bin(c))

c = a | b;
print ("result of OR is ", c,':',bin(c))

c = a ^ b;
print ("result of EXOR is ", c,':',bin(c))

c = ~a;
print ("result of COMPLEMENT is ", c,':',bin(c))

c = a << 2;
print ("result of LEFT SHIFT is ", c,':',bin(c))

c = a >> 2;
print ("result of RIGHT SHIFT is ", c,':',bin(c))

Output

1 a= 20 : 0b10100 b= 10 : 0b1010
2 result of AND is 0 : 0b0
3 result of OR is 30 : 0b11110
4 result of EXOR is 30 : 0b11110
5 result of COMPLEMENT is -21 : -0b10101
6 result of LEFT SHIFT is 80 : 0b1010000
7 result of RIGHT SHIFT is 5 : 0b101

Python Logical Operators


Python logical operators are used to combile two or more conditions and check the final result. There are following logical operators supported by Python
language. Assume variable a holds 10 and variable b holds 20 then

The following table contains all logical operators with their symbols, names, and examples −

Operator Name Example

and AND a and b

or OR a or b

not NOT not(a)


Example of Python Logical Operators
Open Compiler

var = 5

print(var > 3 and var < 10)


print(var > 3 or var < 4)
print(not (var > 3 and var < 10))

Output

1 True
2 True
3 False

Python Membership Operators


Python's membership operators test for membership in a sequence, such as strings, lists, or tuples.

There are two membership operators as explained below −

Operator Description Example

in Returns True if it finds a variable in the specified sequence, false otherwise. a in b

not in returns True if it does not finds a variable in the specified sequence and false otherwise. a not in b

Example of Python Membership Operators


Open Compiler

a = 10
b = 20
list = [1, 2, 3, 4, 5 ]

print ("a:", a, "b:", b, "list:", list)

if ( a in list ):
print ("a is present in the given list")
else:
print ("a is not present in the given list")

if ( b not in list ):
print ("b is not present in the given list")
else:
print ("b is present in the given list")

c=b/a
print ("c:", c, "list:", list)
if ( c in list ):
print ("c is available in the given list")
else:
print ("c is not available in the given list")

Output

1 a: 10 b: 20 list: [1, 2, 3, 4, 5]
2 a is not present in the given list
3 b is not present in the given list
4 c: 2.0 list: [1, 2, 3, 4, 5]
5 c is available in the given list

Python Identity Operators


Python identity operators compare the memory locations of two objects.
There are two Identity operators explained below −

Operator Description Example

is Returns True if both variables are the same object and false otherwise. a is b

is not Returns True if both variables are not the same object and false otherwise. a is not b

Example of Python Identity Operators


Open Compiler

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a

print(a is c)
print(a is b)

print(a is not c)
print(a is not b)

Output

1 True
2 False
3 False
4 True

Python Operators Precedence


Operators precedence decides the order of the evaluation in which an operator is evaluated. Python operators have different levels of precedence. The
following table contains the list of operators having highest to lowest precedence −

The following table lists all operators from highest precedence to lowest.

[Link]. Operator & Description

1 **Exponentiation (raise to the power)

2 ~ + -Complement, unary plus and minus (method names for the last two are +@ and -@)

3 * / % //Multiply, divide, modulo and floor division

4 + -Addition and subtraction

5 >> <<Right and left bitwise shift

6 &Bitwise 'AND'

7 **^

8 <= < > >=Comparison operators

9 <> == !=Equality operators

10 = %= /= //= -= += *= =**Assignment operators

11 is is notIdentity operators

12 in not inMembership operators

13 not or andLogical operators


Python Arithmetic Operators
Python arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, division, and more on numbers.
Arithmetic operators are binary operators in the sense they operate on two operands. Python fully supports mixed arithmetic. That is, the two operands can be
of two different number types. In such a situation.

Types of Arithmetic Operators


Following is the table which lists down all the arithmetic operators available in Python:

Operator Name Example

+ Addition a + b = 30

- Subtraction a – b = -10

* Multiplication a * b = 200

/ Division b/a=2

% Modulus b%a=0

** Exponent ab =1020

// Floor Division 9//2 = 4

Let us study these operators with examples.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Addition Operator

The addition operator represents by + symbol. It is a basic arithmetic operator. It adds the two numeric operands on the either side and returns the addition
result.

Example to add two integer numbers


In the following example, the two integer variables are the operands for the "+" operator.

Open Compiler

a=10
b=20
print ("Addition of two integers")
print ("a =",a,"b =",b,"addition =",a+b)

It will produce the following output −

1 Addition of two integers


2 a = 10 b = 20 addition = 30

Example to add integer and float numbers


Addition of integer and float results in a float.

Open Compiler

a=10
b=20.5
print ("Addition of integer and float")
print ("a =",a,"b =",b,"addition =",a+b)

It will produce the following output −

1 Addition of integer and float


2 a = 10 b = 20.5 addition = 30.5
Example to add two complex numbers
The result of adding float to complex is a complex number.

Open Compiler

a=10+5j
b=20.5
print ("Addition of complex and float")
print ("a=",a,"b=",b,"addition=",a+b)

It will produce the following output −

1 Addition of complex and float


2 a= (10+5j) b= 20.5 addition= (30.5+5j)

Subtraction Operator
The subtraction operator represents by - symbol. It subtracts the second operand from the first. The resultant number is negative if the second operand is
larger.

Example to subtract two integer numbers


First example shows subtraction of two integers.

Open Compiler

a=10
b=20
print ("Subtraction of two integers:")
print ("a =",a,"b =",b,"a-b =",a-b)
print ("a =",a,"b =",b,"b-a =",b-a)

Result −

1 Subtraction of two integers


2 a = 10 b = 20 a-b = -10
3 a = 10 b = 20 b-a = 10

Example to subtract integer and float numbers


Subtraction of an integer and a float follows the same principle.

Open Compiler

a=10
b=20.5
print ("subtraction of integer and float")
print ("a=",a,"b=",b,"a-b=",a-b)
print ("a=",a,"b=",b,"b-a=",b-a)

It will produce the following output −

1 subtraction of integer and float


2 a= 10 b= 20.5 a-b= -10.5
3 a= 10 b= 20.5 b-a= 10.5
Example to subtract complex numbers
In the subtraction involving a complex and a float, real component is involved in the operation.

Open Compiler

a=10+5j
b=20.5
print ("subtraction of complex and float")
print ("a=",a,"b=",b,"a-b=",a-b)
print ("a=",a,"b=",b,"b-a=",b-a)

It will produce the following output −

1 subtraction of complex and float


2 a= (10+5j) b= 20.5 a-b= (-10.5+5j)
3 a= (10+5j) b= 20.5 b-a= (10.5-5j)

Multiplication Operator
The * (asterisk) symbol is defined as a multiplication operator in Python (as in many languages). It returns the product of the two operands on its either side.
If any of the operands negative, the result is also negative. If both are negative, the result is positive. Changing the order of operands doesn't change the result

Example to multiply two integers


Open Compiler

a=10
b=20
print ("Multiplication of two integers")
print ("a =",a,"b =",b,"a*b =",a*b)

It will produce the following output −

1 Multiplication of two integers


2 a = 10 b = 20 a*b = 200

Example to multiply integer and float numbers


In multiplication, a float operand may have a standard decimal point notation, or a scientific notation.

Open Compiler

a=10
b=20.5
print ("Multiplication of integer and float")
print ("a=",a,"b=",b,"a*b=",a*b)

a=-5.55
b=6.75E-3
print ("Multiplication of float and float")
print ("a =",a,"b =",b,"ab =",ab)

It will produce the following output −

1 Multiplication of integer and float


2 a = 10 b = 20.5 a-b = -10.5
3 Multiplication of float and float
4 a = -5.55 b = 0.00675 a*b = -0.037462499999999996
Example to multiply complex numbers
For the multiplication operation involving one complex operand, the other operand multiplies both the real part and imaginary part.

Open Compiler

a=10+5j
b=20.5
print ("Multiplication of complex and float")
print ("a =",a,"b =",b,"a*b =",a*b)

It will produce the following output −

1 Multiplication of complex and float


2 a = (10+5j) b = 20.5 a*b = (205+102.5j)

Division Operator
The "/" symbol is usually called as forward slash. The result of division operator is numerator (left operand) divided by denominator (right operand). The
resultant number is negative if any of the operands is negative. Since infinity cannot be stored in the memory, Python raises ZeroDivisionError if the
denominator is 0.

The result of division operator in Python is always a float, even if both operands are integers.

Example to divide two numbers


Open Compiler

a=10
b=20
print ("Division of two integers")
print ("a=",a,"b=",b,"a/b=",a/b)
print ("a=",a,"b=",b,"b/a=",b/a)

It will produce the following output −

1 Division of two integers


2 a= 10 b= 20 a/b= 0.5
3 a= 10 b= 20 b/a= 2.0

Example to divide two float numbers


In Division, a float operand may have a standard decimal point notation, or a scientific notation.

Open Compiler

a=10
b=-20.5
print ("Division of integer and float")
print ("a=",a,"b=",b,"a/b=",a/b)
a=-2.50
b=1.25E2
print ("Division of float and float")
print ("a=",a,"b=",b,"a/b=",a/b)

It will produce the following output −

1 Division of integer and float


2 a= 10 b= -20.5 a/b= -0.4878048780487805
3 Division of float and float
4 a= -2.5 b= 125.0 a/b= -0.02
Example to divide complex numbers
When one of the operands is a complex number, division between the other operand and both parts of complex number (real and imaginary) object takes
place.

Open Compiler

a=7.5+7.5j
b=2.5
print ("Division of complex and float")
print ("a =",a,"b =",b,"a/b =",a/b)
print ("a =",a,"b =",b,"b/a =",b/a)

It will produce the following output −

1 Division of complex and float


2 a = (7.5+7.5j) b = 2.5 a/b = (3+3j)
3 a = (7.5+7.5j) b = 2.5 b/a = (0.16666666666666666-0.16666666666666666j)

If the numerator is 0, the result of division is always 0 except when denominator is 0, in which case, Python raises ZeroDivisionError wirh Division by Zero
error message.

Open Compiler

a=0
b=2.5
print ("a=",a,"b=",b,"a/b=",a/b)
print ("a=",a,"b=",b,"b/a=",b/a)

It will produce the following output −

1 a= 0 b= 2.5 a/b= 0.0


2 Traceback (most recent call last):
3 File "C:\Users\mlath\examples\[Link]", line 20, in <module>
4 print ("a=",a,"b=",b,"b/a=",b/a)
5 ~^~
6 ZeroDivisionError: float division by zero

Modulus Operator
Python defines the "%" symbol, which is known aa Percent symbol, as Modulus (or modulo) operator. It returns the remainder after the denominator divides
the numerator. It can also be called Remainder operator. The result of the modulus operator is the number that remains after the integer quotient. To give an
example, when 10 is divided by 3, the quotient is 3 and remainder is 1. Hence, 10%3 (normally pronounced as 10 mod 3) results in 1.

Example for modulus operation on integers


If both the operands are integer, the modulus value is an integer. If numerator is completely divisible, remainder is 0. If numerator is smaller than
denominator, modulus is equal to the numerator. If denominator is 0, Python raises ZeroDivisionError.

Open Compiler

a=10
b=2
print ("a=",a, "b=",b, "a%b=", a%b)
a=10
b=4
print ("a=",a, "b=",b, "a%b=", a%b)
print ("a=",a, "b=",b, "b%a=", b%a)
a=0
b=10
print ("a=",a, "b=",b, "a%b=", a%b)
print ("a=", a, "b=", b, "b%a=",b%a)

It will produce the following output −


1 a= 10 b= 2 a%b= 0
2 a= 10 b= 4 a%b= 2
3 a= 10 b= 4 b%a= 4
4 a= 0 b= 10 a%b= 0
5 Traceback (most recent call last):
6 File "C:\Users\mlath\examples\[Link]", line 13, in <module>
7 print ("a=", a, "b=", b, "b%a=",b%a)
8 ~^~
9 ZeroDivisionError: integer modulo by zero

Example for modulus operation on floats


If any of the operands is a float, the mod value is always float.

Open Compiler

a=10
b=2.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=10
b=1.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=7.7
b=2.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=12.4
b=3
print ("a=",a, "b=",b, "a%b=", a%b)

It will produce the following output −

1 a= 10 b= 2.5 a%b= 0.0


2 a= 10 b= 1.5 a%b= 1.0
3 a= 7.7 b= 2.5 a%b= 0.20000000000000018
4 a= 12.4 b= 3 a%b= 0.40000000000000036

Python doesn't accept complex numbers to be used as operand in modulus operation. It throws TypeError: unsupported operand type(s) for %.

Exponent Operator
Python uses ** (double asterisk) as the exponent operator (sometimes called raised to operator). So, for a**b, you say a raised to b, or even bth power of a.

If in the exponentiation expression, both operands are integer, result is also an integer. In case either one is a float, the result is float. Similarly, if either one
operand is complex number, exponent operator returns a complex number.

If the base is 0, the result is 0, and if the index is 0 then the result is always 1.

Example of exponent operator


Open Compiler

a=10
b=2
print ("a=",a, "b=",b, "a**b=", a**b)
a=10
b=1.5
print ("a=",a, "b=",b, "a**b=", a**b)
a=7.7
b=2
print ("a=",a, "b=",b, "a**b=", a**b)
a=1+2j
b=4
print ("a=",a, "b=",b, "a**b=", a**b)
a=12.4
b=0
print ("a=",a, "b=",b, "a**b=", a**b)
print ("a=",a, "b=",b, "b**a=", b**a)
It will produce the following output −

1 a= 10 b= 2 a**b= 100
2 a= 10 b= 1.5 a**b= 31.622776601683793
3 a= 7.7 b= 2 a**b= 59.290000000000006
4 a= (1+2j) b= 4 a**b= (-7-24j)
5 a= 12.4 b= 0 a**b= 1.0
6 a= 12.4 b= 0 b**a= 0.0

Floor Division Operator


Floor division is also called as integer division. Python uses // (double forward slash) symbol for the purpose. Unlike the modulus or modulo which returns
the remainder, the floor division gives the quotient of the division of operands involved.

If both operands are positive, floor operator returns a number with fractional part removed from it. For example, the floor division of 9.8 by 2 returns 4 (pure
division is 4.9, strip the fractional part, result is 4).

But if one of the operands is negative, the result is rounded away from zero (towards negative infinity). Floor division of -9.8 by 2 returns 5 (pure division is
-4.9, rounded away from 0).

Example of floor division operator


Open Compiler

a=9
b=2
print ("a=",a, "b=",b, "a//b=", a//b)
a=9
b=-2
print ("a=",a, "b=",b, "a//b=", a//b)
a=10
b=1.5
print ("a=",a, "b=",b, "a//b=", a//b)
a=-10
b=1.5
print ("a=",a, "b=",b, "a//b=", a//b)

It will produce the following output −

1 a= 9 b= 2 a//b= 4
2 a= 9 b= -2 a//b= -5
3 a= 10 b= 1.5 a//b= 6.0
4 a= -10 b= 1.5 a//b= -7.0

Precedence and Associativity of Arithmetic Operators

Operator(s) Description Associativity

** Exponent Operator Associativity of Exponent operator is fromRight to Left .

%, *, /, // Modulus, Multiplication, Division, and Floor Associativity of Modulus, Multiplication, Division, and Floor Division operators are
Division fromLeft to Right .

+, – Addition and Subtraction Operators Associativity of Addition and Subtraction operators are fromLeft to Right .

The following table shows the precedence and associativity of the arithmetic operators in Python.

Arithmetic Operators with Complex Numbers


Arithmetic operators behave slightly differently when the both operands are complex number objects.
Addition and subtraction of complex numbers
Addition and subtraction of complex numbers is a simple addition/subtraction of respective real and imaginary components.

Open Compiler

a=2.5+3.4j
b=-3+1.0j
print ("Addition of complex numbers - a=",a, "b=",b, "a+b=", a+b)
print ("Subtraction of complex numbers - a=",a, "b=",b, "a-b=", a-b)

It will produce the following output −

1 Addition of complex numbers - a= (2.5+3.4j) b= (-3+1j) a+b= (-0.5+4.4j)


2 Subtraction of complex numbers - a= (2.5+3.4j) b= (-3+1j) a-b= (5.5+2.4j)

Multiplication of complex numbers


Multiplication of complex numbers is similar to multiplication of two binomials in algebra. If "a+bj" and "x+yj" are two complex numbers, then their
multiplication is given by this formula −

(a+bj)*(x+yj) = ax+ayj+xbj+byj2 = (ax-by)+(ay+xb)j

For example,

a=6+4j
b=3+2j
c=a*b
c=(18-8)+(12+12)j
c=10+24j

The following program confirms the result −

a=6+4j
b=3+2j
print ("Multplication of complex numbers - a=",a, "b=",b, "a*b=", a*b)

To understand the how the division of two complex numbers takes place, we should use the conjugate of a complex number. Python's complex object has a
conjugate() method that returns a complex number with the sign of imaginary part reversed.

>>> a=5+6j
>>> [Link]()
(5-6j)

Division of complex numbers


To divide two complex numbers, divide and multiply the numerator as well as the denominator with the conjugate of denominator.

a=6+4j
b=3+2j
c=a/b
c=(6+4j)/(3+2j)
c=(6+4j)*(3-2j)/3+2j)*(3-2j)
c=(18-12j+12j+8)/(9-6j+6j+4)
c=26/13
c=2+0j

To verify, run the following code −

Open Compiler

a=6+4j
b=3+2j
print ("Division of complex numbers - a=",a, "b=",b, "a/b=", a/b)

Complex class in Python doesn't support the modulus operator (%) and floor division operator (//).
Python Comparison Operators
Comparison operators in Python are very important in Python's conditional statements (if, else and elif) and looping statements (while and for loops). The
comparison operators also called relational operators . Some of the well known operators are "<" stands for less than, and ">" stands for greater than
operator.

Python uses two more operators, combining "=" symbol with these two. The "<=" symbol is for less than or equal to operator and the ">=" symbol is for
greater than or equal to operator.

Different Comparison Operators in Python


Python has two more comparison operators in the form of "==" and "!=". They are for is equal to and is not equal to operators. Hence, there are six
comparison operators in Python and they are listed below in this table:

< Less than a<b

> Greater than a>b

<= Less than or equal to a<=b

>= Greater than or equal to a>=b

== Is equal to a==b

!= Is not equal to a!=b

Comparison operators are binary in nature, requiring two operands. An expression involving a comparison operator is called a Boolean expression, and
always returns either True or False.

Example
Open Compiler

a=5
b=7
print (a>b)
print (a<b)

It will produce the following output −

1 False
2 True

Both the operands may be Python literals, variables or expressions. Since Python supports mixed arithmetic, you can have any number type operands.

Example
The following code demonstrates the use of Python's comparison operators with integer numbers −

Open Compiler

print ("Both operands are integer")


a=5
b=7
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a,a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output** −**

[Learn Python** in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.](http
s://[Link]/certification/complete-python-prime-pack/[Link]?utm_source=tutorialspoint&utm_medium=python_tutorial_3p&utm_campai
gn=internal)## Comparison of Float Number**

In the following example, an integer and a float operand are compared.


Example
Open Compiler

It will produce the following output −

Comparison of Complex umbers


Although complex object is a number data type in Python, its behavior is different from others. Python doesn't support < and > operators, however it does
support equality (==) and inequality (!=) operators.

Example
Open Compiler

It will produce the following output −

You get a TypeError with less than or greater than operators.

Example
Open Compiler

**It will produce the following output −**

**Comparison of Booleans**
**Boolean objects in Python are really integers: True is 1 and False is 0. In fact, Python treats any non-zero number as True. In Python, comparison of
Boolean objects is possible. "False < True" is True!**

**Example**
**Open Compiler**

**It will produce the following output −**

**Comparison of Sequence Types**


**In Python, comparison of only similar sequence objects can be performed. A string object is comparable with another string only. A list cannot be compared
with a tuple, even if both have same items.**

**Example**
**Open Compiler**

**It will produce the following output −**

**Sequence objects are compared by lexicographical ordering mechanism. The comparison starts from item at 0th index. If they are equal, comparison moves
to next index till the items at certain index happen to be not equal, or one of the sequences is exhausted. If one sequence is an initial sub-sequence of the
other, the shorter sequence is the smaller (lesser) one.**

**Which of the operands is greater depends on the difference in values of items at the index where they are unequal. For example, 'BAT'>'BAR' is True, as T
comes after R in Unicode order.**

**If all items of two sequences compare equal, the sequences are considered equal.**
**Example**
**Open Compiler**

**It will produce the following output −**

**In the following example, two tuple objects are compared −**

**Example**
**Open Compiler**

**It will produce the following output −**

**Comparison of Dictionary Objects**


**The use of "<" and ">" operators for Python's dictionary is not defined. In case of these operands, TypeError: '<' not supported between instances of 'dict'
and 'dict' is reported.**

**Equality comparison checks if the length of both the dict items is same. Length of dictionary is the number of key-value pairs in it.**

**Python dictionaries are simply compared by length. The dictionary with fewer elements is considered less than a dictionary with more elements.**

**Example**
**Open Compiler**

**It will produce the following output −**

**Python Assignment Operator**


**The = (equal to) symbol is defined as assignment operator in Python. The value of Python expression on its right is assigned to a single variable on its left.
The = symbol as in programming in general (and Python in particular) should not be confused with its usage in Mathematics, where it states that the
expressions on the either side of the symbol are equal.**

**Example of Assignment Operator in Python**


**Consider following Python statements −**

**At the first instance, at least for somebody new to programming but who knows maths, the statement "a=a+b" looks strange. How could a be equal to
"a+b"? However, it needs to be reemphasized that the = symbol is an assignment operator here and not used to show the equality of LHS and RHS.**

**Because it is an assignment, the expression on right evaluates to 15, the value is assigned to a.**

**In the statement "a+=b", the two operators "+" and "=" can be combined in a "+=" operator. It is called as add and assign operator. In a single statement, it
performs addition of two operands "a" and "b", and result is assigned to operand on left, i.e., "a".**

**Augmented Assignment Operators in Python**


**In addition to the simple assignment operator, Python provides few more assignment operators for advanced use. They are called cumulative or augmented
assignment operators. In this chapter, we shall learn to use augmented assignment operators defined in Python.**

**Python has the augmented assignment operators for all arithmetic and comparison operators.**

**Python augmented assignment operators combines addition and assignment in one statement. Since Python supports mixed arithmetic, the two operands
may be of different types. However, the type of left operand changes to the operand of on right, if it is wider.**
**Example**
**The += operator is an augmented operator. It is also called cumulative addition operator, as it adds "b" in "a" and assigns the result back to a variable.**

**The following are the augmented assignment operators in Python:**

**Augmented Addition Operator**


**Augmented Subtraction Operator**
**Augmented Multiplication Operator**
**Augmented Division Operator**
**Augmented Modulus Operator**
**Augmented Exponent Operator**
**Augmented Floor division Operator**

**Augmented Addition Operator (+=)**


**Following examples will help in understanding how the "+=" operator works −**

**Open Compiler**

**It will produce the following output −**

**Augmented Subtraction Operator (-=)**


**Use -= symbol to perform subtract and assign operations in a single statement. The "a-=b" statement performs "a=a-b" assignment. Operands may be of any
number type. Python performs implicit type casting on the object which is narrower in size.**

**Open Compiler**

**It will produce the following output −**

**Augmented Multiplication Operator (*=)**


**The "=" operator works on similar principle. "a=b" performs multiply and assign operations, and is equivalent to "a=a*b". In case of augmented
multiplication of two complex numbers, the rule of multiplication as discussed in the previous chapter is applicable.**

**Open Compiler**

**It will produce the following output −**

**Augmented Division Operator (/=)**


**The combination symbol "/=" acts as divide and assignment operator, hence "a/=b" is equivalent to "a=a/b". The division operation of int or float operands
is float. Division of two complex numbers returns a complex number. Given below are examples of augmented division operator.**

**Open Compiler**

**It will produce the following output −**

**Augmented Modulus Operator (%=)**


**To perform modulus and assignment operation in a single statement, use the %= operator. Like the mod operator, its augmented version also is not
supported for complex number.**

**Open Compiler**

**It will produce the following output −**


**Augmented Exponent Operator (=)****
**The "=" operator results in computation of "a" raised to "b", and assigning the value back to "a". Given below are some examples −****

**Open Compiler**

**It will produce the following output −**

**Augmented Floor division Operator (//=)**


**For performing floor division and assignment in a single statement, use the "//=" operator. "a//=b" is equivalent to "a=a//b". This operator cannot be used
with complex numbers.**

**Open Compiler**

**It will produce the following output −**

**Python Logical Operators**


**Python logical operators are used to form compound Boolean expressions. Each operand for these logical operators is itself a Boolean expression. For
example,**

**Example**
**Along with the keyword False, Python interprets None, numeric zero of all types, and empty sequences (strings, tuples, lists), empty dictionaries, and
empty sets as False. All other values are treated as True.**

**There are three logical operators in Python. They are " and ", " or " and " not ". They must be in lowercase.**

**Logical "and" Operator**


**For the compound Boolean expression to be True, both the operands must be True. If any or both operands evaluate to False, the expression returns
False.**

**Logical "and" Operator Truth Table**


**The following table shows the scenarios.**

a b a and b

F F F

F T F

T F F

T T T

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Logical "or" Operator**

**In contrast, the or operator returns True if any of the operands is True. For the compound Boolean expression to be False, both the operands have to be
False.**
**Logical "or" Operator Truth Table**
**The following tables shows the result of the "or" operator with different conditions:**

a b a or b

F F F

F T T

T F T

T T T

**Logical "not" Operator**


**This is a unary operator. The state of Boolean operand that follows, is reversed. As a result, not True becomes False and not False becomes True.**

**Logical "not" Operator Truth Table**

a not (a)

F T

T F

**How the Python interpreter evaluates the logical operators?**


**The expression "x and y" first evaluates "x". If "x" is false, its value is returned; otherwise, "y" is evaluated and the resulting value is returned.**

**The expression "x or y" first evaluates "x"; if "x" is true, its value is returned; otherwise, "y" is evaluated and the resulting value is returned.**

**Python Logical Operators Examples**


**Some use cases of logical operators are given below −**

**Example 1: Logical Operators With Boolean Conditions**


**Open Compiler**

**It will produce the following output −**

**Example 2: Logical Operators With Non- Boolean Conditions**


**We can use non-boolean operands with logical operators. Here, we need to not that any non-zero numbers, and non-empty sequences evaluate to True.
Hence, the same truth tables of logical operators apply.**

**In the following example, numeric operands are used for logical operators. The variables "x", "y" evaluate to True, "z" is False**

**Open Compiler**

**It will produce the following output −**


**Example 3: Logical Operators With Strings and Tuples**
**The string variable is treated as True and an empty tuple as False in the following example −**

**Open Compiler**

**It will produce the following output −**

**Example 4: Logical Operators To Compare Sequences (Lists)**


**Finally, two list objects below are non-empty. Hence x and y returns the latter, and x or y returns the former.**

**Open Compiler**

**It will produce the following output −**

**Python Bitwise Operators**


**Python bitwise operators are normally used to perform bitwise operations on integer-type objects. However, instead of treating the object as a whole, it is
treated as a string of bits. Different operations are done on each bit in the string.**

**Python has six bitwise operators - &, |, ^, ~, << and >>. All these operators (except ~) are binary in nature, in the sense they operate on two operands. Each
operand is a binary digit (bit) 1 or 0.**

**The following are the bitwise operators in Python -**

**Bitwise AND Operator**


**Bitwise OR Operator**
**Bitwise XOR Operator**
**Bitwise NOT Operator**
**Bitwise Left Shift Operator**
**Biwtise Right Shift Operator**

**Python Bitwise AND Operator (&)**


**Bitwise AND operator is somewhat similar to logical and operator. It returns True only if both the bit operands are 1 (i.e. True). All the combinations are
−**

**When you use integers as the operands, both are converted in equivalent binary, the & operation is done on corresponding bit from each number, starting
from the least significant bit and going towards most significant bit.**

**Example of Bitwise AND Operator in Python**


**Let us take two integers 60 and 13, and assign them to variables a and b respectively.**

**Open Compiler**

**It will produce the following output −**

**To understand how Python performs the operation, obtain the binary equivalent of each variable.**

**It will produce the following output −**

**For the sake of convenience, use the standard 8-bit format for each number, so that "a" is 00111100 and "b" is 00001101. Let us manually perform and
operation on each corresponding bits of these two numbers.**

**Convert the resultant binary back to integer. You'll get 12, which was the result obtained earlier.**

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python Bitwise OR Operator (|)**

**The "|" symbol (called pipe ) is the bitwise OR operator. If any bit operand is 1, the result is 1 otherwise it is 0.**
**Example of Bitwise OR Operator in Python**
**Take the same values of a=60, b=13. The "|" operation results in 61. Obtain their binary equivalents.**

**Open Compiler**

**It will produce the following output −**

**To perform the "|" operation manually, use the 8-bit format.**

**Convert the binary number back to integer to tally the result −**

**Python Bitwise XOR Operator (^)**


**The term XOR stands for exclusive OR. It means that the result of OR operation on two bits will be 1 if only one of the bits is 1.**

**Example of Bitwise XOR Operator in Python**


**Let us perform XOR operation on a=60 and b=13.**

**Open Compiler**

**It will produce the following output −**

**We now perform the bitwise XOR manually.**

**The int() function shows 00110001 to be 49.**

**Python Bitwise NOT Operator (~)**


**This operator is the binary equivalent of logical NOT operator. It flips each bit so that 1 is replaced by 0, and 0 by 1, and returns the complement of the
original number. Python uses 2's complement method. For positive integers, it is obtained simply by reversing the bits. For negative number, -x, it is written
using the bit pattern for (x-1) with all of the bits complemented (switched from 1 to 0 or 0 to 1). Hence: (for 8 bit representation)**

**Example of Bitwise NOT Operator in Python**


**For a=60, its complement is −**

**Open Compiler**

**It will produce the following output −**

**Python Bitwise Left Shift Operator (<<)**


**Left shift operator shifts most significant bits to right by the number on the right side of the "<<" symbol. Hence, "x << 2" causes two bits of the binary
representation of to right.**

**Example of Bitwise Left Shift Operator in Python**


**Let us perform left shift on 60.**

**Open Compiler**

**It will produce the following output −**

**How does this take place? Let us use the binary equivalent of 60, and perform the left shift by 2.**

**Convert the binary to integer. It is 240.**


**Python Bitwise Right Shift Operator (>>)**
**Right shift operator shifts least significant bits to left by the number on the right side of the ">>" symbol. Hence, "x >> 2" causes two bits of the binary
representation of to left.**

**Example of Bitwise Right Shift Operator in Python**


**Let us perform right shift on 60.**

**Open Compiler**

**It will produce the following output −**

**Manual right shift operation on 60 is shown below −**

**Use int() function to covert the above binary number to integer. It is 15.**

**Python Membership Operators**


**The membership operators in Python help us determine whether an item is present in a given container type object, or in other words, whether an item is a
member of the given container type object.**

**Types of Python Membership Operators**


**Python has two membership operators: in and not in . Both return a Boolean result. The result of in operator is opposite to that of not in operator.**

**The 'in' Operator**


**The " in " operator is used to check whether a substring is present in a bigger string, any item is present in a list or tuple, or a sub-list or sub-tuple is
included in a list or tuple.**

**Example of Python Membership "in" Operator**


**In the following example, different substrings are checked whether they belong to the string var="TutorialsPoint". Python differentiates characters on the
basis of their Unicode value. Hence "To" is not the same as "to". Also note that if the "in" operator returns True, the "not in" operator evaluates to False.**

**Open Compiler**

**It will produce the following output −**

**The 'not in' Operator**


**The "not in" operator is used to check a sequence with the given value is not present in the object like string, list, tuple, etc.**

**Example of Python Membership "not in" Operator**


**Open Compiler**

**It will produce the following output −**

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Membership Operator with Lists and Tuples**

**You can use the "in/not in" operator to check the membership of an item in the list or tuple.**

**Open Compiler**

**It will produce the following output −**

**In the last case, "d" is a float but still it compares to True with 10 (an int ) in the list. Even if a number expressed in other formats like binary, octal or
hexadecimal are given the membership operators tell if it is inside the sequence.**
**Example**
**However, if you try to check if two successive numbers are present in a list or tuple, the in operator returns False. If the list/tuple contains the successive
numbers as a sequence itself, then it returns True.**

**Open Compiler**

**It will produce the following output −**

**Membership Operator with Sets**


**Python's membership operators also work well with the set objects.**

**Open Compiler**

**It will produce the following output −**

**Membership Operator with Dictionaries**


**Use of in as well as not in operators with dictionary object is allowed. However, Python checks the membership only with the collection of keys and not
values.**

**Open Compiler**

**It will produce the following output −**

**Python Identity Operators**


**The identity operators compare the objects to determine whether they share the same memory and refer to the same object type (data type).**

**Python provided two identity operators; we have listed them as follows:**

**' is ' Operator**


**' is not ' Operator**

**Python 'is' Operator**


**The ' is ' operator evaluates to True if both the operand objects share the same memory location. The memory location of the object can be obtained by the
"id()" function. If the "id()" of both variables is same, the "is" operator returns True.**

**Example of Python Identity 'is' Operator**


**Open Compiler**

**It will produce the following output −**

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python 'is not' Operator**

**The ' is not ' operator evaluates to True if both the operand objects do not share the same memory location or both operands are not the same objects.**

**Example of Python Identity 'is not' Operator**


**Open Compiler**

**It will produce the following output −**


**Python Identity Operators Examples with Explanations**

**Example 1**
**Open Compiler**

**It will produce the following output −**

**The list and tuple objects behave differently, which might look strange in the first instance. In the following example, two lists "a" and "b" contain same
items. But their id() differs.**

**Example 2**
**Open Compiler**

**It will produce the following output −**

**The list or tuple contains the memory locations of individual items only and not the items itself. Hence "a" contains the addresses of 10,20 and 30 integer
objects in a certain location which may be different from that of "b".**

**Example 3**
**It will produce the following output −**

**Because of two different locations of "a" and "b", the " is " operator returns False even if the two lists contain same numbers.**

**Python Operator Precedence**


**An expression may have multiple operators to be evaluated. The operator precedence defines the order in which operators are evaluated. In other words, the
order of operator evaluation is determined by the operator precedence.**

**If a certain expression contains multiple operators, their order of evaluation is determined by the order of precedence. For example, consider the following
expression**

**Here, what will be the value of a ? - yes it will be 17 (multiply 3 by 5 first and then add 2) or 25 (adding 2 and 3 and then multiply with 5)? Python’s
operator precedence rule comes into picture here.**

**If we consider only the arithmetic operators in Python, the traditional BODMAS rule is also employed by Python interpreter, where the brackets are
evaluated first, the division and multiplication operators next, followed by addition and subtraction operators. Hence, a will become 17 in the above
expression.**

**In addition to the operator precedence, the associativity of operators is also important. If an expression consists of operators with same level of precedence,
the associativity determines the order. Most of the operators have left to right associativity. It means, the operator on the left is evaluated before the one on the
right.**

**Let us consider another expression:**

**In this case, both * (multiplication) and / (division) operators have same level of precedence. However, the left to right associativity rule performs the
division first (10/5 = 2) and then the multiplication (2*4 = 8).**

**Python Operator Precedence Table**


**The following table lists all the operators in Python in their decreasing order of precedence. Operators in the same cell under the Operators column have the
same precedence.**

[Link]. Operator & Description

1 (),[], {}Parentheses and braces

2 [index], [index:index]Subscription, slicing,

3 await xAwait expression


[Link]. Operator & Description

4 **Exponentiation

5 +x, -x, ~xPositive, negative, bitwise NOT

6 *, @, /, //, %Multiplication, matrix multiplication, division, floor division, remainder

7 +, -Addition and subtraction

8 <<, >>Left Shifts, Right Shifts

9 &Bitwise AND

10 ^Bitwise XOR

11 **

12 in, not in, is, is not, <, <=, >, >=, !=, ==Comparisons, including membership tests and identity tests

13 not xBoolean NOT

14 andBoolean AND

15 orBoolean OR

16 if – elseConditional expression

17 lambdaLambda expression

18 :=Walrus operator

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python Operator Precedence Example**

**Open Compiler**

**When you execute the above program, it produces the following result −**

**Python Comments**
**Python comments are programmer-readable explanation or annotations in the Python source code. They are added with the purpose of making the source
code easier for humans to understand, and are ignored by Python interpreter. Comments enhance the readability of the code and help the programmers to
understand the code very carefully.**

**Example**
**If we execute the code given below, the output produced will simply print "Hello, World!" to the console, as comments are ignored by the Python
interpreter and do not affect the execution of the program −**

**Open Compiler**

**Python supports three types of comments as shown below −**

**Single-line comments**
**Multi-line comments**
**Docstring Comments**

**Single Line Comments in Python**


**Single-line comments in Python start with a hash symbol (#) and extend to the end of the line. They are used to provide short explanations or notes about
the code. They can be placed on their own line above the code they describe, or at the end of a line of code (known as an inline comment) to provide context
or clarification about that specific line.**
**Example: Standalone Single-Line Comment**
**A standalone single-line comment is a comment that occupies an entire line by itself, starting with a hash symbol (#). It is placed above the code it
describes or annotates.**

**In this example, the standalone single-line comment is placed above the "greet" function "−**

**Open Compiler**

**Example: Inline Single-Line Comment**


**An inline single-line comment is a comment that appears on the same line as a piece of code, following the code and preceded by a hash symbol (#).**

**In here, the inline single-line comment follows the print("Hello, World!") statement −**

**Open Compiler**

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Multi Line Comments in Python**

**In Python, multi-line comments are used to provide longer explanations or notes that span multiple lines. While Python does not have a specific syntax for
multi-line comments, there are two common ways to achieve this: consecutive single-line comments and triple-quoted strings −**

**Consecutive Single-Line Comments**


**Consecutive single-line comments refers to using the hash symbol (#) at the beginning of each line. This method is often used for longer explanations or to
section off parts of the code.**

**Example**

**In this example, multiple lines of comments are used to explain the purpose and logic of the factorial function −**

**Open Compiler**

**Multi Line Comment Using Triple Quoted Strings**


**We can use triple-quoted strings (''' or """) to create multi-line comments. These strings are technically string literals but can be used as comments if they
are not assigned to any variable or used in expressions.**

**This pattern is often used for block comments or when documenting sections of code that require detailed explanations.**

**Example**

**Here, the triple-quoted string provides a detailed explanation of the "gcd" function, describing its purpose and the algorithm used −**

**Open Compiler**

**Using Comments for Documentation**


**In Python, documentation comments, also known as docstrings, provide a way to incorporate documentation within your code. This can be useful for
explaining the purpose and usage of modules, classes, functions, and methods. Effective use of documentation comments helps other developers understand
your code and its purpose without needing to read through all the details of the implementation.**

**Python Docstrings**
**In Python, docstrings are a special type of comment that is used to document modules, classes, functions, and methods. They are written using triple quotes
(''' or """) and are placed immediately after the definition of the entity they document.**

**Docstrings can be accessed programmatically, making them an integral part of Python’s built-in documentation tools.**

**Example of a Function Docstring**


**Open Compiler**

**Accessing Docstrings**
**Docstrings can be accessed using the .doc attribute or the help() function. This makes it easy to view the documentation for any module, class, function, or
method directly from the interactive Python shell or within the code.**

**Example: Using the .doc attribute**

**Open Compiler**

**Example: Using the help() Function**

**Open Compiler**

**Provide User Input in Python**


**In this chapter, we will learn how Python accepts the user input from the console, and displays the output on the same console.**

**Every computer application should have a provision to accept input from the user when it is running. This makes the application interactive. Depending on
how it is developed, an application may accept the user input in the form of text entered in the console ([Link]) , a graphical layout, or a web-based
interface.**

**Python User Input Functions**


**Python provides us with two built-in functions to read the input from the keyboard.**

**The input () Function**


**The raw_input () Function**

**Python interpreter works in interactive and scripted mode. While the interactive mode is good for quick evaluations, it is less productive. For repeated
execution of same set of instructions, scripted mode should be used.**

**Let us write a simple Python script to start with.**

**Open Compiler**

**Save the above code as [Link] and run it from the command-line. Here's the output**

**The program simply prints the values of the two variables in it. If you run the program repeatedly, the same output will be displayed every time. To use the
program for another name and city, you can edit the code, change name to say "Ravi" and city to "Chennai". Every time you need to assign different value,
you will have to edit the program, save and run, which is not the ideal way.**

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
The input() Function**

**Obviously, you need some mechanism to assign different value to the variable in the runtime − while the program is running. Python's input() function
does the same job.**

**Following is the syntax of Python's standard library input() function.**

**When the interpreter encounters input() function, it waits for the user to enter data from the standard input stream (keyboard) till the Enter key is pressed.
The sequence of characters may be stored in a string variable for further use.**

**On reading the Enter key, the program proceeds to the next statement. Let use change our program to store the user input in name and city variables.**

**When you run, you will find the cursor waiting for user's input. Enter values for name and city. Using the entered data, the output will be displayed.**

**Now, the variables are not assigned any specific value in the program. Every time you run, different values can be input. So, your program has become
truly interactive.**

**Inside the input() function, you may give a prompt text, which will appear before the cursor when you run the code.**

**When you run the program displays the prompt message, basically helping the user what to enter.**
**The raw_input() Function**
**The raw_input() function works similar to input() function. Here only point is that this function was available in Python 2.7, and it has been renamed to
input() in Python 3.6**

**Following is the syntax of the raw_input() function:**

**Let's re-write the above program using raw_input() function:**

**When you run, you will find the cursor waiting for user's input. Enter values for name and city. Using the entered data, the output will be displayed.**

**Taking Numeric Input in Python**


**Let us write a Python code that accepts width and height of a rectangle from the user and computes the area.**

**Run the program, and enter width and height.**

**Why do you get a TypeError here? The reason is, Python always read the user input as a string. Hence, width="20" and height="30" are the strings and
obviously you cannot perform multiplication of two strings.**

**To overcome this problem, we shall use int() , another built-in function from Python's standard library. It converts a string object to an integer.**

**To accept an integer input from the user, read the input in a string, and type cast it to integer with int() function −**

**You can combine the input and type cast statements in one −**

**Now you can input any integer value to the two variables in the program −**

**Python's float() function converts a string into a float object. The following program accepts the user input and parses it to a float variable − rate, and
computes the interest on an amount which is also input by the user.**

**The program ask user to enter amount and rate; and displays the result as follows −**

**The print() Function**


**Python's print() function is a built-in function. It is the most frequently used function, that displays value of Python expression given in parenthesis, on
Python's console, or standard output ([Link]) .**

**Open Compiler**

**Any number of Python expressions can be there inside the parenthesis. They must be separated by comma symbol. Each item in the list may be any Python
object, or a valid Python expression.**

**The first call to print() displays a string literal and a string variable. The second prints value of two variables and their subtraction. The pow() function
computes the square root of a number and square value of a variable.**

**If there are multiple comma separated objects in the print() function's parenthesis, the values are separated by a white space " ". To use any other character
as a separator, define a sep parameter for the print() function. This parameter should follow the list of expressions to be printed.**

**In the following output of print() function, the variables are separated by comma.**

**Open Compiler**

**The effect of sep=',' can be seen in the result −**

**The print() function issues a newline character ('\n') at the end, by default. As a result, the output of the next print() statement appears in the next line of the
console.**

**Open Compiler**

**Two lines are displayed as the output −**

**To make these two lines appear in the same line, define end parameter in the first print() function and set it to a whitespace string " ".**

**Open Compiler**

**Output of both the print() functions appear in continuation.**

**Python has built-in support to store and process numeric data ( Python Numbers ). Most of the times you work with numbers in almost every Python
application. Obviously, any computer application deals with numbers. This tutorial will discuss about different types of Python Numbers and their
properties.**
**Python - Number Types**
**There are three built-in number types available in Python:**

**integers (int)**
**floating point numbers (float)**
**complex numbers**

**Python also has a bult-in Boolean data type called bool . It can be treated as a sub-type of int type, since it's two possible values True and False represent
the integers 1 and 0 respectively.**

**Python − Integer Numbers**


**In Python, any number without the provision to store a fractional part is an integer. (Note that if the fractional part in a number is 0, it doesn't mean that it is
an integer. For example a number 10.0 is not an integer, it is a float with 0 fractional part whose numeric value is 10.) An integer can be zero, positive or a
negative whole number. For example, 1234, 0, -55 all represent to integers in Python.**

**There are three ways to form an integer object. With (a) literal representation, (b) any expression evaluating to an integer, and (c) using int() function.**

**Literal is a notation used to represent a constant directly in the source code. For example −**

**However, look at the following assignment of the integer variable c .**

**Open Compiler**

**It will produce the following output −**

**Here, c is indeed an integer variable, but the expression a + b is evaluated first, and its value is indirectly assigned to c .**

**The third method of forming an integer object is with the return value of int() function. It converts a floating point number or a string in an integer.**

**You can represent an integer as a binary, octal or Hexa-decimal number. However, internally the object is stored as an integer.**

**Binary Numbers in Python**


**A number consisting of only the binary digits (1 and 0) and prefixed with "0b" is a binary number. If you assign a binary number to a variable, it still is an
int variable.**

**A represent an integer in binary form, store it directly as a literal, or use int() function, in which the base is set to 2**

**Open Compiler**

**It will produce the following output −**

**There is also a bin() function in Python. It returns a binary string equivalent of an integer.**

**Open Compiler**

**It will produce the following output −**

**Octal Numbers in Python**


**An octal number is made up of digits 0 to 7 only. In order to specify that the integer uses octal notation, it needs to be prefixed by "0o" (lowercase O) or
"0O" (uppercase O). A literal representation of octal number is as follows −**

**Open Compiler**

**It will produce the following output −**

**Note that the object is internally stored as integer. Decimal equivalent of octal number 107 is 71.**

**Since octal number system has 8 symbols (0 to 7), its base is 7. Hence, while using int() function to covert an octal string to integer, you need to set the
base argument to 8.**

**Open Compiler**

**It will produce the following output −**


**Decimal equivalent of octal 30 is 16.**

**In the following code, two int objects are obtained from octal notations and their addition is performed.**

**Open Compiler**

**It will produce the following output −**

**To obtain the octal string for an integer, use oct() function.**

**Open Compiler**

**Hexa-decimal Numbers in Python**


**As the name suggests, there are 16 symbols in the Hexadecimal number system. They are 0-9 and A to F. The first 10 digits are same as decimal digits. The
alphabets A, B, C, D, E and F are equivalents of 11, 12, 13, 14, 15, and 16 respectively. Upper or lower cases may be used for these letter symbols.**

**For the literal representation of an integer in Hexadecimal notation, prefix it by "0x" or "0X" .**

**Open Compiler**

**It will produce the following output −**

**To convert a Hexadecimal string to integer, set the base to 16 in the int() function.**

**Open Compiler**

**Try out the following code snippet. It takes a Hexadecimal string, and returns the integer.**

**Open Compiler**

**It will produce the following output −**

**However, if the string contains any symbol apart from the Hexadecimal symbol chart an error will be generated.**

**Open Compiler**

**The above program generates the following error −**

**Python's standard library has hex() function, with which you can obtain a hexadecimal equivalent of an integer.**

**Open Compiler**

**It will produce the following output −**

**Though an integer can be represented as binary or octal or hexadecimal, internally it is still integer. So, when performing arithmetic operation, the
representation doesn't matter.**

**Open Compiler**

**It will produce the following output −**

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python − Floating Point Numbers**

**A floating point number has an integer part and a fractional part, separated by a decimal point symbol (.). By default, the number is positive, prefix a dash
(-) symbol for a negative number.**

**A floating point number is an object of Python's float class. To store a float object, you may use a literal notation, use the value of an arithmetic expression,
or use the return value of float() function.**

**Using literal is the most direct way. Just assign a number with fractional part to a variable. Each of the following statements declares a float object.**

**In Python, there is no restriction on how many digits after the decimal point can a floating point number have. However, to shorten the representation, the
E or e symbol is used. E stands for Ten raised to. For example, E4 is 10 raised to 4 (or 4th power of 10), e-3 is 10 raised to -3.**

**In scientific notation, number has a coefficient and exponent part. The coefficient should be a float greater than or equal to 1 but less than 10. Hence,
1.23E+3, 9.9E-5, and 1E10 are the examples of floats with scientific notation.**

**The second approach of forming a float object is indirect, using the result of an expression. Here, the quotient of two floats is assigned to a variable, which
refers to a float object.**

**Open Compiler**

**It will produce the following output −**


**Python's float() function returns a float object, parsing a number or a string if it has the appropriate contents. If no arguments are given in the parenthesis, it
returns 0.0, and for an int argument, fractional part with 0 is added.**

**Even if the integer is expressed in binary, octal or hexadecimal, the float() function returns a float with fractional part as 0.**

**Open Compiler**

**It will produce the following output −**

**The float() function retrieves a floating point number out of a string that encloses a float, either in standard decimal point format, or having scientific
notation.**

**Open Compiler**

**It will produce the following output −**

**In mathematics, infinity is an abstract concept. Physically, infinitely large number can never be stored in any amount of memory. For most of the computer
hardware configurations, however, a very large number with 400th power of 10 is represented by Inf. If you use "Infinity" as argument for float() function, it
returns Inf.**

**Open Compiler**

**It will produce the following output −**

**One more such entity is Nan (stands for Not a Number). It represents any value that is undefined or not representable.**

**Python − Complex Numbers**


**In this section, we shall know in detail about Complex data type in Python. Complex numbers find their applications in mathematical equations and laws in
electromagnetism, electronics, optics, and quantum theory. Fourier transforms use complex numbers. They are Used in calculations with wavefunctions,
designing filters, signal integrity in digital electronics, radio astronomy, etc.**

**A complex number consists of a real part and an imaginary part, separated by either "+" or "−". The real part can be any floating point (or itself a complex
number) number. The imaginary part is also a float/complex, but multiplied by an imaginary number.**

**In mathematics, an imaginary number "i" is defined as the square root of -1 (−1−−−√−1). Therefore, a complex number is represented as "x+yi", where x is
the real part, and "y" is the coefficient of imaginary part.**

**Quite often, the symbol "j" is used instead of "I" for the imaginary number, to avoid confusion with its usage as current in theory of electricity. Python also
uses "j" as the imaginary number. Hence, "x+yj" is the representation of complex number in Python.**

**Like int or float data type, a complex object can be formed with literal representation or using complex() function. All the following statements form a
complex object.**

**Note that the real part as well as the coefficient of imaginary part have to be floats, and they may be expressed in standard decimal point notation or
scientific notation.**

**Python's complex() function helps in forming an object of complex type. The function receives arguments for real and imaginary part, and returns the
complex number.**

**There are two versions of complex() function, with two arguments and with one argument. Use of complex() with two arguments is straightforward. It uses
first argument as real part and second as coefficient of imaginary part.**

**Open Compiler**

**It will produce the following output −**

**In the above example, we have used x and y as float parameters. They can even be of complex data type.**

**Open Compiler**

**It will produce the following output −**

**Surprised by the above example? Put "x" as 1+2j and "y" as 2-3j. Try to perform manual computation of "x+yj" and you'll come to know.**

**If you use only one numeric argument for complex() function, it treats it as the value of real part; and imaginary part is set to 0.**

**Open Compiler**

**It will produce the following output −**

**The complex() function can also parse a string into a complex number if its only argument is a string having complex number representation.**

**In the following snippet, user is asked to input a complex number. It is used as argument. Since Python reads the input as a string, the function extracts the
complex object from it.**

**Open Compiler**
**It will produce the following output −**

**Python's built-in complex class has two attributes real and imag − they return the real and coefficient of imaginary part from the object.**

**Open Compiler**

**It will produce the following output −**

**The complex class also defines a conjugate() method. It returns another complex number with the sign of imaginary component reversed. For example,
conjugate of x+yj is x-yj.**

**Number Type Conversion**


**Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number
explicitly from one type to another to satisfy the requirements of an operator or function parameter.**

**Type int(x) to convert x to a plain integer.**


**Type long(x) to convert x to a long integer.**
**Type float(x) to convert x to a floating-point number.**
**Type complex(x) to convert x to a complex number with real part x and imaginary part zero. In the same way type complex(x, y) to convert x and y to a
complex number with real part x and imaginary part y. x and y are numeric expressions**

**Let us see various numeric and math-related functions.**

**Theoretic and Representation Functions**


**Python includes following theoretic and representation Functions in the math module −**

[Link]. Function & Description

1 [Link](x)The ceiling of x: the smallest integer not less than x

2 [Link](n,k)This function is used to find the returns the number of ways to choose "x" items from "y" items without repetition and without
order.

3 [Link](x, y)This function returns a float with the magnitude (absolute value) of x but the sign of y.

4 [Link](x, y)This function is used to compare the values of to objects. This function is deprecated in Python3.

5 [Link](x)This function is used to calculate the absolute value of a given integer.

6 [Link](n)This function is used to find the factorial of a given integer.

7 [Link](x)This function calculates the floor value of a given integer.

8 [Link](x, y)The fmod() function in math module returns same result as the "%" operator. However fmod() gives more accurate result of
modulo division than modulo operator.

9 [Link](x)This function is used to calculate the mantissa and exponent of a given number.

10 [Link](iterable)This function returns the floating point sum of all numeric items in an iterable i.e. list, tuple, array.

11 [Link](*integers)This function is used to calculate the greatest common divisor of all the given integers.

12 [Link]()This function is used to determine whether two given numeric values are close to each other.

13 [Link](x)This function is used to determine whether the given number is a finite number.

14 [Link](x)This function is used to determine whether the given value is infinity (+ve or, -ve).

15 [Link](x)This function is used to determine whether the given number is "NaN".

16 [Link](n)This function calculates the integer square-root of the given non negative integer.

17 [Link](*integers)This function is used to calculate the least common factor of the given integer arguments.

18 [Link](x, i)This function returns product of first number with exponent of second number. So, ldexp(x,y) returns x*2**y. This is inverse of
frexp() function.
[Link]. Function & Description

19 [Link](x)This returns the fractional and integer parts of x in a two-item tuple.

20 [Link](x, y, steps)This function returns the next floating-point value after x towards y.

21 [Link](n, k)This function is used to calculate the permutation. It returns the number of ways to choose x items from y items without
repetition and with order.

22 [Link](iterable, *, start)This function is used to calculate the product of all numeric items in the iterable (list, tuple) given as argument.

23 [Link](x,y)This function returns the remainder of x with respect to y. This is the difference x − n*y, where n is the integer closest to
the quotient x / y.

24 [Link](x)This function returns integral part of the number, removing the fractional part. trunc() is equivalent to floor() for positive x, and
equivalent to ceil() for negative x.

25 [Link](x)This function returns the value of the least significant bit of the float x. trunc() is equivalent to floor() for positive x, and equivalent
to ceil() for negative x.

**Power and Logarithmic Functions**


[Link]. Function & Description

1 [Link](x)This function is used to calculate the cube root of a number.

2 [Link](x)This function calculate the exponential of x: ex

3 math.exp2(x)This function returns 2 raised to power x. It is equivalent to 2**x.

4 math.expm1(x)This function returns e raised to the power x, minus 1. Here e is the base of natural logarithms.

5 [Link](x)This function calculates the natural logarithm of x, for x> 0.

6 math.log1p(x)This function returns the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

7 math.log2(x)This function returns the base-2 logarithm of x. This is usually more accurate than log(x, 2).

8 math.log10(x)The base-10 logarithm of x for x> 0.

9 [Link](x, y)The value of x**y.

10 [Link](x)The square root of x for x > 0

**Trigonometric Functions**
**Python includes following functions that perform trigonometric calculations in the math module −**

[Link]. Function & Description

1 [Link](x)This function returns the arc cosine of x, in radians.

2 [Link](x)This function returns the arc sine of x, in radians.

3 [Link](x)This function returns the arc tangent of x, in radians.

4 math.atan2(y, x)This function returns atan(y / x), in radians.

5 [Link](x)This function returns the cosine of x radians.

6 [Link](x)This function returns the sine of x radians.

7 [Link](x)This function returns the tangent of x radians.

8 [Link](x, y)This function returns the Euclidean norm, sqrt(xx + yy).


**Angular conversion Functions**
**Following are the angular conversion function provided by Python math module −**

[Link]. Function & Description

1 [Link](x)This function converts the given angle from radians to degrees.

2 [Link](x)This function converts the given angle from degrees to radians.

**Mathematical Constants**
**The Python math module defines the following mathematical constants −**

[Link]. Constants & Description

1 [Link] represents the mathematical constant pi, which equals to "3.141592..." to available precision.

2 [Link] represents the mathematical constant e, which is equal to "2.718281..." to available precision.

3 [Link] represents the mathematical constant Tau (denoted by τ ). It is equivalent to the ratio of circumference to radius, and is equal to 2Π
.

4 [Link] represents positive infinity. For negative infinity use "−[Link]" .

5 [Link] constant is a floating-point "not a number" (NaN) value. Its value is equivalent to the output of float('nan').

**Hyperbolic Functions**
**Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas instead of circles. Following are the hyperbolic functions of the
Python math module −**

[Link]. Function & Description

1 [Link](x)This function is used to calculate the inverse hyperbolic cosine of the given value.

2 [Link](x)This function is used to calculate the inverse hyperbolic sine of a given number.

3 [Link](x)This function is used to calculate the inverse hyperbolic tangent of a number.

4 [Link](x)This function is used to calculate the hyperbolic cosine of the given value.

5 [Link](x)This function is used to calculate the hyperbolic sine of a given number.

6 [Link](x)This function is used to calculate the hyperbolic tangent of a number.

**Special Functions**
**Following are the special functions provided by the Python math module −**

[Link]. Function & Description

1 [Link](x)This function returns the value of the Gauss error function for the given parameter.

2 [Link](x)This function is the complementary for the error function. Value of erf(x) is equivalent to 1-erf(x) .

3 [Link](x)This is used to calculate the factorial of the complex numbers. It is defined for all the complex numbers except the non-positive
integers.

4 [Link](x)This function is used to calculate the natural logarithm of the absolute value of the Gamma function at x.
**Random Number Functions**
**Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions in the random
module.**

[Link]. Function & Description

1 [Link](seq)A random item from a list, tuple, or string.

2 [Link]([start,] stop [,step])A randomly selected element from range(start, stop, step)

3 [Link]()A random float r, such that 0 is less than or equal to r and r is less than 1

4 [Link]([x])This function sets the integer starting value used in generating random numbers. Call this function before calling any other
random module function. Returns None.

5 [Link](seq)This function is used to randomize the items of the given sequence.

6 [Link](a, b)This function returns a random floating point value r, such that a is less than or equal to r and r is less than b.

**Built-in Mathematical Functions**


**Following mathematical functions are built into the Python interpreter, hence you don't need to import them from any module.**

[Link]. Function & Description

1 Python abs() functionThe abs() function returns the absolute value of x, i.e. the positive distance between x and zero.

2 Python max() functionThe max() function returns the largest of its arguments or largest number from the iterable (list or tuple).

3 Python min() functionThe function min() returns the smallest of its arguments i.e. the value closest to negative infinity, or smallest number from
the iterable (list or tuple)

4 Python pow() functionThe pow() function returns x raised to y. It is equivalent to x**y.

5 Python round() Functionround() is a built-in function in Python. It returns x rounded to n digits from the decimal point.

6 Python sum() functionThe sum() function returns the sum of all numeric items in any iterable (list or tuple). It has an optional start argument
which is 0 by default. If given, the numbers in the list are added to start value.

**Python Booleans (bool)**


**In Python, bool is a sub-type of int type. A bool object has two possible values, and it is initialized with Python keywords, True and False .**

**Example**
**A bool object is accepted as argument to type conversion functions. With True as argument, the int() function returns 1, float() returns 1.0; whereas for
False, they return 0 and 0.0 respectively. We have a one argument version of complex() function.**

**If the argument is a complex object, it is taken as real part, setting the imaginary coefficient to 0.**

**Example**
**Open Compiler**

**On running this code, you will get the following output −**
**Python Boolean Expression**
**Python boolean expression is an expression that evaluates to a Boolean value. It almost always involves a comparison operator. In the below example we
will see how the comparison operators can give us the Boolean values. The bool() method is used to return the truth value of an expresison.**

**Below we have examples which use numbers streams and Boolean values as parameters to the bool function. The results come out as true or false
depending on the parameter.**

**Example**
**Open Compiler**

**Python - Control Flow**


**Python program control flow is regulated by various types of conditional statements, loops, and function calls. By default, the instructions in a computer
program are executed in a sequential manner, from top to bottom, or from start to end. However, such sequentially executing programs can perform only
simplistic tasks. We would like the program to have a decision-making ability, so that it performs different steps depending on different conditions.**

**Most programming languages including Python provide functionality to control the flow of execution of instructions. Normally, there are two type of
control flow statements in any programming language and Python also supports them.**

**Decision Making Statements**


**Decision making statements are used in the Python programs to make them able to decide which of the alternative group of instructions to be executed,
depending on value of a certain Boolean expression.**

**The following diagram illustrates how decision-making statements work −**

**The if Statements**
**Python provides if..elif..else control statements as a part of decision marking. It consists of three different blocks, which are if block, elif (short of else if)
block and else block.**

**Example**
**Following is a simple example which makes use of if..elif..else. You can try to run this program using different marks and verify the result.**

**Open Compiler**

**This will produce following result:**

**The match Statement**


**Python supports Match-Case statement, which can also be used as a part of decision making. If a pattern matches the expression, the code under that case
will execute.**

**Example**
**Following is a simple example which makes use of match statement.**

**Open Compiler**

**This will produce following result:**


**Loops or Iteration Statements**
**Most of the processes require a group of instructions to be repeatedly executed. In programming terminology, it is called a loop . Instead of the next step, if
the flow is redirected towards any earlier step, it constitutes a loop.**

**The following diagram illustrates how the looping works −**

**If the control goes back unconditionally, it forms an infinite loop which is not desired as the rest of the code would never get executed.**

**In a conditional loop, the repeated iteration of block of statements goes on till a certain condition is met. Python supports a number of loops like for loop,
while loop which we will study in next chapters.**

**The for Loop**


**The for loop iterates over the items of any sequence, such as a list, tuple or a string .**

**Example**
**Following is an example which makes use of For Loop to iterate through an array in Python:**

**Open Compiler**

**This will produce following result:**

**The while Loop**


**The while loop repeatedly executes a target statement as long as a given boolean expression is true.**

**Example**
**Following is an example which makes use of While Loop to print first 5 numbers in Python:**

**Open Compiler**

**This will produce following result:**

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Jump Statements**

**The jump statements are used to jump on a specific statement by breaking the current flow of the program. In Python, there are two jump statements break
and continue.**

**The break Statement**


**It terminates the current loop and resumes execution at the next statement.**

**Example**
**The following example demonstrates the use of break statement −**

**Open Compiler**

**This will produce following result:**

**The continue Statement**


**It skips the execution of the program block and returns the control to the beginning of the current loop to start the next iteration.**
**Example**
**The following example demonstrates the use of continue statement −**

**Open Compiler**

**This will produce following result:**

**Python - Decision Making**


**Python's decision making functionality is in its keywords − if..elif...else . The if keyword requires a boolean expression, followed by colon (:) symbol. The
colon (:) symbol starts an indented block. The statements with the same level of indentation are executed if the boolean expression in if statement is True .
If the expression is not True (False), the interpreter bypasses the indented block and proceeds to execute statements at earlier indentation level.**

**Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which
statements to execute if outcome is TRUE or FALSE otherwise.**

**Following is the general form of a typical decision making structure found in most of the programming languages −**

**Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null , then it is assumed as FALSE value.**

**Types of Decision Making Statements in Python**


**Python programming language provides following types of decision making statements. Click the following links to check their detail.**

[Link]. Statement & Description

1 if statementsAn if statement consists of a boolean expression followed by one or more statements.

2 if...else statementsAn if statement can be followed by an optional else statement , which executes when the boolean expression is FALSE.

3 nested if statementsYou can use one if or else if statement inside another if or else if statement(s).

**Let us go through each decision making briefly −**

**Single Statement Suites**


**If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.**

**Example**
**Here is an example of a one-line if clause −**

**Open Compiler**

**When the above code is executed, it produces the following result −**

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
if...else statement**

**In this decision making statement, if the if condition is true, then the statements within this block are executed, otherwise, the else block is executed.**

**The program will choose which block of code to execute based on whether the condition in the if statement is true or false.**
**Example**
**The following example shows the use of if...else statement.**

**Open Compiler**

**On running the above code, it will show the following output −**

**Nested if statements**
**A nested if is another decision making statement in which one if statement resides inside another. It allows us to check multiple conditions sequentially.**

**Example**
**In this example, we will see the use of nested-if statement.**

**Open Compiler**

**On executing the above code, it will display the below output −**

**Python If Statement**
**The if statement in Python evaluates whether a condition is true or false. It contains a logical expression that compares data, and a decision is made based
on the result of the comparison.**

**Syntax of the if Statement**


**If the boolean expression evaluates to TRUE, then the statement(s) inside the if block is executed. If boolean expression evaluates to FALSE, then the first
set of code after the end of the if block is executed.**

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Flow Diagram (Flowchart) of the if Statement**

**The below diagram shows flowchart of the if statement −**

**Example of Python if Statement**


**Let us consider an example of a customer entitled to 10% discount if his purchase amount is > 1000; if not, then no discount is applicable. The following
flowchart shows the whole decision making process −**

**First, set a discount variable to 0 and an amount variable to 1200. Then, use an if statement to check whether the amount is greater than 1000. If this
condition is true, calculate the discount amount. If a discount is applicable, deduct it from the original amount.**

**Python code for the above flowchart can be written as follows −**

**Open Compiler**

**Here the amout is 1200, hence discount 120 is deducted. On executing the code, you will get the following output −**

**Change the variable amount to 800, and run the code again. This time, no discount is applicable. And, you will get the following output −**

**Python if else Statement**


**The if-else statement in Python is used to execute a block of code when the condition in the if statement is true, and another block of code when the
condition is false.**
**Syntax of if-else Statement**
**The syntax of an if-else statement in Python is as follows −**

**If the boolean expression evaluates to TRUE, then the statement(s) inside the if block will be executed otherwise statements of the else block will be
executed.**

**Flowchart of if-else Statement**


**This flowchart shows how if-else statement is used −**

**If the expr is True, block of stmt1, 2, 3 is executed then the default flow continues with stmt7. However, if the expr is False, block stmt4, 5, 6 runs then the
default flow continues.**

**Python implementation of the above flowchart is as follows −**

**Python if-else Statement Example**


**Let us understand the use of if-else statements with the following example. Here, variable age can take different values. If the expression age > 18 is true,
then eligible to vote message will be displayed otherwise not eligible to vote message will be displayed. Following flowchart illustrates this logic −**

**Now, let's see the Python implementation the above flowchart.**

**Open Compiler**

**On executing this code, you will get the following output −**

**To test the else block, change the age to 12, and run the code again.**

**Python if elif else Statement**


**The if elif else statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to
TRUE.**

**Similar to the else block, the elif block is also optional. However, a program can contains only one else block whereas there can be an arbitrary number of
elif blocks following an if block.**

**Syntax of Python if elif else Statement**

**How if elif else Works?**


**The keyword elif is a short form of else if. It allows the logic to be arranged in a cascade of elif statements after the first if statement. If the first if statement
evaluates to false, subsequent elif statements are evaluated one by one and comes out of the cascade if any one is satisfied.**

**Last in the cascade is the else block which will come in picture when all preceding if/elif conditions fails.**

**Example**
**Suppose there are different slabs of discount on a purchase −**

**20% on amount exceeding 10000,**


**10% for amount between 5-10000,**
**5% if it is between 1 to 5000.**
**no discount if amount<1000**

**The following flowchart illustrates these conditions −**


**We can write a Python code for the above logic with if-else statements −**

**Open Compiler**

**Set amount to test all possible conditions: 800, 2500, 7500 and 15000. The outputs will vary accordingly −**

**While the code will work perfectly fine, if you look at the increasing level of indentation at each if and else statement, it will become difficult to manage if
there are still more conditions.**

**Python if elif else Statement Example**


**The elif statement makes the code easy to read and comprehend. Following is the Python code for the same logic with if elif else statements −**

**Open Compiler**

**The output of the above code is as follows −**

**Python supports nested if statements which means we can use a conditional if and if...else statement inside an existing if statement .**

**There may be a situation when you want to check for additional conditions after the initial one resolves to true. In such a situation, you can use the nested if
construct.**

**Additionally, within a nested if construct, you can include an if...elif...else construct inside another if...elif...else construct.**

**Syntax of Nested if Statement**


**The syntax of the nested if construct with else condition will be like this −**

**Flowchart of Nested if Statement**


**Following is the flowchart of Python nested if statement −**

**Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Example of Nested if Statement**

**The below example shows the working of nested if statements −**

**Open Compiler**

**When you run the above code, it will display the following result −**

**Nested if Statement with else Condition**


**As mentioned earlier, we can nest if-else statement within an if statement. If the if condition is true, the first if-else statement will be executed otherwise,
statements inside the else block will be executed.**

**Syntax**
**The syntax of the nested if construct with else condition will be like this −**

**Example**
**Now let's take a Python code to understand how it works −**

**Open Compiler**

**When the above code is executed, it produces the following output −**
Python match-case Statement
A Python match-case statement takes an expression and compares its value to successive patterns given as one or more case blocks. Only the first pattern that
matches gets executed. It is also possible to extract components (sequence elements or object attributes) from the value into variables.

With the release of Python 3.10, a pattern matching technique called match-case has been introduced, which is similar to the switch-case construct available
in C/C++/Java etc. Its basic use is to compare a variable against one or more values. It is more similar to pattern matching in languages like Rust or Haskell
than a switch statement in C or C++.

Syntax
The following is the syntax of match-case statement in Python -

match variable_name:
case 'pattern 1' : statement 1
case 'pattern 2' : statement 2
...
case 'pattern n' : statement n

Example
The following code has a function named weekday(). It receives an integer argument, matches it with all possible weekday number values, and returns the
corresponding name of day.

Open Compiler

def weekday(n):
match n:
case 0: return "Monday"
case 1: return "Tuesday"
case 2: return "Wednesday"
case 3: return "Thursday"
case 4: return "Friday"
case 5: return "Saturday"
case 6: return "Sunday"
case _: return "Invalid day number"
print (weekday(3))
print (weekday(6))
print (weekday(7))

On executing, this code will produce the following output −

1 Thursday
2 Sunday
3 Invalid day number

The last case statement in the function has "_" as the value to compare. It serves as the wildcard case, and will be executed if all other cases are not true.

Combined Cases in Match Statement


Sometimes, there may be a situation where for more than one cases, a similar action has to be taken. For this, you can combine cases with the OR operator
represented by "|" symbol.

Example
The code below shows how to combine cases in match statement. It defines a function named access() and has one string argument, representing the name of
the user. For admin or manager user, the system grants full access; for Guest, the access is limited; and for the rest, there's no access.

Open Compiler

def access(user):
match user:
case "admin" | "manager": return "Full access"
case "Guest": return "Limited access"
case _: return "No access"
print (access("manager"))
print (access("Guest"))
print (access("Ravi"))

On running the above code, it will show the following result −

1 Full access
2 Limited access
3 No access

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.## List
as the Argument in Match Case Statement

Since Python can match the expression against any literal, you can use a list as a case value. Moreover, for variable number of items in the list, they can be
parsed to a sequence with "*" operator.

Example
In this code, we use list as argument in match case statement.

Open Compiler

def greeting(details):
match details:
case [time, name]:
return f'Good {time}{name}!'
case [time, *names]:
msg=''
for name in names:
msg+=f'Good {time}{name}!\n'
return msg

print (greeting(["Morning", "Ravi"]))


print (greeting(["Afternoon","Guest"]))
print (greeting(["Evening", "Kajal", "Praveen", "Lata"]))

On executing, this code will produce the following output −

1 Good Morning Ravi!


2 Good Afternoon Guest!
3 Good Evening Kajal!
4 Good Evening Praveen!
5 Good Evening Lata!

Using "if" in "Case" Clause


Normally Python matches an expression against literal cases. However, it allows you to include if statement in the case clause for conditional computation of
match variable.

Example
In the following example, the function argument is a list of amount and duration, and the intereset is to be calculated for amount less than or more than 10000.
The condition is included in the case clause.

Open Compiler

def intr(details):
match details:
case [amt, duration] if amt<10000:
return amt*10*duration/100
case [amt, duration] if amt>=10000:
return amt*15*duration/100
print ("Interest = ", intr([5000,5]))
print ("Interest = ", intr([15000,3]))

On executing, this code will produce the following output −


1 Interest = 2500.0
2 Interest = 6750.0

Python Loops
Python loops allow us to execute a statement or group of statements multiple times.

In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a
situation when you need to execute a block of code several number of times.

Programming languages provide various control structures that allow for more complicated execution paths.

Flowchart of a Loop
The following diagram illustrates a loop statement −

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.## Types
of Loops in Python

Python programming language provides following types of loops to handle looping requirements −

[Link]. Loop Type & Description

1 while loopRepeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.

2 for loopExecutes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

3 nested loopsYou can use one or more loop inside any another while, for or do..while loop.

Python Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are
destroyed.

Python supports the following control statements. Click the following links to check their detail.

Let us go through the loop control statements briefly

[Link]. Control Statement & Description

1 break statementTerminates the loop statement and transfers execution to the statement immediately following the loop.

2 continue statementCauses the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
[Link]. Control Statement & Description

3 pass statementThe pass statement in Python is used when a statement is required syntactically but you do not want any command or code to
execute.

The for loop in Python provides the ability to loop over the items of any sequence, such as a list, tuple or a string. It performs the same action on each item of
the sequence. This loop starts with the for keyword, followed by a variable that represents the current item in the sequence. The in keyword links the variable
to the sequence you want to iterate over. A colon (:) is used at the end of the loop header, and the indented block of code beneath it is executed once for each
item in the sequence.

Syntax of Python for Loop


for iterating_var in sequence:
statement(s)

Here, the iterating_var is a variable to which the value of each sequence item will be assigned during each iteration. Statements represents the block of code
that you want to execute repeatedly.

Before the loop starts, the sequence is evaluated. If it's a list, the expression list (if any) is evaluated first. Then, the first item (at index 0) in the sequence is
assigned to iterating_var variable.

During each iteration, the block of statements is executed with the current value of iterating_var. After that, the next item in the sequence is assigned to
iterating_var, and the loop continues until the entire sequence is exhausted.

Flowchart of Python for Loop


The following flow diagram illustrates the working of for loop −

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python for Loop with Strings

A string is a sequence of Unicode letters, each having a positional index. Since, it is a sequence, you can iterate over its characters using the for loop.

Example
The following example compares each character and displays if it is not a vowel ('a', 'e', 'i', 'o', 'u').

Open Compiler

zen = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
'''
for char in zen:
if char not in 'aeiou':
print (char, end='')

On executing, this code will produce the following output −

1 Btfl s bttr thn gly.


2 Explct s bttr thn mplct.
3 Smpl s bttr thn cmplx.
4 Cmplx s bttr thn cmplctd.

Python for Loop with Tuples


Python's tuple object is also an indexed sequence, and hence you can traverse its items with a for loop.

Example
In the following example, the for loop traverses a tuple containing integers and returns the total of all numbers.

Open Compiler

numbers = (34,54,67,21,78,97,45,44,80,19)
total = 0
for num in numbers:
total += num
print ("Total =", total)

On running this code, it will produce the following output −

1 Total = 539

Python for Loop with Lists


Python's list object is also an indexed sequence, and hence you can iterate over its items using a for loop.

Example
In the following example, the for loop traverses a list containing integers and prints only those which are divisible by 2.

Open Compiler

numbers = [34,54,67,21,78,97,45,44,80,19]
total = 0
for num in numbers:
if num%2 == 0:
print (num)

When you execute this code, it will show the following result −

1 34
2 54
3 78
4 44
5 80

Python for Loop with Range Objects


Python's built-in range() function returns an iterator object that streams a sequence of numbers. This object contains integers from start to stop, separated by
step parameter. You can run a for loop with range as well.
Syntax
The range() function has the following syntax −

range(start, stop, step)

Where,

Start − Starting value of the range. Optional. Default is 0


Stop − The range goes upto stop-1
Step − Integers in the range increment by the step value. Option, default is 1.

Example
In this example, we will see the use of range with for loop.

Open Compiler

for num in range(5):


print (num, end=' ')
print()
for num in range(10, 20):
print (num, end=' ')
print()
for num in range(1, 10, 2):
print (num, end=' ')

When you run the above code, it will produce the following output −

1 0 1 2 3 4
2 10 11 12 13 14 15 16 17 18 19
3 1 3 5 7 9

Python for Loop with Dictionaries


Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is
still possible with the for loop.

Example
Running a simple for loop over the dictionary object traverses the keys used in it.

Open Compiler

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}


for x in numbers:
print (x)

On executing, this code will produce the following output −

1 10
2 20
3 30
4 40

Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with the get() method.
Example
The following example illustrates the above mentioned approach.

Open Compiler

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}


for x in numbers:
print (x,":",numbers[x])

It will produce the following output −

1 10 : Ten
2 20 : Twenty
3 30 : Thirty
4 40 : Forty

The items(), keys() and values() methods of dict class return the view objects dict_items, dict_keys and dict_values respectively. These objects are iterators,
and hence we can run a for loop over them.

Example
The dict_items object is a list of key-value tuples over which a for loop can be run as follows −

Open Compiler

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}


for x in [Link]():
print (x)

It will produce the following output −

1 (10, 'Ten')
2 (20, 'Twenty')
3 (30, 'Thirty')
4 (40, 'Forty')

Using else Statement with For Loop


Python supports to have an else statement associated with a loop statement. However, the else statement is executed when the loop has exhausted iterating the
list.

Example
The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 to 20.

Open Compiler

#For loop to iterate between 10 to 20


for num in range(10, 20):
#For loop to iterate on the factors
for i in range(2,num):
#If statement to determine the first factor
if num%i == 0:
#To calculate the second factor
j=num/i
print ("%d equals %d * %d" % (num,i,j))
#To move to the next number
break
else:
print (num, "is a prime number")
break

When the above code is executed, it produces the following result −


1 10 equals 2 * 5
2 11 is a prime number
3 12 equals 2 * 6
4 13 is a prime number
5 14 equals 2 * 7
6 15 equals 3 * 5
7 16 equals 2 * 8
8 17 is a prime number
9 18 equals 2 * 9
10 19 is a prime number

Python - For Else Loop


Python supports an optional else block to be associated with a for loop. If a else block is used with a for loop , it is executed only when the for loop
terminates normally.

The for loop terminates normally when it completes all its iterations without encountering a break statement, which allows us to exit the loop when a certain
condition is met.

Flowchart of For Else Loop


The following flowchart illustrates use of for-else loop −

Syntax of For Else Loop


Following is the syntax of for loop with optional else block −

for variable_name in iterable:


#stmts in the loop
.
.
.
else:
#stmts in else clause
.
.
Example of For Else Loop
The following example illustrates the combination of an else statement with a for statement in Python. Till the count is less than 5, the iteration count is
printed. As it becomes 5, the print statement in else block is executed, before the control is passed to the next statement in the main program.

Open Compiler

for count in range(6):


print ("Iteration no. {}".format(count))
else:
print ("for loop over. Now in else block")
print ("End of for loop")

On executing, this code will produce the following output −

1 Iteration no. 1
2 Iteration no. 2
3 Iteration no. 3
4 Iteration no. 4
5 Iteration no. 5
6 for loop over. Now in else block
7 End of for loop

For-Else Construct without break statement


As mentioned earlier in this tutorial, the else block executes only when the loop terminates normally i.e. without using break statement.

Example
In the following program, we use the for-else loop without break statement.

Open Compiler

for i in ['T','P']:
print(i)
else:
# Loop else statement
# there is no break statement in for loop, hence else part gets executed directly
print("ForLoop-else statement successfully executed")

On executing, the above program will generate the following output −

1 T
2 P
3 ForLoop-else statement successfully executed

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.## For-
Else Construct with break statementIn case of forceful termination (by using break statement) of the loop, else statement is overlooked by the interpreter and
hence its execution is skipped.

Example
The following program shows how else conditions work in case of a break statement.

Open Compiler

for i in ['T','P']:
print(i)
break
else:
# Loop else statement
# terminated after 1st iteration due to break statement in for loop
print("Loop-else statement successfully executed")

On executing, the above program will generate the following output −

1 T
For-Else with break statement and if conditions
If we use for-else construct with break statement and if condition, the for loop will iterate over the iterators and within this loop, you can use an if block to
check for a specific condition. If the loop completes without encountering a break statement, the code in the else block is executed.

Example
The following program shows how else conditions works in case of break statement and conditional statements.

Open Compiler

# creating a function to check whether the list item is a positive


# or a negative number
def positive_or_negative():
# traversing in a list
for i in [5,6,7]:
# checking whether the list element is greater than 0
if i>=0:
# printing positive number if it is greater than or equal to 0
print ("Positive number")
else:
# Else printing Negative number and breaking the loop
print ("Negative number")
break
# Else statement of the for loop
else:
# Statement inside the else block
print ("Loop-else Executed")
# Calling the above-created function
positive_or_negative()

On executing, the above program will generate the following output −

1 Positive number
2 Positive number
3 Positive number
4 Loop-else Executed

Python while Loop


A while loop in Python programming language repeatedly executes a target statement as long as the specified boolean expression is true. This loop starts with
while keyword followed by a boolean expression and colon symbol (:). Then, an indented block of statements starts.

Here, statement(s) may be a single statement or a block of statements with uniform indent. The condition may be any expression, and true is any non-zero
value. As soon as the expression becomes false, the program control passes to the line immediately following the loop.

If it fails to turn false, the loop continues to run, and doesn't stop unless forcefully stopped. Such a loop is called infinite loop, which is undesired in a
computer program.

Syntax of while Loop


The syntax of a while loop in Python programming language is −

while expression:
statement(s)

In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of
code. Python uses indentation as its method of grouping statements.
Flowchart of While loop
The following flow diagram illustrates the while loop −

Example 1
The following example illustrates the working of while loop. Here, the iteration run till value of count will become 5.

Open Compiler

count=0
while count<5:
count+=1
print ("Iteration no. {}".format(count))

print ("End of while loop")

On executing, this code will produce the following output −

1 Iteration no. 1
2 Iteration no. 2
3 Iteration no. 3
4 Iteration no. 4
5 Iteration no. 5
6 End of while loop

Example 2
Here is another example of using the while loop. For each iteration, the program asks for user input and keeps repeating till the user inputs a non-numeric
string. The isnumeric() function returns true if input is an integer, false otherwise.

var = '0'
while [Link]() == True:
var = "test"
if [Link]() == True:
print ("Your input", var)
print ("End of while loop")

On running the code, it will produce the following output −


1 enter a number..10
2 Your input 10
3 enter a number..100
4 Your input 100
5 enter a number..543
6 Your input 543
7 enter a number..qwer
8 End of while loop

Python Infinite while Loop


A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious when using while loops because of the possibility that this condition
never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as
and when required.

Example
Let's take an example to understand how the infinite loop works in Python −

var = 1
while var == 1 : # This constructs an infinite loop
num = int(input("Enter a number :"))
print ("You entered: ", num)
print ("Good bye!")

On executing, this code will produce the following output −

1 Enter a number :20


2 You entered: 20
3 Enter a number :29
4 You entered: 29
5 Enter a number :3
6 You entered: 3
7 Enter a number :11
8 You entered: 11
9 Enter a number :22
10 You entered: 22
11 Enter a number :Traceback (most recent call last):
12 File "examples\[Link]", line 5, in
13 num = int(input("Enter a number :"))
14 KeyboardInterrupt

The above example goes in an infinite loop and you need to use CTRL+C to exit the program.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python while-else Loop

Python supports having an else statement associated with a while loop. If the else statement is used with a while loop, the else statement is executed when
the condition becomes false before the control shifts to the main line of execution.

Flowchart of While loop with else Statement


The following flow diagram shows how to use else statement with while loop −
Example
The following example illustrates the combination of an else statement with a while statement. Till the count is less than 5, the iteration count is printed. As it
becomes 5, the print statement in else block is executed, before the control is passed to the next statement in the main program.

Open Compiler

count=0
while count<5:
count+=1
print ("Iteration no. {}".format(count))
else:
print ("While loop over. Now in else block")
print ("End of while loop")

On running the above code, it will print the following output −

1 Iteration no. 1
2 Iteration no. 2
3 Iteration no. 3
4 Iteration no. 4
5 Iteration no. 5
6 While loop over. Now in else block
7 End of while loop

Single Statement Suites


Similar to the if statement syntax, if your while clause consists only of a single statement, it may be placed on the same line as the while header.

Example
The following example shows how to use one-line while clause.

Open Compiler

flag = 0
while (flag): print ("Given flag is really true!")
print ("Good bye!")

When you run this code, it will display the following output −

1 Good bye!

Change the flag value to "1" and try the above program. If you do so, it goes into infinite loop and you need to press CTRL+C keys to exit.
Python break Statement
Python break statement is used to terminate the current loop and resumes execution at the next statement, just like the traditional break statement in C.

The most common use for Python break statement is when some external condition is triggered requiring a sudden exit from a loop. The break statement can
be used in both Python while and for loops.

If you are using nested loops in Python, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.

Syntax of break Statement


The syntax for a break statement in Python is as follows −

looping statement:
condition check:
break

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.## Flow
Diagram of break Statement

Following is the flowchart of the break statement −

break Statement with for loop


If we use break statement inside a for loop, it interrupts the normal flow of program and exit the loop before completing the iteration.

Example
In this example, we will see the working of break statement in for loop.

Open Compiler

for letter in 'Python':


if letter == 'h':
break
print ("Current Letter :", letter)
print ("Good bye!")

When the above code is executed, it produces the following result −

1 Current Letter : P
2 Current Letter : y
3 Current Letter : t
4 Good bye!
break Statement with while loop
Similar to the for loop, we can use the break statement to skip the code inside while loop after the specified condition becomes TRUE.

Example
The code below shows how to use break statement with while loop.

Open Compiler

var = 10
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break

print ("Good bye!")

On executing the above code, it produces the following result −

1 Current variable value : 10


2 Current variable value : 9
3 Current variable value : 8
4 Current variable value : 7
5 Current variable value : 6
6 Good bye!

break Statement with Nested Loops


In nested loops, one loop is defined inside another. The loop that enclose another loop (i.e. inner loop) is called as outer loop.

When we use a break statement with nested loops, it behaves as follows −

When break statement is used inside the inner loop, only the inner loop will be skipped and the program will continue executing statements after the inner
loop
And, when the break statement is used in the outer loop, both the outer and inner loops will be skipped and the program will continue executing statements
immediate to the outer loop.

Example
The following program demonstrates the use of break in a for loop iterating over a list. Here, the specified number will be searched in the list. If it is found,
then the loop terminates with the "found" message.

Open Compiler

no = 33
numbers = [11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num == no:
print ('number found in list')
break
else:
print ('number not found in list')

The above program will produce the following output −

1 number found in list

Python continue Statement


Python continue statement is used to skip the execution of the program block and returns the control to the beginning of the current loop to start the next
iteration. When encountered, the loop starts next iteration without executing the remaining statements in the current iteration.
The continue statement is just the opposite to that of break. It skips the remaining statements in the current loop and starts the next iteration.

Syntax of continue Statement


looping statement:
condition check:
continue

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.## Flow
Diagram of continue Statement

The flow diagram of the continue statement looks like this −

Python continue Statement with for Loop


In Python, the continue statement is allowed to be used with a for loop. Inside the for loop, you should include an if statement to check for a specific
condition. If the condition becomes TRUE, the continue statement will skip the current iteration and proceed with the next iteration of the loop.

Example
Let's see an example to understand how the continue statement works in for loop.

Open Compiler

for letter in 'Python':


if letter == 'h':
continue
print ('Current Letter :', letter)
print ("Good bye!")

When the above code is executed, it produces the following output −

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Good bye!
Python continue Statement with while Loop
Python continue statement is used with 'for' loops as well as 'while' loops to skip the execution of the current iteration and transfer the program's control to
the next iteration.

Example: Checking Prime Factors


Following code uses continue to find the prime factors of a given number. To find prime factors, we need to successively divide the given number starting
with 2, increment the divisor and continue the same process till the input reduces to 1.

Open Compiler

num = 60
print ("Prime factors for: ", num)
d=2
while num > 1:
ifnum%d==0:
print (d)
num=num/d
continue
d=d+1

On executing, this code will produce the following output −

1 Prime factors for: 60


2 2
3 2
4 3
5 5

Assign different value (say 75) to num in the above program and test the result for its prime factors.

1 Prime factors for: 75


2 3
3 5
4 5

Python pass Statement


Python pass statement is used when a statement is required syntactically but you do not want any command or code to execute. It is a null which means
nothing happens when it executes. This is also useful in places where piece of code will be added later, but a placeholder is required to ensure the program
runs without errors.

For instance, in a function or class definition where the implementation is yet to be written, pass statement can be used to avoid the SyntaxError.
Additionally, it can also serve as a placeholder in control flow statements like for and while loops.

Syntax of pass Statement


Following is the syntax of Python pass statement −

pass

Example of pass Statement


The following code shows how you can use the pass statement in Python −

Open Compiler

for letter in 'Python':


if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")

When the above code is executed, it produces the following output −

1 Current Letter : P
2 Current Letter : y
3 Current Letter : t
4 This is pass block
5 Current Letter : h
6 Current Letter : o
7 Current Letter : n
8 Good bye!

Dumpy Infinite Loop with pass Statement


This is simple enough to create an infinite loop using pass statement in Python.

Example
If you want to code an infinite loop that does nothing each time through, do it as shown below −

while True: pass


# Type Ctrl-C to stop

Because the body of the loop is just an empty statement, Python gets stuck in this loop.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Using Ellipses (...) as pass Statement Alternative

Python 3.X allows ellipses (coded as three consecutive dots ...) to be used in place of pass statement. Both serve as placeholders for code that are going to be
written later.

Example
For example if we create a function which does not do anything especially for code to be filled in later, then we can make use of ...

def func1():
# Alternative to pass
...

# Works on same line too


def func2(): ...
# Does nothing if called
func1()
func2()

In Python, when you write one or more loops within a loop statement that is known as a nested loop . The main loop is considered as outer loop and loop(s)
inside the outer loop are known as inner loops.

The Python programming language allows the use of one loop inside another loop. A loop is a code block that executes specific instructions repeatedly. There
are two types of loops, namely for and while, using which we can create nested loops.

You can put any type of loop inside of any other type of loop. For example, a for loop can be inside a while loop or vice versa.

Python Nested for Loop


The for loop with one or more inner for loops is called nested for loop. A for loop is used to loop over the items of any sequence, such as a list, tuple or a
string and performs the same action on each item of the sequence.
Python Nested for Loop Syntax
The syntax for a Python nested for loop statement in Python programming language is as follows −

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

Python Nested for Loop Example


The following program uses a nested for loop to iterate over months and days lists.

Open Compiler

months = ["jan", "feb", "mar"]


days = ["sun", "mon", "tue"]

for x in months:
for y in days:
print(x, y)

print("Good bye!")

When the above code is executed, it produces following result −

1 jan sun
2 jan mon
3 jan tue
4 feb sun
5 feb mon
6 feb tue
7 mar sun
8 mar mon
9 mar tue
10 Good bye!

Python Nested while Loop


The while loop having one or more inner while loops are nested while loop. A while loop is used to repeat a block of code for an unknown number of times
until the specified boolean expression becomes TRUE.

Python Nested while Loop Syntax


The syntax for a nested while loop statement in Python programming language is as follows −

while expression:
while expression:
statement(s)
statement(s)

Python Nested while Loop Example


The following program uses a nested while loop to find the prime numbers from 2 to 100 −

Open Compiler

i = 2
while(i < 25):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print (i, " is prime")
i = i + 1
print ("Good bye!")

On executing, the above code produces following result −

1 2 is prime
2 3 is prime
3 5 is prime
4 7 is prime
5 11 is prime
6 13 is prime
7 17 is prime
8 19 is prime
9 23 is prime
10 Good bye!

A Python function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your
application and a high degree of code reusing.

A top-to-down approach towards building the processing logic involves defining blocks of independent reusable functions. A Python function may be invoked
from any other function by passing required data (called parameters or arguments ). The called function returns its result back to the calling environment.

Types of Python Functions


Python provides the following types of functions −

[Link] Type & Description

1 Built-in functionsPython's standard library includes number of built-in functions. Some of Python's built-in functions are print(), int(), len(),
sum(), etc. These functions are always available, as they are loaded into computer's memory as soon as you start Python interpreter.

2 Functions defined in built-in modulesThe standard library also bundles a number of modules. Each module defines a group of functions. These
functions are not readily available. You need to import them into the memory from their respective modules.

3 User-defined functionsIn addition to the built-in functions and functions in the built-in modules, you can also create your own functions. These
functions are called user-defined functions.

Defining a Python Function


You can define custom functions to provide the required functionality. Here are simple rules to define a function in Python −

Function blocks begin with the keyword def followed by the function name and parentheses ().
Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement; the documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same
as return None.
Syntax to Define a Python Function
def function_name( parameters ):
"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.

Once the function is defined, you can execute it by calling it from another function or directly from the Python prompt.

Example to Define a Python Function


The following example shows how to define a function greetings(). The bracket is empty so there aren't any parameters. Here, the first line is a docstring and
the function block ends with return statement.

def greetings():
"This is docstring of greetings function"
print ("Hello World")
return

When this function is called, Hello world message will be printed.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Calling a Python Function

Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the basic
structure of a function is finalized, you can call it by using the function name itself. If the function requires any parameters, they should be passed within
parentheses. If the function doesn't require any parameters, the parentheses should be left empty.

Example to Call a Python Function


Following is the example to call printme() function −

Open Compiler

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print (str)
return;

# Now you can call the function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following output −

1 I'm first call to user defined function!


2 Again second call to the same function

Pass by Reference vs Value


In programming languages like C and C++, there are two main ways to pass variables to a function, which are Call by Value and Call by Reference (also
known as pass by reference and pass by value). However, the way we pass variables to functions in Python differs from others.

call by value − When a variable is passed to a function while calling, the value of actual arguments is copied to the variables representing the formal
arguments. Thus, any changes in formal arguments does not get reflected in the actual argument. This way of passing variable is known as call by value.
call by reference − In this way of passing variable, a reference to the object in memory is passed. Both the formal arguments and the actual arguments
(variables in the calling code) refer to the same object. Hence, any changes in formal arguments does get reflected in the actual argument.
Python uses pass by reference mechanism. As variable in Python is a label or reference to the object in the memory, both the variables used as actual
argument as well as formal arguments really refer to the same object in the memory. We can verify this fact by checking the id() of the passed variable before
and after passing.

Example
In the following example, we are checking the id() of a variable.

Open Compiler

def testfunction(arg):
print ("ID inside the function:", id(arg))

var = "Hello"
print ("ID before passing:", id(var))
testfunction(var)

If the above code is executed, the id() before passing and inside the function will be displayed.

1 ID before passing: 1996838294128


2 ID inside the function: 1996838294128

The behavior also depends on whether the passed object is mutable or immutable. Python numeric object is immutable. When a numeric object is passed, and
then the function changes the value of the formal argument, it actually creates a new object in the memory, leaving the original variable unchanged.

Example
The following example shows how an immutable object behaves when it is passed to a function.

Open Compiler

def testfunction(arg):
print ("ID inside the function:", id(arg))
arg = arg + 1
print ("new object after increment", arg, id(arg))

var=10
print ("ID before passing:", id(var))
testfunction(var)
print ("value after function call", var)

It will produce the following output −

1 ID before passing: 140719550297160


2 ID inside the function: 140719550297160
3 new object after increment 11 140719550297192
4 value after function call 10
Let us now pass a mutable object (such as a list or dictionary) to a function. It is also passed by reference, as the id() of list before and after passing is same.
However, if we modify the list inside the function, its global representation also reflects the change.

Example
Here we pass a list, append a new item, and see the contents of original list object, which we will find has changed.

Open Compiler

def testfunction(arg):
print ("Inside function:",arg)
print ("ID inside the function:", id(arg))
arg=[Link](100)

var=[10, 20, 30, 40]


print ("ID before passing:", id(var))
testfunction(var)
print ("list after function call", var)

It will produce the following output −

1 ID before passing: 2716006372544


2 Inside function: [10, 20, 30, 40]
3 ID inside the function: 2716006372544
4 list after function call [10, 20, 30, 40, 100]

Python Function Arguments


Function arguments are the values or variables passed into a function when it is called. The behavior of a function often depends on the arguments passed to
it.

While defining a function, you specify a list of variables (known as formal parameters) within the parentheses. These parameters act as placeholders for the
data that will be passed to the function when it is called. When the function is called, value to each of the formal arguments must be provided. Those are
called actual arguments.

Example
Let's modify greetings function and have name an argument. A string passed to the function as actual argument becomes name variable inside the function.

Open Compiler

def greetings(name):
"This is docstring of greetings function"
print ("Hello {}".format(name))
return

greetings("Samay")
greetings("Pratima")
greetings("Steven")

This code will produce the following output −


1 Hello Samay
2 Hello Pratima
3 Hello Steven

Types of Python Function Arguments


Based on how the arguments are declared while defining a Python function, they are classified into the following categories −

Positional or Required Arguments


Keyword Arguments
Default Arguments
Positional-only Arguments
Keyword-only arguments
Arbitrary or Variable-length Arguments

Positional or Required Arguments


Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match
exactly with the function definition, otherwise the code gives a syntax error.

Example
In the code below, we call the function printme() without any parameters which will give error.

Open Compiler

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print (str)
return;

# Now you can call printme function


printme()

When the above code is executed, it produces the following result −

1 Traceback (most recent call last):


2 File "[Link]", line 11, in <module>
3 printme();
4 TypeError: printme() takes exactly 1 argument (0 given)

Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the
parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match
the values with parameters.

Example 1
The following example shows how to use keyword arguments in Python.

Open Compiler

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print (str)
return;
# Now you can call printme function
printme( str = "My string")

When the above code is executed, it produces the following result −

1 My string

Example 2
The following example gives more clear picture. Note that the order of parameters does not matter.

Open Compiler

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −

1 Name: miki
2 Age 50

Default Arguments
A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument.

Example
The following example gives an idea on default arguments, it prints default age if it is not passed −

Open Compiler

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result −

1 Name: miki
2 Age 50
3 Name: miki
4 Age 35

Positional-only arguments
Those arguments that can only be specified by their position in the function call is called as Positional-only arguments. They are defined by placing a "/" in
the function's parameter list after all positional-only parameters. This feature was introduced with the release of Python 3.8.

The benefit of using this type of argument is that it ensures the functions are called with the correct arguments in the correct order. The positional-only
arguments should be passed to a function as positional arguments, not keyword arguments.
Example
In the following example, we have defined two positional-only arguments namely "x" and "y". This method should be called with positional arguments in the
order in which the arguments are declared, otherwise, we will get an error.

Open Compiler

def posFun(x, y, /, z):


print(x + y + z)

print("Evaluating positional-only arguments: ")


posFun(33, 22, z=11)

It will produce the following output −

1 Evaluating positional-only arguments:


2 66

Keyword-only arguments
Those arguments that must be specified by their name while calling the function is known as Keyword-only arguments. They are defined by placing an
asterisk ("*") in the function's parameter list before any keyword-only parameters. This type of argument can only be passed to a function as a keyword
argument, not a positional argument.

Example
In the code below, we have defined a function with three keyword-only arguments. To call this method, we need to pass keyword arguments, otherwise, we
will encounter an error.

Open Compiler

def posFun(*, num1, num2, num3):


print(num1 * num2 * num3)

print("Evaluating keyword-only arguments: ")


posFun(num1=6, num2=8, num3=5)

It will produce the following output −

1 Evaluating keyword-only arguments:


2 240

Arbitrary or Variable-length Arguments


You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length
arguments and are not named in the function definition, unlike required and default arguments.

Syntax for a function with non-keyword variable arguments is this −

def functionname([formal_args,] *var_args_tuple ):


"function_docstring"
function_suite
return [expression]

An asterisk (*) is placed before the variable name that holds the values of all non-keyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call.

Example
Following is a simple example of Python variable-length arguments.

Open Compiler

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result −

1 Output is:
2 10
3 Output is:
4 70
5 60
6 50

In the next few chapters, we will discuss these function arguments at length.

Order of Python Function Arguments


A function can have arguments of any of the types defined above. However, the arguments must be declared in the following order −

The argument list begins with the positional-only args, followed by the slash (/) symbol.
It is followed by regular positional args that may or may not be called as keyword arguments.
Then there may be one or more args with default values.
Next, arbitrary positional arguments represented by a variable prefixed with single asterisk, that is treated as tuple. It is the next.
If the function has any keyword-only arguments, put an asterisk before their names start. Some of the keyword-only arguments may have a default value.
Last in the bracket is argument with two asterisks ** to accept arbitrary number of keyword arguments.

The following diagram shows the order of formal arguments −

Python Function with Return Value


The return keyword as the last statement in function definition indicates end of function block, and the program flow goes back to the calling function.
Although reduced indent after the last statement in the block also implies return but using explicit return is a good practice.

Along with the flow control, the function can also return value of an expression to the calling function. The value of returned expression can be stored in a
variable for further processing.

Example
Let us define the add() function. It adds the two values passed to it and returns the addition. The returned value is stored in a variable called result.

Open Compiler

def add(x,y):
z=x+y
return z
a=10
b=20
result = add(a,b)
print ("a = {} b = {} a+b = {}".format(a, b, result))

It will produce the following output −

1 a = 10 b = 20 a+b = 30

The Anonymous Functions


The functions are called anonymous when they are not declared in the standard manner by using the def keyword. Instead, they are defined using the lambda
keyword.

Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple
expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression
Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by
passing function stack allocation during invocation for performance reasons.

Syntax
The syntax of lambda functions contains only a single statement, which is as follows −

lambda [arg1 [,arg2,.....argn]]:expression

Example
Following is the example to show how lambda form of function works −

Open Compiler

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))

When the above code is executed, it produces the following result −

1 Value of total : 30
2 Value of total : 40

Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python

Global variables
Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.

This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared inside it are brought into scope.
Example
Following is a simple example of local and global scope −

Open Compiler

total = 0; # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total;

# Now you can call sum function


sum( 10, 20 );
print ("Outside the function global total : ", total)

When the above code is executed, it produces the following result −

1 Inside the function local total : 30


2 Outside the function global total : 0

Python Default Arguments


Python allows to define a function with default value assigned to one or more formal arguments. Python uses the default value for such an argument if no
value is passed to it. If any value is passed, the default value is overridden with the actual value passed.

Default arguments in Python are the function arguments that will be used if no arguments are passed to the function call.

Example of Default Arguments


The following example shows use of Python default arguments. Here, the second call to the function will not pass value to "city" argument, hence its default
value "Hyderabad" will be used.

Open Compiler

# Function definition
def showinfo( name, city = "Hyderabad" ):
"This prints a passed info into this function"
print ("Name:", name)
print ("City:", city)
return

# Now call showinfo function


showinfo(name = "Ansh", city = "Delhi")
showinfo(name = "Shrey")

It will produce the following output −

1 Name: Ansh
2 City: Delhi
3 Name: Shrey
4 City: Hyderabad

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Example: Calling Function Without Keyword Arguments

Let us look at another example that assigns default value to a function argument. The function percent() has a default argument named "maxmarks" which
is set to 200. Hence, we can omit the value of third argument while calling the function.

Open Compiler

# function definition
def percent(phy, maths, maxmarks=200):
val = (phy + maths) * 100/maxmarks
return val
phy = 60
maths = 70
# function calling with default argument
result = percent(phy, maths)
print ("percentage:", result)

phy = 40
maths = 46
result = percent(phy, maths, 100)
print ("percentage:", result)

On executing, this code will produce the following output −

1 percentage: 65.0
2 percentage: 86.0

Mutable Objects as Default Argument


Python evaluates default arguments once when the function is defined, not each time the function is called. Therefore, If you use a mutable default argument
and modify it within the given function, the same values are referenced in the subsequent function calls.

Those Python objects that can be changed after creation are called as mutable objects.

Example
The code below explains how to use mutable objects as default argument in Python.

Open Compiler

def fcn(nums, numericlist = []):


[Link](nums + 1)
print(numericlist)

# function calls
fcn(66)
fcn(68)
fcn(70)

On executing the above code, it will produce the following output −

1 [67]
2 [67, 69]
3 [67, 69, 71]

Keyword Arguments
Python allows to pass function arguments in the form of keywords which are also called named arguments. Variables in the function definition are used as
keywords. When the function is called, you can explicitly mention the name and its value.

Calling Function With Keyword Arguments


The following example demonstrates keyword arguments in Python. In the second function call, we have used keyword arguments.

Open Compiler

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return

# Now you can call printinfo function


# by positional arguments
printinfo ("Naveen", 29)
# by keyword arguments
printinfo(name="miki", age = 30)

It will produce the following output −

1 Name: Naveen
2 Age 29
3 Name: miki
4 Age 30

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.## Order
of Keyword Arguments

By default, the function assigns the values to arguments in the order of appearance. However, while using keyword arguments, it is not necessary to follow
the order of formal arguments in function definition. Use of keyword arguments is optional. You can use mixed calling. You can pass values to some
arguments without keywords, and for others with keyword.

Example
Let us try to understand with the help of following function definition −

Open Compiler

def division(num, den):


quotient = num/den
print ("num:{} den:{} quotient:{}".format(num, den, quotient))

division(10,5)
division(5,10)

Since the values are assigned as per the position, the output is as follows −

1 num:10 den:5 quotient:2.0


2 num:5 den:10 quotient:0.5

Example
Instead of passing the values with positional arguments, let us call the function with keyword arguments −

Open Compiler

def division(num, den):


quotient = num/den
print ("num:{} den:{} quotient:{}".format(num, den, quotient))

division(num=10, den=5)
division(den=5, num=10)

Unlike positional arguments, the order of keyword arguments does not matter. Hence, it will produce the following output −

1 num:10 den:5 quotient:2.0


2 num:10 den:5 quotient:2.0

However, the positional arguments must be before the keyword arguments while using mixed calling.

Example
Try to call the division() function with the keyword arguments as well as positional arguments.

Open Compiler

def division(num, den):


quotient = num/den
print ("num:{} den:{} quotient:{}".format(num, den, quotient))

division(num = 5, 10)
As the Positional argument cannot appear after keyword arguments, Python raises the following error message −

1 division(num=5, 10)
2 ^
3 SyntaxError: non-keyword arg after keyword arg

Keyword-Only Arguments
You can use the variables in formal argument list as keywords to pass value. Use of keyword arguments is optional. But, you can force the function to accept
arguments by keyword only. You should put an astreisk (*) before the keyword-only arguments list.

Let us say we have a function with three arguments, out of which we want second and third arguments to be keyword-only. For that, put * after the first
argument.

Example of Keyword-Only Arguments


The built-in print() function is an example of keyword-only arguments. You can give list of expressions to be printed in the parentheses. The printed values
are separated by a white space by default. You can specify any other separation character instead using "sep" argument.

Open Compiler

print ("Hello", "World", sep="-")

It will print −

1 Hello-World

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Example: Using "sep" as non-keyword Argument

The sep argument of the print() function is keyword-only. Try using it as non-keyword argument.

Open Compiler

print ("Hello", "World", "-")

You'll get different output, not as desired −

1 Hello World -

Using Keyword-Only argument in User-Defined Method


To make an argument keyword-only, put the astreisk (*) before it while creating the user-defined function.

Those Python functions that are defined by us within a given class to perform certain actions are called as user-defined function. They are not predefined by
Python.

Example
In the following user defined function "intr()" the "rate" argument is keyword-only. To call this function, the value for rate must be passed by keyword.

Open Compiler

def intr(amt,*, rate):


val = amt*rate/100
return val

interest = intr(1000, rate=10)


print(interest)

1 100.0

However, if you try to use the default positional way of calling the above function, you will encounter an error.
Example
The code below shows it is not possible to use positional arguments when keyword-only arguments are required.

Open Compiler

def intr(amt, *, rate):


val = amt * rate / 100
return val

interest = intr(1000, 10)


print(interest)

On executing, this code will show the following result −

1 interest = intr(1000, 10)


2 ^^^^^^^^^^^^^^
3 TypeError: intr() takes 1 positional argument but 2 were given

Positional Arguments
The list of variables declared in the parentheses at the time of defining a function are the formal arguments. And, these arguments are also known as
positional arguments. A function may be defined with any number of formal arguments.

While calling a function −

All the arguments are required.


The number of actual arguments must be equal to the number of formal arguments.
They Pick up values in the order of definition.
The type of arguments must match.
Names of formal and actual arguments need not be same.

Positional Arguments Examples


Let's discuss some examples of Positional arguments −

Example 1
The following example shows the use of positional argument.

Open Compiler

def add(x,y):
z = x+y
print ("x={} y={} x+y={}".format(x,y,z))
a = 10
b = 20
add(a, b)

It will produce the following output −

1 x=10 y=20 x+y=30

Here, the add() function has two formal arguments, both are numeric. When integers 10 and 20 passed to it. The variable "a" takes 10 and "b" takes 20, in
the order of declaration. The add() function displays the addition.
Example 2
Python also raises error when the number of arguments don't match. If you give only one argument and check the result you can see an error.

Open Compiler

def add(x,y):
z=x+y
print (z)
a=10;
add(a)

The error generated will be as shown below −

1 TypeError: add() missing 1 required positional argument: 'y'

Example 3
Similarly, if you pass more than the number of formal arguments an error will be generated stating the same −

Open Compiler

def add(x,y):
z=x+y
print ("x={} y={} x+y={}".format(x,y,z))
add(10, 20, 30)

Following is the output −

1 TypeError: add() takes 2 positional arguments but 3 were given

Example 4
Data type of corresponding actual and formal arguments must match. Change a to a string value and see the result.

Open Compiler

def add(x,y):
z=x+y
print (z)
a="Hello"
b=20
add(a,b)

It will produce the following error −

1 z=x+y
2 ~^~
3 TypeError: can only concatenate str (not "int") to str

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Difference between Positional and Keyword argument

The below table explains the difference between positional and keyword argument −

Positional Argument Keyword Argument

Only the names of arguments are used to pass data to the given function. Keyword arguments are passed to a function in name=value form.

Arguments are passed in the order defined in function declaration. While passing arguments, their order can be changed.

Syntax: function(param1, param2,...) Syntax: function(param1 = value1,...)


Positional Only Arguments
It is possible in Python to define a function in which one or more arguments can not accept their value with keywords. Such arguments are called positional-
only arguments.

To make an argument positional-only, use the forward slash (/) symbol. All the arguments before this symbol will be treated as positional-only.

Python's built-in input() function is an example of positional-only arguments. The syntax of input function is −

input(prompt = "")

Prompt is an explanatory string for the benefit of the user. However, you cannot use the prompt keyword inside the parentheses.

Example
In this example, we are using prompt keyword, which will lead to error.

Open Compiler

name = input(prompt="Enter your name ")

On executing, this code will show the following error message −<>

1 name = input (prompt="Enter your name ")


2 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3 TypeError: input() takes no keyword arguments

Positional-Only Arguments Examples


Let's understand positional-only arguments with the help of some examples −

Example 1
In this example, we make both the arguments of intr() function as positional-only by putting "/" at the end.

Open Compiler

def intr(amt, rate, /):


val = amt * rate / 100
return val

print(intr(316200, 4))

When you run the code, it will show the following result −

1 12648.0

Example 2
If we try to use the arguments as keywords, Python raises errors as shown in the below example.

Open Compiler

def intr(amt, rate, /):


val = amt * rate / 100
return val

print(intr(amt=1000, rate=10))

On running this code, it will show following error message −

1 interest = intr(amt=1000, rate=10)


2 ^^^^^^^^^^^^^^^^^^^^^^^
3 TypeError: intr() got some positional-only arguments passed as keyword arguments: 'amt, rate'
Example 3
A function may be defined in such a way that it has some keyword-only and some positional-only arguments. Here, x is a required positional-only argument,
y is a regular positional argument, and z is a keyword-only argument.

Open Compiler

def myfunction(x, /, y, *, z):


print (x, y, z)

myfunction(10, y=20, z=30)


myfunction(10, 20, z=30)

The above code will show the following output −

1 10 20 30
2 10 20 30

Arbitrary Arguments (*args)


You may want to define a function that is able to accept arbitrary or variable number of arguments . Moreover, the arbitrary number of arguments might
be positional or keyword arguments.

An argument prefixed with a single asterisk * for arbitrary positional arguments.


An argument prefixed with two asterisks ** for arbitrary keyword arguments.

Arbitrary Arguments Example


Given below is an example of arbitrary or variable length positional arguments −

Open Compiler

# sum of numbers
def add(*args):
s=0
for x in args:
s=s+x
return s
result = add(10,20,30,40)
print (result)

result = add(1,2,3)
print (result)

The args variable prefixed with "*" stores all the values passed to it. Here, args becomes a tuple. We can run a loop over its items to add the numbers.

It will produce the following output −

1 100
2 6

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Required Arguments With Arbitrary Arguments

It is also possible to have a function with some required arguments before the sequence of variable number of values.

Example
The following example has avg() function. Assume that a student can take any number of tests. First test is mandatory. He can take as many tests as he likes
to better his score. The function calculates the average of marks in first test and his maximum score in the rest of tests.

The function has two arguments, first is the required argument and second to hold any number of values.

Open Compiler

#avg of first test and best of following tests


def avg(first, *rest):
second=max(rest)
return (first+second)/2

result=avg(40,30,50,25)
print (result)

Following call to avg() function passes first value to the required argument first, and the remaining values to a tuple named rest. We then find the maximum
and use it to calculate the average.

It will produce the following output −

1 45.0

Arbitrary Keyword Arguments (**kwargs)


If a variable in the argument list has two asterisks prefixed to it, the function can accept arbitrary number of keyword arguments. The variable becomes a
dictionary of keyword:value pairs.

Example
The following code is an example of a function with arbitrary keyword arguments. The addr() function has an argument **kwargs which is able to accept any
number of address elements like name, city, phno, pin, etc. Inside the function kwargs dictionary of kw:value pairs is traversed using items() method.

Open Compiler

def addr(**kwargs):
for k,v in [Link]():
print ("{}:{}".format(k,v))

print ("pass two keyword args")


addr(Name="John", City="Mumbai")
print ("pass four keyword args")

# pass four keyword args


addr(Name="Raam", City="Mumbai", ph_no="9123134567", PIN="400001")

It will produce the following output −

1 pass two keyword args


2 Name:John
3 City:Mumbai
4 pass four keyword args
5 Name:Raam
6 City:Mumbai
7 ph_no:9123134567
8 PIN:400001

Multiple Arguments With Arbitrary Keyword Arguments


If the function uses mixed types of arguments, the arbitrary keyword arguments should be after positional, keyword and arbitrary positional arguments in the
argument list.

Example
Imagine a case where science and maths are mandatory subjects, in addition to which student may choose any number of elective subjects.

The following code defines a percent() function where marks in science and marks are stored in required arguments, and the marks in variable number of
elective subjects in **optional argument.

Open Compiler

def percent(math, sci, **optional):


print ("maths:", math)
print ("sci:", sci)
s=math+sci
for k,v in [Link]():
print ("{}:{}".format(k,v))
s=s+v
return s/(len(optional)+2)

result=percent(math=80, sci=75, Eng=70, Hist=65, Geo=72)


print ("percentage:", result)

It will produce the following output −

1 maths: 80
2 sci: 75
3 Eng:70
4 Hist:65
5 Geo:72
6 percentage: 72.4

The scope of a variable in Python is defined as the specific area or region where the variable is accessible to the user. The scope of a variable depends on
where and how it is defined. In Python, a variable can have either a global or a local scope.

Types of Scope for Variables in Python


On the basis of scope, the Python variables are classified in three categories −

Local Variables
Global Variables
Nonlocal Variables

Local Variables
A local variable is defined within a specific function or block of code. It can only be accessed by the function or block where it was defined, and it has a
limited scope. In other words, the scope of local variables is limited to the function they are defined in and attempting to access them outside of this function
will result in an error. Always remember, multiple local variables can exist with the same name.

Example
The following example shows the scope of local variables.

Open Compiler

def myfunction():
a = 10
b = 20
print("variable a:", a)
print("variable b:", b)
return a+b

print (myfunction())

In the above code, we have accessed the local variables through its function. Hence, the code will produce the following output −

1 variable a: 10
2 variable b: 20
3 30

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Global Variables

A global variable can be accessed from any part of the program, and it is defined outside any function or block of code. It is not specific to any block or
function.
Example
The following example shows the scope of global variable. We can access them inside as well as outside of the function scope.

Open Compiler

#global variables
name = 'TutorialsPoint'
marks = 50
def myfunction():
# accessing inside the function
print("name:", name)
print("marks:", marks)
# function call
myfunction()

The above code will produce the following output −

1 name: TutorialsPoint
2 marks: 50

Nonlocal Variables
The Python variables that are not defined in either local or global scope are called nonlocal variables. They are used in nested functions.

Example
The following example demonstrates the how nonlocal variables works.

Open Compiler

def yourfunction():
a = 5
b = 6
# nested function
def myfunction():
# nonlocal function
nonlocal a
nonlocal b
a = 10
b = 20
print("variable a:", a)
print("variable b:", b)
return a+b
print (myfunction())
yourfunction()

The above code will produce the below output −

1 variable a: 10
2 variable b: 20
3 30

Namespace and Scope of Python Variables


A namespace is a collection of identifiers, such as variable names, function names, class names, etc. In Python, namespace is used to manage the scope of
variables and to prevent naming conflicts.

Python provides the following types of namespaces −

Built-in namespace contains built-in functions and built-in exceptions. They are loaded in the memory as soon as Python interpreter is loaded and remain
till the interpreter is running.
Global namespace contains any names defined in the main program. These names remain in memory till the program is running.
Local namespace contains names defined inside a function. They are available till the function is running.

These namespaces are nested one inside the other. Following diagram shows relationship between namespaces.
The life of a certain variable is restricted to the namespace in which it is defined. As a result, it is not possible to access a variable present in the inner
namespace from any outer namespace.

Python globals() Function


Python's standard library includes a built-in function globals(). It returns a dictionary of symbols currently available in global namespace.

Run the globals() function directly from the Python prompt.

1 >>> globals()
2 {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class
'_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins'
(built-in)>}

It can be seen that the built-in module which contains definitions of all built-in functions and built-in exceptions is loaded.

Example
Save the following code that contains few variables and a function with few more variables inside it.

Open Compiler

name = 'TutorialsPoint'
marks = 50
result = True
def myfunction():
a = 10
b = 20
return a+b

print (globals())

Calling globals() from inside this script returns following dictionary object −

1 {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':


<_frozen_importlib_external.SourceFileLoader object at 0x00000263E7255250>, '__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\user\\examples\\[Link]', '__cached__': None,
'name': 'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction': <function myfunction at 0x00000263E72004A0>}

The global namespace now contains variables in the program and their values and the function object in it (and not the variables in the function).

Python locals() Function


Python's standard library includes a built-in function locals(). It returns a dictionary of symbols currently available in the local namespace of the function.
Example
Modify the above script to print dictionary of global and local namespaces from within the function.

Open Compiler

name = 'TutorialsPoint'
marks = 50
result = True
def myfunction():
a = 10
b = 20
c = a+b
print ("globals():", globals())
print ("locals():", locals())
return c
myfunction()

The output shows that locals() returns a dictionary of variables and their values currently available in the function.

1 globals(): {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':


<_frozen_importlib_external.SourceFileLoader object at 0x00000169AE265250>, '__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\mlath\\examples\\[Link]', '__cached__': None,
'name': 'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction': <function myfunction at 0x00000169AE2104A0>}
2 locals(): {'a': 10, 'b': 20, 'c': 30}

Since both globals() and locals functions return dictionary, you can access value of a variable from respective namespace with dictionary get() method or
index operator.

print (globals()['name']) # displays TutorialsPoint


print (locals().get('a')) # displays 10

Namespace Conflict in Python


If a variable of same name is present in global as well as local scope, Python interpreter gives priority to the one in local namespace.

Example
In the following example, we define a local and a global variable.

Open Compiler

marks = 50 # this is a global variable


def myfunction():
marks = 70 # this is a local variable
print (marks)

myfunction()
print (marks) # prints global value

It will produce the following output −

1 70
2 50

Example
If you try to manipulate value of a global variable from inside a function, Python raises UnboundLocalError as shown in example below −

Open Compiler

# this is a global variable


marks = 50
def myfunction():
marks = marks + 20
print (marks)
myfunction()
# prints global value
print (marks)

It will produce the following error message −

1 marks = marks + 20
2 ^^^^^
3 UnboundLocalError: cannot access local variable 'marks' where it is not associated with a value

Example
To modify a global variable, you can either update it with a dictionary syntax, or use the global keyword to refer it before modifying.

Open Compiler

var1 = 50 # this is a global variable


var2 = 60 # this is a global variable
def myfunction():
"Change values of global variables"
globals()['var1'] = globals()['var1']+10
global var2
var2 = var2 + 20

myfunction()
print ("var1:",var1, "var2:",var2) #shows global variables with changed values

On executing the code, it will produce the following output −

1 var1: 60 var2: 80

Example
Lastly, if you try to access a local variable in global scope, Python raises NameError as the variable in local scope can't be accessed outside it.

Open Compiler

var1 = 50 # this is a global variable


var2 = 60 # this is a global variable
def myfunction(x, y):
total = x+y
print ("Total is a local variable: ", total)

myfunction(var1, var2)
print (total) # This gives NameError

It will produce the following error message −

1 Total is a local variable: 110


2 Traceback (most recent call last):
3 File "C:\Users\user\examples\[Link]", line 9, in <module>
4 print (total) # This gives NameError
5 ^^^^^
6 NameError: name 'total' is not defined

Function Annotations
The function annotation feature of Python enables you to add additional explanatory metadata about the arguments declared in a function definition, and
also the return data type. They are not considered by Python interpreter while executing the function. They are mainly for the Python IDEs for providing a
detailed documentation to the programmer.

Although you can use the docstring feature of Python for documentation of a function, it may be obsolete if certain changes in the function's prototype are
made. Hence, the annotation feature was introduced in Python as a result of PEP 3107.

Annotations are any valid Python expressions added to the arguments or return data type. Simplest example of annotation is to prescribe the data type of the
arguments. Annotation is mentioned as an expression after putting a colon in front of the argument.
Example
Remember that Python is a dynamically typed language, and doesn't enforce any type checking at runtime. Hence annotating the arguments with data types
doesn't have any effect while calling the function. Even if non-integer arguments are given, Python doesn't detect any error.

Open Compiler

def myfunction(a: int, b: int):


c = a+b
return c

print (myfunction(10,20))
print (myfunction("Hello ", "Python"))

It will produce the following output −

1 30
2 Hello Python

Function Annotations With Return Type


Annotations are ignored at runtime, but are helpful for the IDEs and static type checker libraries such as mypy.

You can give annotation for the return data type as well. After the parentheses and before the colon symbol, put an arrow (->) followed by the annotation.

Example
In this example, we are providing annotation for return type.

Open Compiler

def myfunction(a: int, b: int) -> int:


c = a+b
return c
print(myfunction(56,88))
print(myfunction.__annotations__)

This will generate the following output −

1 144
2 {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Function Annotations With Expression

As using the data type as annotation is ignored at runtime, you can put any expression which acts as the metadata for the arguments. Hence, function may
have any arbitrary expression as annotation.

Example
In the below example, we are using expression as a function annotation.

Open Compiler

def total(x : 'marks in Physics', y: 'marks in chemistry'):


return x+y
print(total(86, 88))
print(total.__annotations__)

Following is the output −

1 174
2 {'x': 'marks in Physics', 'y': 'marks in chemistry'}
Function Annotations With Default Arguments
If you want to specify a default argument along with the annotation, you need to put it after the annotation expression. Default arguments must come after the
required arguments in the argument list.

Example 1
The following example demonstrates how to provide annotation for default arguments of a function.

def myfunction(a: "physics", b:"Maths" = 20) -> int:


c = a+b
return c
print (myfunction(10))

The function in Python is also an object, and one of its attributes is annotations. You can check with dir() function.

print (dir(myfunction))

This will print the list of myfunction object containing annotations as one of the attributes.

1 ['__annotations__', '__builtins__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__',


'__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__getstate__',
'__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__',
'__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__']

Example 2
The annotations attribute itself is a dictionary in which arguments are keys and anotations their values.

Open Compiler

def myfunction(a: "physics", b:"Maths" = 20) -> int:


c = a+b
return c
print (myfunction.__annotations__)

It will produce the following output −

1 {'a': 'physics', 'b': 'Maths', 'return': <class 'int'>}

Example 3
You may have arbitrary positional and/or arbitrary keyword arguments for a function. Annotations can be given for them also.

Open Compiler

def myfunction(*args: "arbitrary args", **kwargs: "arbitrary keyword args") -> int:
pass
print (myfunction.__annotations__)

It will produce the following output −

1 {'args': 'arbitrary args', 'kwargs': 'arbitrary keyword args', 'return': <class 'int'>}

Example 4
In case you need to provide more than one annotation expressions to a function argument, give it in the form of a dictionary object in front of the argument
itself.

Open Compiler
def division(num: dict(type=float, msg='numerator'), den: dict(type=float, msg='denominator')) -> float:
return num/den
print (division.__annotations__)

It will produce the following output −

1 {'num': {'type': <class 'float'>, 'msg': 'numerator'}, 'den': {'type': <class 'float'>, 'msg': 'denominator'}, 'return':
<class 'float'>}

Python Modules
The concept of module in Python further enhances the modularity. You can define more than one related functions together and load required functions. A
module is a file containing definition of functions, classes, variables, constants or any other Python object. Contents of this file can be made available to any
other program. Python has the import keyword for this purpose.

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application
and a high degree of code reusing.

Example of Python Module


Open Compiler

import math
print ("Square root of 100:", [Link](100))

It will produce the following output −

1 Square root of 100: 10.0

Python Built-in Modules


Python's standard library comes bundled with a large number of modules. They are called built-in modules. Most of these built-in modules are written in C (as
the reference implementation of Python is in C), and pre-compiled into the library. These modules pack useful functionality like system-specific OS
management, disk IO, networking, etc.

Here is a select list of built-in modules −

[Link]. Name & Brief Description

1 osThis module provides a unified interface to a number of operating system functions.

2 stringThis module contains a number of functions for string processing

3 reThis module provides a set of powerful regular expression facilities. Regular expression (RegEx), allows powerful string search and matching
for a pattern in a string

4 mathThis module implements a number of mathematical operations for floating point numbers. These functions are generally thin wrappers
around the platform C library functions.

5 cmathThis module contains a number of mathematical operations for complex numbers.

6 datetimeThis module provides functions to deal with dates and the time within a day. It wraps the C runtime library.

7 gcThis module provides an interface to the built-in garbage collector.

8 asyncioThis module defines functionality required for asynchronous processing

9 CollectionsThis module provides advanced Container datatypes.

10 FunctoolsThis module has Higher-order functions and operations on callable objects. Useful in functional programming

11 operatorFunctions corresponding to the standard operators.

12 pickleConvert Python objects to streams of bytes and back.

13 socketLow-level networking interface.


[Link]. Name & Brief Description

14 sqlite3A DB-API 2.0 implementation using SQLite 3.x.

15 statisticsMathematical statistics functions

16 typingSupport for type hints

17 venvCreation of virtual environments.

18 jsonEncode and decode the JSON format.

19 wsgirefWSGI Utilities and Reference Implementation.

20 unittestUnit testing framework for Python.

21 randomGenerate pseudo-random numbers

22 sysProvides functions that acts strongly with the interpreter.

23 requestsIt simplifies HTTP requests by offering a user-friendly interface for sending and handling responses.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python User-defined Modules

Any text file with .py extension and containing Python code is basically a module. It can contain definitions of one or more functions, variables, constants as
well as classes. Any Python object from a module can be made available to interpreter session or another Python script by import statement. A module can
also include runnable code.

Creating a Python Module


Creating a module is nothing but saving a Python code with the help of any editor. Let us save the following code as [Link]

def SayHello(name):
print ("Hi {}! How are you?".format(name))
return

You can now import mymodule in the current Python terminal.

>>> import mymodule


>>> [Link]("Harish")
Hi Harish! How are you?

You can also import one module in another Python script. Save the following code as [Link]

import mymodule
[Link]("Harish")

Run this script from command terminal

Hi Harish! How are you?

The import Statement


In Python, the import keyword has been provided to load a Python object from one module. The object may be a function, class, a variable etc. If a module
contains multiple definitions, all of them will be loaded in the namespace.

Let us save the following code having three functions as [Link].

def sum(x,y):
return x+y

def average(x,y):
return (x+y)/2

def power(x,y):
return x**y

The import mymodule statement loads all the functions in this module in the current namespace. Each function in the imported module is an attribute of this
module object.
>>> dir(mymodule)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'average', 'power', 'sum']

To call any function, use the module object's reference. For example, [Link]().

import mymodule
print ("sum:",[Link](10,20))
print ("average:",[Link](10,20))
print ("power:",[Link](10, 2))

It will produce the following output −

1 sum:30
2 average:15.0
3 power:100

The from ... import Statement


The import statement will load all the resources of the module in the current namespace. It is possible to import specific objects from a module by using this
syntax. For example −

Out of three functions in mymodule , only two are imported in following executable script [Link]

from mymodule import sum, average


print ("sum:",sum(10,20))
print ("average:",average(10,20))

It will produce the following output −

1 sum: 30
2 average: 15.0

Note that function need not be called by prefixing name of its module to it.

The from...import * Statement


It is also possible to import all the names from a module into the current namespace by using the following import statement −

from modname import *

This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.

The import ... as Statement


You can assign an alias name to the imported module.

from modulename as alias

The alias should be prefixed to the function while calling.

Take a look at the following example −

import mymodule as x
print ("sum:",[Link](10,20))
print ("average:", [Link](10,20))
print ("power:", [Link](10, 2))

Locating Modules
When you import a module, the Python interpreter searches for the module in the following sequences −

The current directory.


If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/.

The module search path is stored in the system module sys as the [Link] variable. The [Link] variable contains the current directory, PYTHONPATH, and
the installation-dependent default.
The PYTHONPATH Variable
The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable
PATH.

Here is a typical PYTHONPATH from a Windows system −

set PYTHONPATH = c:\python20\lib;

And here is a typical PYTHONPATH from a UNIX system −

set PYTHONPATH = /usr/local/lib/python

Namespaces and Scoping


Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values).

A Python statement can access variables in a local namespace and in the global namespace . If a local and a global variable have the same name, the local
variable shadows the global variable.
Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local.
In order to assign a value to a global variable within a function, you must first use the global statement.
The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable.

Example
For example, we define a variable Money in the global namespace. Within the function Money , we assign Money a value, therefore Python assumes Money
as a local variable. However, we accessed the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the
global statement fixes the problem.

Open Compiler

Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1

print (Money)
AddMoney()
print (Money)

Module Attributes
In Python, a module is an object of module class, and hence it is characterized by attributes.

Following are the module attributes −

file returns the physical name of the module.


package returns the package to which the module belongs.
doc returns the docstring at the top of the module if any
dict returns the entire scope of the module
name returns the name of the module

Example
Assuming that the following code is saved as [Link]

"The docstring of mymodule"


def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2

def power(x,y):
return x**y

Let us check the attributes of mymodule by importing it in the following script −

import mymodule

print ("file attribute:", [Link])


print ("doc attribute:", [Link])
print ("name attribute:", [Link])

It will produce the following output −

1 __file__ attribute: C:\math\examples\[Link]


2 __doc__ attribute: The docstring of mymodule
3 __name__ attribute: mymodule

The nameAttribute
The name attribute of a Python module has great significance. Let us explore it in more detail.

In an interactive shell, name attribute returns 'main'

>>> __name__
'__main__'

If you import any module in the interpreter session, it returns the name of the module as the name attribute of that module.

>>> import math


>>> math.__name__
'math'

From inside a Python script, the name attribute returns 'main'

#[Link]
print ("__name__ attribute within a script:", __name__)

Run this in the command terminal −

__name__ attribute within a script: __main__

This attribute allows a Python script to be used as executable or as a module. Unlike in C++, Java, C# etc., in Python, there is no concept of the main()
function. The Python program script with .py extension can contain function definitions as well as executable statements.

Save [Link] and with the following code −

Open Compiler

"The docstring of mymodule"


def sum(x,y):
return x+y

print ("sum:",sum(10,20))

You can see that sum() function is called within the same script in which it is defined.

1 sum: 30

Now let us import this function in another script [Link] .

import mymodule
print ("sum:",[Link](10,20))

It will produce the following output −

1 sum: 30
2 sum: 30

The output "sum:30" appears twice. Once when mymodule module is imported. The executable statements in imported module are also run. Second output is
from the calling script, i.e., [Link] program.

What we want to happen is that when a module is imported, only the function should be imported, its executable statements should not run. This can be done
by checking the value of name. If it is main, means it is being run and not imported. Include the executable statements like function calls conditionally.
Add if statement in [Link] as shown −

Open Compiler

"The docstring of mymodule"


def sum(x,y):
return x+y

if name == "main":
print ("sum:",sum(10,20))

Now if you run [Link] program, you will find that the sum:30 output appears only once.

1 sum: 30

The dir( ) Function


The dir() built-in function returns a sorted list of strings containing the names defined by a module.

The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −

Open Compiler

# Import built-in module math


import math

content = dir(math)
print (content)

When the above code is executed, it produces the following result −

1 ['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',


2 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
3 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
4 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
5 'sqrt', 'tan', 'tanh']

The reload() Function


Sometimes you may need to reload a module, especially when working with the interactive interpreter session of Python.

Assume that we have a test module ([Link]) with the following function −

def SayHello(name):
print ("Hi {}! How are you?".format(name))
return

We can import the module and call its function from Python prompt as −

1 >>> import test


2 >>> [Link]("Deepak")
3 Hi Deepak! How are you?

However, suppose you need to modify the SayHello() function, such as −

def SayHello(name, course):


print ("Hi {}! How are you?".format(name))
print ("Welcome to {} Tutorial by TutorialsPoint".format(course))
return

Even if you edit the [Link] file and save it, the function loaded in the memory won't update. You need to reload it, using reload() function in imp module.

1 >>> import imp


2 >>> [Link](test)
3 >>> [Link]("Deepak", "Python")
4 Hi Deepak! How are you?
5 Welcome to Python Tutorial by TutorialsPoint
Packages in Python
A package is a hierarchical file directory structure that defines a single Python application environment that consists of modules, subpackages and, sub-
subpackages, and so on.

Consider a file [Link] available in Phone directory. This file has following line of source code −

def Pots():
print "I'm Pots Phone"

Similar way, we have another two files having different functions with the same name as above −

Phone/[Link] file having function Isdn()


Phone/[Link] file having function G3()

Now, create one more file [Link] in Phone directory −

Phone/[Link]

To make all of your functions available when you've imported Phone, you need to put explicit import statements in [Link] as follows −

from Pots import Pots


from Isdn import Isdn
from G3 import G3

After you add these lines to [Link], you have all of these classes available when you import the Phone package.

# Now import your Phone Package.


import Phone

[Link]()
[Link]()
Phone.G3()

When the above code is executed, it produces the following result −

1 I'm Pots Phone


2 I'm 3G Phone
3 I'm ISDN Phone

In the above example, we have taken example of a single functions in each file, but you can keep multiple functions in your files. You can also define
different Python classes in those files and then you can create your packages out of those classes.

Built-in Functions in Python?


Built-in functions are those functions that are pre-defined in the Python interpreter and you don't need to import any module to use them. These functions
help to perform a wide variety of operations on strings, iterators, and numbers. For instance, the built-in functions like sum(), min(), and max() are used to
simplify mathematical operations.

How to Use Built-in Function in Python?


To use built-in functions in your code, simply call the specific function by passing the required parameter (if any) inside the parentheses. Since these
functions are pre-defined, you don't need to import any module or package.

Example of Using Built-in Functions


Consider the following example demonstrating the use of built-in functions in your code:

# Using print() and len() function

text = "Tutorials Point"

print(len(text)) # Prints 15

In the above example, we are using two built-in functions print() and len().

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.## List
of Python Built-in Functions

As of Python 3.12.2 version, the list of built-in functions is given below −


[Link]. Function & Description

1 Python aiter() functionReturns an asynchronous iterator for an asynchronous iterable.

2 Python all() functionReturns true when all elements in iterable is true.

3 Python anext() functionReturns the next item from the given asynchronous iterator.

4 Python any() functionChecks if any Element of an Iterable is True.

5 Python ascii() functionReturns String Containing Printable Representation.

6 Python bin() functionConverts integer to binary string.

7 Python bool() functionConverts a Value to Boolean.

8 Python breakpoint() functionThis function drops you into the debugger at the call site and calls [Link]().

9 Python bytearray() functionReturns array of given byte size.

10 Python bytes() functionReturns immutable bytes object.

11 Python callable() functionChecks if the Object is Callable.

12 Python chr() functionReturns a Character (a string) from an Integer.

13 Python classmethod() functionReturns class method for given function.

14 Python compile() functionReturns a code object.

15 Python complex() functionCreates a Complex Number.

16 Python delattr() functionDeletes Attribute From the Object.

17 Python dict() functionCreates a Dictionary.

18 Python dir() functionTries to Return Attributes of Object.

19 Python divmod() functionReturns a Tuple of Quotient and Remainder.

20 Python enumerate() functionReturns an Enumerate Object.

21 Python eval() functionRuns Code Within Program.

22 Python exec() functionExecutes Dynamically Created Program.

23 Python filter() functionConstructs iterator from elements which are true.

24 Python float() functionReturns floating point number from number, string.

25 Python format() functionReturns formatted representation of a value.

26 Python frozenset() functionReturns immutable frozenset object.

27 Python getattr() functionReturns value of named attribute of an object.

28 Python globals() functionReturns dictionary of current global symbol table.

29 Python hasattr() functionReturns whether object has named attribute.

30 Python hash() functionReturns hash value of an object.

31 Python help() functionInvokes the built-in Help System.

32 Python hex() functionConverts to Integer to Hexadecimal.

33 Python id() functionReturns Identify of an Object.

34 Python input() functionReads and returns a line of string.

35 Python int() functionReturns integer from a number or string.

36 Python isinstance() functionChecks if a Object is an Instance of Class.


[Link]. Function & Description

37 Python issubclass() functionChecks if a Class is Subclass of another Class.

38 Python iter() functionReturns an iterator.

39 Python len() functionReturns Length of an Object.

40 Python list() functionCreates a list in Python.

41 Python locals() functionReturns dictionary of a current local symbol table.

42 Python map() functionApplies Function and Returns a List.

43 Python memoryview() functionReturns memory view of an argument.

44 Python next() functionRetrieves next item from the iterator.

45 Python object() functionCreates a featureless object.

46 Python oct() functionReturns the octal representation of an integer.

47 Python open() functionReturns a file object.

48 Python ord() functionReturns an integer of the Unicode character.

49 Python print() functionPrints the Given Object.

50 Python property() functionReturns the property attribute.

51 Python range() functionReturns a sequence of integers.

52 Python repr() functionReturns a printable representation of the object.

53 Python reversed() functionReturns the reversed iterator of a sequence.

54 Python set() functionConstructs and returns a set.

55 Python setattr() functionSets the value of an attribute of an object.

56 Python slice() functionReturns a slice object.

57 Python sorted() functionReturns a sorted list from the given iterable.

58 Python staticmethod() functionTransforms a method into a static method.

59 Python str() functionReturns the string version of the object.

60 Python super() functionReturns a proxy object of the base class.

61 Python tuple() functionReturns a tuple.

62 Python type() functionReturns the type of the object.

63 Python vars() functionReturns the dict attribute.

64 Python zip() functionReturns an iterator of tuples.

65 Python import() functionFunction called by the import statement.

66 Python unichr() functionConverts a Unicode code point to its corresponding Unicode character.

67 Python long() functionRepresents integers of arbitrary size.

Built-in Mathematical Functions


There are some additional built-in functions that are used for performing only mathematical operations in Python, they are listed below −

[Link]. Function & Description

1 Python abs() functionThe abs() function returns the absolute value of x, i.e. the positive distance between x and zero.
[Link]. Function & Description

2 Python max() functionThe max() function returns the largest of its arguments or largest number from the iterable (list or tuple).

3 Python min() functionThe function min() returns the smallest of its arguments i.e. the value closest to negative infinity, or smallest number from
the iterable (list or tuple)

4 Python pow() functionThe pow() function returns x raised to y. It is equivalent to xy. The function has third optional argument mod. If
given, it returns (xy) % mod value

5 Python round() Functionround() is a built-in function in Python. It returns x rounded to n digits from the decimal point.

6 Python sum() functionThe sum() function returns the sum of all numeric items in any iterable (list or tuple). An optional start argument is 0 by
default. If given, the numbers in the list are added to start value.

Advantages of Using Built-in Functions


The following are the advantages of using built-in functions:

The use of the built-in functions simplifies and reduces the code length and enhances the readability of the code.
Instead of writing the same logic repeatedly, you can use these functions across different sections of the program. This not only saves time but also helps in
maintaining consistency of code.
These functions provide a wide range of functionalities including mathematical operations, datatype conversion, and performing operations on iterators.
These functions have descriptive names that make the code easier to understand and maintain. Developers need not write additional complex code for
performing certain operations.

Frequently Asked Questions about Built-in Functions

How do I handle errors with built-in functions?


While working with built-in functions, you may encounter errors and to handle those errors you can use the try-except blocks. This may help you identify the
type of error and exceptions raised.

Can we extend the functionality of built-in functions?


Yes, we can extend the functionality of built-in functions by using it with other methods and by applying your logic as per the need. However, it will not
affect the pre-defined feature of the used function.

Can I create my built-in functions?


No, you cannot create your built-in function. But, Python allows a user to create user-defined functions.

How do I use built-in functions?


Using a built-in function is very simple, call it by its name followed by parentheses, and pass the required arguments inside the parentheses.

In Python, a string is an immutable sequence of Unicode characters. Each character has a unique numeric value as per the UNICODE standard. But, the
sequence as a whole, doesn't have any numeric value even if all the characters are digits. To differentiate the string from numbers and other identifiers, the
sequence of characters is included within single, double or triple quotes in its literal representation. Hence, 1234 is a number (integer) but '1234' is a string.

Creating Python Strings


As long as the same sequence of characters is enclosed, single or double or triple quotes don't matter. Hence, following string representations are equivalent.
Example
>>> 'Welcome To TutorialsPoint'
'Welcome To TutorialsPoint'
>>> "Welcome To TutorialsPoint"
'Welcome To TutorialsPoint'
>>> '''Welcome To TutorialsPoint'''
'Welcome To TutorialsPoint'
>>> """Welcome To TutorialsPoint"""
'Welcome To TutorialsPoint'

Looking at the above statements, it is clear that, internally Python stores strings as included in single quotes.

In older versions strings are stored internally as 8-bit ASCII, hence it is required to attach 'u' to make it Unicode. Since Python 3, all strings are
represented in Unicode. Therefore, It is no longer necessary now to add 'u' after the string.

Accessing Values in Strings


Python does not support a character type; these are treated as strings of length one, thus also considered a substring.

To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −

Open Compiler

var1 = 'Hello World!'


var2 = "Python Programming"

print ("var1[0]: ", var1[0])


print ("var2[1:5]: ", var2[1:5])

When the above code is executed, it produces the following result −

1 var1[0]: H
2 var2[1:5]: ytho

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Updating Strings

You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely
different string altogether. For example −

Open Compiler

var1 = 'Hello World!'


print ("Updated String :- ", var1[:6] + 'Python')

When the above code is executed, it produces the following result −

1 Updated String :- Hello Python

Visit our Python - Modify Strings tutorial to know more about updating/modifying strings.

Escape Characters
Following table is a list of escape or non-printable characters that can be represented with backslash notation.

An escape character gets interpreted; in a single quoted as well as double quoted strings.

Backslash notation Hexadecimal character Description

\a 0x07 Bell or alert

\b 0x08 Backspace

\cx Control-x

\C-x Control-x

\e 0x1b Escape
Backslash notation Hexadecimal character Description

\f 0x0c Formfeed

\M-\C-x Meta-Control-x

\n 0x0a Newline

\nnn Octal notation, where n is in the range 0.7

\r 0x0d Carriage return

\s 0x20 Space

\t 0x09 Tab

\v 0x0b Vertical tab

\x Character x

\xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

String Special Operators


Assume string variable a holds 'Hello' and variable b holds 'Python', then −

Operator Description Example

+ Concatenation - Adds values on either side of the operator a + b will give


HelloPython

* Repetition - Creates new strings, concatenating multiple copies of the same string a*2 will give -
HelloHello

[] Slice - Gives the character from the given index a[1] will give e

[:] Range Slice - Gives the characters from the given range a[1:4] will give ell

in Membership - Returns true if a character exists in the given string H in a will give 1

not in Membership - Returns true if a character does not exist in the given string M not in a will give 1

r/R Raw String - Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for print r'\n' prints \n
normal strings with the exception of the raw string operator, the letter "r," which precedes the quotation marks. The and print R'\n'prints
"r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. \n

% Format - Performs String formatting See at next section

String Formatting Operator


One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's
printf() family. Following is a simple example −

Open Compiler

print ("My name is %s and weight is %d kg!" % ('Zara', 21))

When the above code is executed, it produces the following result −

1 My name is Zara and weight is 21 kg!

Here is the list of complete set of symbols which can be used along with % −

[Link]. Format Symbol & Conversion

1 %ccharacter
[Link]. Format Symbol & Conversion

2 %sstring conversion via str() prior to formatting

3 %isigned decimal integer

4 %dsigned decimal integer

5 %uunsigned decimal integer

6 %ooctal integer

7 %xhexadecimal integer (lowercase letters)

8 %Xhexadecimal integer (UPPERcase letters)

9 %eexponential notation (with lowercase 'e')

10 %Eexponential notation (with UPPERcase 'E')

11 %ffloating point real number

12 %gthe shorter of %f and %e

13 %Gthe shorter of %f and %E

Other supported symbols and functionality are listed in the following table −

[Link]. Symbol & Functionality

1 *argument specifies width or precision

2 -left justification

3 +display the sign

4 <sp>leave a blank space before a positive number

5 #add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.

6 0pad from left with zeros (instead of spaces)

7 %'%%' leaves you with a single literal '%'

8 (var)mapping variable (dictionary arguments)

9 m.n.m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)

Visit our Python - String Formatting tutorial to learn about various ways to format strings.

Double Quotes in Python Strings


You want to embed some text in double quotes as a part of string, the string itself should be put in single quotes. To embed a single quoted text, string should
be written in double quotes.

Example
Open Compiler

var = 'Welcome to "Python Tutorial" from TutorialsPoint'


print ("var:", var)

var = "Welcome to 'Python Tutorial' from TutorialsPoint"


print ("var:", var)

It will produce the following output −


1 var: Welcome to "Python Tutorial" from TutorialsPoint
2 var: Welcome to 'Python Tutorial' from TutorialsPoint

Triple Quotes
To form a string with triple quotes, you may use triple single quotes, or triple double quotes − both versions are similar.

Example
Open Compiler

var = '''Welcome to TutorialsPoint'''


print ("var:", var)

var = """Welcome to TutorialsPoint"""


print ("var:", var)

It will produce the following output −

1 var: Welcome to TutorialsPoint


2 var: Welcome to TutorialsPoint

Python Multiline Strings


Triple quoted string is useful to form a multi-line string.

Example
Open Compiler

var = '''
Welcome To
Python Tutorial
from TutorialsPoint
'''
print ("var:", var)

It will produce the following output −

1 var:
2 Welcome To
3 Python Tutorial
4 from TutorialsPoint

Arithmetic Operators with Strings


A string is a non-numeric data type. Obviously, we cannot use arithmetic operators with string operands. Python raises TypeError in such a case.

Open Compiler

print ("Hello"-"World")

On executing the above program it will generate the following error −

1 >>> "Hello"-"World"
2 Traceback (most recent call last):
3 File "<stdin>", line 1, in <module>
4 TypeError: unsupported operand type(s) for -: 'str' and 'str'
Getting Type of Python Strings
A string in Python is an object of str class. It can be verified with type() function.

Example
Open Compiler

var = "Welcome To TutorialsPoint"


print (type(var))

It will produce the following output −

1 <class 'str'>

Built-in String Methods


Python includes the following built-in methods to manipulate strings −

[Link]. Methods with Description

1 capitalize()Capitalizes first letter of string.

2 casefold()Converts all uppercase letters in string to lowercase. Similar to lower(), but works on UNICODE characters alos.

3 center(width, fillchar)Returns a space-padded string with the original string centered to a total of width columns.

4 count(str, beg= 0,end=len(string))Counts how many times str occurs in string or in a substring of string if starting index beg and ending index
end are given.

5 decode(encoding='UTF-8',errors='strict')Decodes the string using the codec registered for encoding. encoding defaults to the default string
encoding.

6 encode(encoding='UTF-8',errors='strict')Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given
with 'ignore' or 'replace'.

7 endswith(suffix, beg=0, end=len(string))Determines if string or a substring of string (if starting index beg and ending index end are given) ends
with suffix; returns true if so and false otherwise.

8 expandtabs(tabsize=8)Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.

9 find(str, beg=0 end=len(string))Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given
returns index if found and -1 otherwise.

10 format(*args, **kwargs)This method is used to format the current string value.

11 format_map(mapping)This method is also use to format the current string the only difference is it uses a mapping object.

12 index(str, beg=0, end=len(string))Same as find(), but raises an exception if str not found.

13 isalnum()Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.

14 isalpha()Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.

15 isascii()Returns True is all the characters in the string are from the ASCII character set.

16 isdecimal()Returns true if a unicode string contains only decimal characters and false otherwise.

17 isdigit()Returns true if string contains only digits and false otherwise.

18 isidentifier()Checks whether the string is a valid Python identifier.

19 islower()Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

20 isnumeric()Returns true if a unicode string contains only numeric characters and false otherwise.

21 isprintable()Checks whether all the characters in the string are printable.


[Link]. Methods with Description

22 isspace()Returns true if string contains only whitespace characters and false otherwise.

23 istitle()Returns true if string is properly "titlecased" and false otherwise.

24 isupper()Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

25 join(seq)Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.

26 ljust(width[, fillchar])Returns a space-padded string with the original string left-justified to a total of width columns.

27 lower()Converts all uppercase letters in string to lowercase.

28 lstrip()Removes all leading white space in string.

29 maketrans()Returns a translation table to be used in translate function.

30 partition()Splits the string in three string tuple at the first occurrence of separator.

31 removeprefix()Returns a string after removing the prefix string.

32 removesuffix()Returns a string after removing the suffix string.

33 replace(old, new [, max])Replaces all occurrences of old in string with new or at most max occurrences if max given.

34 rfind(str, beg=0,end=len(string))Same as find(), but search backwards in string.

35 rindex( str, beg=0, end=len(string))Same as index(), but search backwards in string.

36 rjust(width,[, fillchar])Returns a space-padded string with the original string right-justified to a total of width columns.

37 rpartition()Splits the string in three string tuple at the ladt occurrence of separator.

38 rsplit()Splits the string from the end and returns a list of substrings.

39 rstrip()Removes all trailing whitespace of string.

40 split(str="", num=[Link](str))Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most
num substrings if given.

41 splitlines( num=[Link]('\n'))Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.

42 startswith(str, beg=0,end=len(string))Determines if string or a substring of string (if starting index beg and ending index end are given) starts
with substring str; returns true if so and false otherwise.

43 strip([chars])Performs both lstrip() and rstrip() on string.

44 swapcase()Inverts case for all letters in string.

45 title()Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.

46 translate(table, deletechars="")Translates string according to translation table str(256 chars), removing those in the del string.

47 upper()Converts lowercase letters in string to uppercase.

48 zfill (width)Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less
one zero).

Built-in Functions with Strings


Following are the built-in functions we can use with strings −

[Link]. Function with Description

1 len(list)Returns the length of the string.

2 max(list)Returns the max alphabetical character from the string str.

3 min(list)Returns the min alphabetical character from the string str.


Python String slicing is a way of creating a sub-string from a given string. In this process, we extract a portion or piece of a string. Usually, we use the slice
operator "[ : ]" to perform slicing on a Python String. Before proceeding with string slicing let's understand string indexing.

In Python, a string is an ordered sequence of Unicode characters. Each character in the string has a unique index in the sequence. The index starts with 0. First
character in the string has its positional index 0. The index keeps incrementing towards the end of string.

If a string variable is declared as var="HELLO PYTHON", index of each character in the string is as follows −

Python String Indexing


Python allows you to access any individual character from the string by its index. In this case, 0 is the lower bound and 11 is the upper bound of the string.
So, var[0] returns H, var[6] returns P. If the index in square brackets exceeds the upper bound, Python raises IndexError.

Example
In the below example, we accessing the characters of a string through index.

Open Compiler

var = "HELLO PYTHON"


print(var[0])
print(var[7])
print(var[11])
print(var[12])

On running the code, it will produce the following output −

1 H
2 Y
3 N
4 ERROR!
5 Traceback (most recent call last):
6 File "<[Link]>", line 5, in <module>
7 IndexError: string index out of range

Python String Negative & Positive Indexing


One of the unique features of Python sequence types (and therefore a string object) is that it has a negative indexing scheme also. In the example above, a
positive indexing scheme is used where the index increments from left to right. In case of negative indexing, the character at the end has -1 index and the
index decrements from right to left, as a result the first character H has -12 index.
Example
Let us use negative indexing to fetch N, Y, and H characters.

Open Compiler

var = "HELLO PYTHON"


print(var[-1])
print(var[-5])
print(var[-12])

On executing the above code, it will give the following result −

1 N
2 Y
3 H

We can therefore use positive or negative index to retrieve a character from the string.

In Python, string is an immutable object. The object is immutable if it cannot be modified in-place, once stored in a certain memory location. You can retrieve
any character from the string with the help of its index, but you cannot replace it with another character.

Example
In the following example, character Y is at index 7 in HELLO PYTHON. Try to replace Y with y and see what happens.

Open Compiler

var="HELLO PYTHON"
var[7]="y"
print (var)

It will produce the following output −

1 Traceback (most recent call last):


2 File "C:\Users\users\[Link]", line 2, in <module>
3 var[7]="y"
4 ~~~^^^
5 TypeError: 'str' object does not support item assignment

The TypeError is because the string is immutable.

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Python String Slicing

Python defines ":" as string slicing operator. It returns a substring from the original string. Its general usage is as follows −

substr=var[x:y]
The ":" operator needs two integer operands (both of which may be omitted, as we shall see in subsequent examples). The first operand x is the index of the
first character of the desired slice. The second operand y is the index of the character next to the last in the desired string. So var(x:y] separates characters
from xth position to (y-1)th position from the original string.

Example
Open Compiler

var="HELLO PYTHON"

print ("var:",var)
print ("var[3:8]:", var[3:8])

It will produce the following output −

1 var: HELLO PYTHON


2 var[3:8]: LO PY

Python String Slicing With Negative Indexing


Like positive indexes, negative indexes can also be used for slicing.

Example
The below example shows how to slice a string using negative indexes.

Open Compiler

var="HELLO PYTHON"
print ("var:",var)
print ("var[3:8]:", var[3:8])
print ("var[-9:-4]:", var[-9:-4])

It will produce the following output −

1 var: HELLO PYTHON


2 var[3:8]: LO PY
3 var[-9:-4]: LO PY

Default Values of Indexes with String Slicing


Both the operands for Python's Slice operator are optional. The first operand defaults to zero, which means if we do not give the first operand, the slice starts
of character at 0th index, i.e. the first character. It slices the leftmost substring up to "y-1" characters.

Example
In this example, we are performing slice operation using default values.

Open Compiler

var="HELLO PYTHON"
print ("var:",var)
print ("var[0:5]:", var[0:5])
print ("var[:5]:", var[:5])

It will produce the following output −

1 var: HELLO PYTHON


2 var[0:5]: HELLO
3 var[:5]: HELLO
Example
Similarly, y operand is also optional. By default, it is "-1", which means the string will be sliced from the xth position up to the end of string.

Open Compiler

var="HELLO PYTHON"
print ("var:",var)
print ("var[6:12]:", var[6:12])
print ("var[6:]:", var[6:])

It will produce the following output −

1 var: HELLO PYTHON


2 var[6:12]: PYTHON
3 var[6:]: PYTHON

Example
Naturally, if both the operands are not used, the slice will be equal to the original string. That's because "x" is 0, and "y" is the last index+1 (or -1) by default.

Open Compiler

var="HELLO PYTHON"
print ("var:",var)
print ("var[0:12]:", var[0:12])
print ("var[:]:", var[:])

It will produce the following output −

1 var: HELLO PYTHON


2 var[0:12]: HELLO PYTHON
3 var[:]: HELLO PYTHON

Example
The left operand must be smaller than the operand on right, for getting a substring of the original string. Python doesn't raise any error, if the left operand is
greater, bu returns a null string.

Open Compiler

var="HELLO PYTHON"
print ("var:",var)
print ("var[-1:7]:", var[-1:7])
print ("var[7:0]:", var[7:0])

It will produce the following output −

1 var: HELLO PYTHON


2 var[-1:7]:
3 var[7:0]:

Return Type of String Slicing


Slicing returns a new string. You can very well perform string operations like concatenation, or slicing on the sliced string.

Example
Open Compiler

var="HELLO PYTHON"

print ("var:",var)
print ("var[:6][:2]:", var[:6][:2])
var1=var[:6]
print ("slice:", var1)
print ("var1[:2]:", var1[:2])

It will produce the following output −

1 var: HELLO PYTHON


2 var[:6][:2]: HE
3 slice: HELLO
4 var1[:2]: HE

String modification refers to the process of changing the characters of a string. If we talk about modifying a string in Python, what we are talking about is
creating a new string that is a variation of the original one.

In Python, a string (object of str class) is of immutable type. Here, immutable refers to an object that cannot be modified in place once it's created in memory.
Unlike a list, we cannot overwrite any character in the sequence, nor can we insert or append characters to it directly. If we need to modify a string, we will
use certain string methods that return a new string object. However, the original string remains unchanged.

We can use any of the following tricks as a workaround to modify a string.

Converting a String to a List


Both strings and lists in Python are sequence types, they are interconvertible. Thus, we can cast a string to a list, modify the list using methods like insert(),
append(), or remove() and then convert the list back to a string to obtain a modified version.

Suppose, we have a string variable s1 with WORD as its value and we are required to convert it into a list. For this operation, we can use the list() built-in
function and insert a character L at index 3. Then, we can concatenate all the characters using join() method of str class.

Example
The below example practically illustrates how to convert a string into a list.

Open Compiler

s1="WORD"
print ("original string:", s1)
l1=list(s1)

[Link](3,"L")

print (l1)

s1=''.join(l1)
print ("Modified string:", s1)

It will produce the following output −

1 original string: WORD


2 ['W', 'O', 'R', 'L', 'D']
3 Modified string: WORLD

Using the Array Module


To modify a string, construct an array object using the Python standard library named array module. It will create an array of Unicode type from a string
variable.

Example
In the below example, we are using array module to modify the specified string.

Open Compiler

import array as ar
# initializing a string
s1="WORD"
print ("original string:", s1)

# converting it to an array
sar=[Link]('u', s1)

# inserting an element
[Link](3,"L")

# getting back the modified string


s1=[Link]()
print ("Modified string:", s1)

It will produce the following output −

1 original string: WORD


2 Modified string: WORLD

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Using the StringIO Class

Python's io module defines the classes to handle streams. The StringIO class represents a text stream using an in-memory text buffer. A StringIO object
obtained from a string behaves like a File object. Hence we can perform read/write operations on it. The getvalue() method of StringIO class returns a string.

Example
Let us use the above discussed principle in the following program to modify a string.

Open Compiler

import io

s1="WORD"
print ("original string:", s1)

sio=[Link](s1)
[Link](3)
[Link]("LD")
s1=[Link]()

print ("Modified string:", s1)

It will produce the following output −

1 original string: WORD


2 Modified string: WORLD

Concatenate Strings in Python


String concatenation in Python is the operation of joining two or more strings together. The result of this operation will be a new string that contains the
original strings. The diagram below shows a general string concatenation operation −

In Python, there are numerous ways to concatenate strings. We are going to discuss the following −
Using '+' operator
Concatenating String with space
Using multiplication operator
Using '+' and '*' operators together

String Concatenation using '+' operator


The "+" operator is well-known as an addition operator, returning the sum of two numbers. However, the "+" symbol acts as string concatenation operator
in Python. It works with two string operands, and results in the concatenation of the two.

The characters of the string on the right of plus symbol are appended to the string on its left. Result of concatenation is a new string.

Example
The following example shows string concatenation operation in Python using + operator.

Open Compiler

str1="Hello"
str2="World"
print ("String 1:",str1)
print ("String 2:",str2)
str3=str1+str2
print("String 3:",str3)

It will produce the following output −

1 String 1: Hello
2 String 2: World
3 String 3: HelloWorld

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Concatenating String with space

To insert a whitespace between two strings, we can use a third empty string.

Example
In the below example, we are inserting space between two strings while concatenation.

Open Compiler

str1="Hello"
str2="World"
blank=" "
print ("String 1:",str1)
print ("String 2:",str2)
str3=str1+blank+str2
print("String 3:",str3)

It will produce the following output −

1 String 1: Hello
2 String 2: World
3 String 3: Hello World

String Concatenation By Multiplying


Another symbol *, which we normally use for multiplication of two numbers, can also be used with string operands. Here, * acts as a repetition operator in
Python. One of the operands must be an integer, and the second a string. The integer operand specifies the number of copies of the string operand to be
concatenated.
Example
In this example, the * operator concatenates multiple copies of the string.

Open Compiler

newString = "Hello" * 3
print(newString)

The above code will produce the following output −

1 HelloHelloHello

String Concatenation With '+' and '*' Operators


Both the repetition operator () and the concatenation operator (+), can be used in a single expression to concatenate strings. The "" operator has a higher
precedence over the "+" operator.

Example
In the below example, we are concatenating strings using the + and * operator together.

str1="Hello"
str2="World"
print ("String 1:",str1)
print ("String 2:",str2)
str3=str1+str2*3
print("String 3:",str3)
str4=(str1+str2)*3
print ("String 4:", str4)

To form str3 string, Python concatenates 3 copies of World first, and then appends the result to Hello

1 String 3: HelloWorldWorldWorld

In the second case, the strings str1 and str2 are inside parentheses, hence their concatenation takes place first. Its result is then replicated three times.

1 String 4: HelloWorldHelloWorldHelloWorld

Apart from + and *, no other arithmetic operators can be used with string operands.

String formatting in Python is the process of building a string representation dynamically by inserting the value of numeric expressions in an already
existing string. Python's string concatenation operator doesn't accept a non-string operand. Hence, Python offers following string formatting techniques −

Using % operator
Using format() method of str class
Using f-string
Using String Template class

Using % operator
The "%" (modulo) operator often referred to as the string formatting operator. It takes a format string along with a set of variables and combine them to create
a string that contain values of the variables formatted in the specified way.

Example
To insert a string into a format string using the "%" operator, we use "%s" as shown in the below example −

Open Compiler

name = "Tutorialspoint"
print("Welcome to %s!" % name)
It will produce the following output −

1 Welcome to Tutorialspoint!

Using format() method


It is a built-in method of str class. The format() method works by defining placeholders within a string using curly braces "{}". These placeholders are then
replaced by the values specified in the method's arguments.

Example
In the below example, we are using format() method to insert values into a string dynamically.

Open Compiler

str = "Welcome to {}"


print([Link]("Tutorialspoint"))

On running the above code, it will produce the following output −

1 Welcome to Tutorialspoint

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Using f-string

The f-strings, also known as formatted string literals, is used to embed expressions inside string literals. The "f" in f-strings stands for formatted and prefixing
it with strings creates an f-string. The curly braces "{}" within the string will then act as placeholders that is filled with variables, expressions, or function
calls.

Example
The following example illustrates the working of f-strings with expressions.

Open Compiler

item1_price = 2500
item2_price = 300
total = f'Total: {item1_price + item2_price}'
print(total)

The output of the above code is as follows −

1 Total: 2800

Using String Template class


The String Template class belongs to the string module and provides a way to format strings by using placeholders. Here, placeholders are defined by a dollar
sign ($) followed by an identifier.

Example
The following example shows how to use Template class to format strings.

Open Compiler

from string import Template

# Defining template string


str = "Hello and Welcome to $name !"
# Creating Template object
templateObj = Template(str)

# now provide values


new_str = [Link](name="Tutorialspoint")
print(new_str)

It will produce the following output −

1 Hello and Welcome to Tutorialspoint !

Escape Character
An escape character is a character followed by a backslash (). It tells the Interpreter that this escape character (sequence) has a special meaning. For
instance, \n is an escape sequence that represents a newline. When Python encounters this sequence in a string, it understands that it needs to start a new line.

Unless an 'r' or 'R' prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C. In
Python, a string becomes a raw string if it is prefixed with "r" or "R" before the quotation symbols. Hence 'Hello' is a normal string whereas r'Hello' is a raw
string.

Example
In the below example, we are practically demonstrating raw and normal string.

Open Compiler

# normal string
normal = "Hello"
print (normal)

# raw string
raw = r"Hello"
print (raw)

Output of the above code is shown below −

1 Hello
2 Hello

In normal circumstances, there is no difference between the two. However, when the escape character is embedded in the string, the normal string actually
interprets the escape sequence, whereas the raw string doesn't process the escape character.

Example
In the following example, when a normal string is printed the escape character '\n' is processed to introduce a newline. However, because of the raw string
operator 'r' the effect of escape character is not translated as per its meaning.

Open Compiler

normal = "Hello\nWorld"
print (normal)

raw = r"Hello\nWorld"
print (raw)

On running the above code, it will print the following result −

1 Hello
2 World
3 Hello\nWorld
Escape Characters in Python
The following table shows the different escape characters used in Python -

[Link] Escape Sequence & Meaning

1 <newline>Backslash and newline ignored

2 \Backslash ()

3 'Single quote (')

4 "Double quote (")

5 \aASCII Bell (BEL)

6 \bASCII Backspace (BS)

7 \fASCII Formfeed (FF)

8 \nASCII Linefeed (LF)

9 \rASCII Carriage Return (CR)

10 \tASCII Horizontal Tab (TAB)

11 \vASCII Vertical Tab (VT)

12 \oooCharacter with octal value ooo

13 \xhhCharacter with hex value hh

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.##
Escape Characters Example

The following code shows the usage of escape sequences listed in the above table −

Open Compiler

# ignore \
s = 'This string will not include \
backslashes or newline characters.'
print (s)

# escape backslash
s=s = 'The \character is called backslash'
print (s)

# escape single quote


s='Hello 'Python''
print (s)

# escape double quote


s="Hello "Python""
print (s)

# escape \b to generate ASCII backspace


s='Hel\blo'
print (s)

# ASCII Bell character


s='Hello\a'
print (s)

# newline
s='Hello\nPython'
print (s)

# Horizontal tab
s='Hello\tPython'
print (s)

# form feed
s= "hello\fworld"
print (s)
# Octal notation
s="\101"
print(s)

# Hexadecimal notation
s="\x41"
print (s)

It will produce the following output −

1 This string will not include backslashes or newline characters.


2 The \character is called backslash
3 Hello 'Python'
4 Hello "Python"
5 Helo
6 Hello
7 Hello
8 Python
9 Hello Python
10 hello
11 world
12 A
13 A

Python's built-in str class defines different methods. They help in manipulating strings. Since string is an immutable object, these methods return a copy of
the original string, performing the respective processing on it. The string methods can be classified in following categories −

Case Conversion Methods


This category of built-in methods of Python's str class deal with the conversion of alphabet characters in the string object. Following methods fall in this
category −

[Link]. Method & Description

1 capitalize()Capitalizes first letter of string

2 casefold()Converts all uppercase letters in string to lowercase. Similar to lower(), but works on UNICODE characters alos

3 lower()Converts all uppercase letters in string to lowercase.

4 swapcase()Inverts case for all letters in string.

5 title()Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.

6 upper()Converts lowercase letters in string to uppercase.

Alignment Methods
Following methods in the str class control the alignment of characters within the string object.

[Link]. Methods & Description

1 center(width, fillchar)Returns a string padded with fillchar with the original string centered to a total of width columns.

2 ljust(width[, fillchar])Returns a space-padded string with the original string left-justified to a total of width columns.

3 rjust(width,[, fillchar])Returns a space-padded string with the original string right-justified to a total of width columns.

4 expandtabs(tabsize = 8)Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.

5 zfill (width)Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less
one zero).

Learn Python in-depth with real-world projects through our Python certification course . Enroll and become a certified expert to boost your career.## Split
and Join Methods
Python has the following methods to perform split and join operations −

[Link]. Method & Description

1 lstrip()Removes all leading whitespace in string.

2 rstrip()Removes all trailing whitespace of string.

3 strip()Performs both lstrip() and rstrip() on string

4 rsplit()Splits the string from the end and returns a list of substrings

5 split()Splits string according to delimiter (space if not provided) and returns list of substrings.

6 splitlines()Splits string at NEWLINEs and returns a list of each line with NEWLINEs removed.

7 partition()Splits the string in three string tuple at the first occurrence of separator

8 rpartition()Splits the string in three string tuple at the ladt occurrence of separator

9 join()Concatenates the string representations of elements in sequence into a string, with separator string.

10 removeprefix()Returns a string after removing the prefix string

11 removesuffix()Returns a string after removing the suffix string

Boolean String Methods


Following methods in str class return True or False.

[Link]. Methods & Description

1 isalnum()Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.

2 isalpha()Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.

3 isdigit()Returns true if the string contains only digits and false otherwise.

4 islower()Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

5 isnumeric()Returns true if a unicode string contains only numeric characters and false otherwise.

6 isspace()Returns true if string contains only whitespace characters and false otherwise.

7 istitle()Returns true if string is properly "titlecased" and false otherwise.

8 isupper()Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

9 isascii()Returns True is all the characters in the string are from the ASCII character set

10 isdecimal()Checks if all the characters are decimal characters

11 isidentifier()Checks whether the string is a valid Python identifier

12 isprintable()Checks whether all the characters in the string are printable

Find and Replace Methods


Following are the Find and Replace methods in Python −

[Link]. Method & Description

1 count(sub, beg ,end)Counts how many times sub occurs in string or in a substring of string if starting index beg and ending index end are given.

2 find(sub, beg, end)Determine if sub occurs in string or in a substring of string if starting index beg and ending index end are given returns index
if found and -1 otherwise.
[Link]. Method & Description

3 index(sub, beg, end)Same as find(), but raises an exception if str not found.

4 replace(old, new [, max])Replaces all occurrences of old in string with new or at most max occurrences if max given.

5 rfind(sub, beg, end)Same as find(), but search backwards in string.

6 rindex( sub, beg, end)Same as index(), but search backwards in string.

7 startswith(sub, beg, end)Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring
sub; returns true if so and false otherwise.

8 endswith(suffix, beg, end)Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix;
returns true if so and false otherwise.

Translation Methods
Following are the Translation methods of the string −

[Link]. Method & Description

1 maketrans()Returns a translation table to be used in translate function.

2 translate(table, deletechars="")Translates string according to translation table str(256 chars), removing those in the del string.

Example 1
Python program to find number of vowels in a given string.

Open Compiler

mystr = "All animals are equal. Some are more equal"


vowels = "aeiou"
count=0
for x in mystr:
if [Link]() in vowels: count+=1
print ("Number of Vowels:", count)

It will produce the following output −

1 Number of Vowels: 18

Example 2
Python program to convert a string with binary digits to integer.

Open Compiler

mystr = '10101'

def strtoint(mystr):
for x in mystr:
if x not in '01': return "Error. String with non-binary characters"
num = int(mystr, 2)
return num
print ("binary:{} integer: {}".format(mystr,strtoint(mystr)))

It will produce the following output −

1 binary:10101 integer: 21

Change mystr to '10, 101'


1 binary:10,101 integer: Error. String with non-binary characters

Example 3
Python program to drop all digits from a string.

Open Compiler

digits = [str(x) for x in range(10)]


mystr = 'He12llo, Py00th55on!'
chars = []
for x in mystr:
if x not in digits:
[Link](x)
newstr = ''.join(chars)
print (newstr)

It will produce the following output −

1 Hello, Python!

Exercise Programs
Python program to sort the characters in a string
Python program to remove duplicate characters from a string
Python program to list unique characters with their count in a string
Python program to find number of words in a string
Python program to remove all non-alphabetic characters from a string

QUESTIONS
No code comments

A good code needs no comment. The variables, methods, and any other component of the code such as attributes should use easily identifiable and descriptive
names. “Code comments are smell, remove them.”

Dead comments or code should be deleted

Any unused piece of code or comments should be deleted. The best place to find them is in the version control systems.

Incorrect behaviour at boundaries.

Boundaries should always be unit tested. No behaviour should be assumed.

Positive conditionals

Positive conditionals are easier to read than negative conditionals.

Standard architecture, coding, and design guidelines should be followed.

All the set standard architecture, coding, and design guidelines should be adhered to. Tools should also be used to ensure that this is accurate.

Good and Consistent naming

Try to call variables, methods, classes to be understandable from the caller perspective. And it should be consistent.

KISS principle should be applied

Needless complexity should be avoided. With increase in complexity, some design and codes in the system become useless. All designs and codes should be
kept as simple as possible.

Use of exceptions instead of return codes


In exceptional cases, an exception should be thrown, when the method fails to do its intended purpose. Null or return codes shouldn’t be used.

Make things small. Class size and method size both matter

Typically, method should be small and compact in size. Ideally

1. Introduction to Python
What is Python?
Setting Up the Environment
Your First Python Program
2. Basics of Python
Variables and Data Types
Operators
Strings and Lists
3. Control Structures
Conditional Statements
Loops
Error Handling
4. Functions and Modules
Defining Functions
Function Arguments
Modules and Packages
5. Advanced Topics
Object-Oriented Programming
File Handling
Working with Libraries
6. Data Management
Introduction to Databases
SQL Basics
Data Analysis with Pandas
7. Web Development
Introduction to Web Frameworks
Building Web Applications with Flask/Django
Working with APIs
8. Final Projects
Building a Personal Project
Contributing to Open Source
Preparing for Job Interviews

What is Python?
Introduction to Python
Python is a high-level, interpreted programming language known for its simplicity and readability. Developed by Guido van Rossum and first released in
1991, Python emphasizes code readability with its use of significant indentation.

Key Features of Python:


Easy to Learn and Use: Python's syntax is clear and intuitive, making it an excellent choice for beginners.
Versatile: Python can be used for a wide range of applications, including web development, data analysis, artificial intelligence, scientific computing, and
more.
Extensive Libraries and Frameworks: Python has a rich ecosystem of libraries and frameworks that facilitate various types of programming tasks.
Community Support: Python has a large and active community, which contributes to a wealth of resources and documentation.
Cross-Platform: Python is compatible with multiple operating systems, including Windows, macOS, and Linux.

Popular Uses of Python:


Web Development: Frameworks like Django and Flask are used for creating web applications.
Data Analysis: Libraries like Pandas and NumPy are used for data manipulation and analysis.
Machine Learning and AI: Tools such as TensorFlow and scikit-learn are used for building machine learning models.
Automation: Python scripts are often used for automating repetitive tasks.

Variables and Data Types: Questions


Questions and Answers

1. What is the result of adding an integer and a string?


Code:

1
2 integer_value = 10
3 string_value = "20"
4 result = integer_value + int(string_value)
5 print(result)
6

Hint: You need to convert the string to an integer to perform the addition.

Riddle: I am not a number, but I become one when you change me. What am I?

Short Story: John was a novice coder who often struggled with combining different types of data. One day, he decided to add a number to a string, only to
find himself in an unexpected situation. With a little conversion magic, John discovered that mixing data types could be both fun and educational.

2. How do you check the type of a variable in Python?


Code:

1
2 variable = 3.14
3 print(type(variable))
4

Hint: This function will reveal the type of the variable you pass to it.

Riddle: I tell you what something is without looking inside. What am I?

Short Story: Sarah was working on a project and needed to confirm the type of her variables. She learned that a simple function could reveal the exact nature
of her data, making her debugging process much smoother.

3. What is the difference between a list and a tuple?


Code:
1
2 list_example = [1, 2, 3]
3 tuple_example = (1, 2, 3)
4 list_example[1] = 4 # This works
5 tuple_example[1] = 4 # This will raise an error
6

Hint: Think about mutability when choosing between these two data structures.

Riddle: I am a collection that you can change. My twin is fixed and unchanging. Who am I?

Short Story: Emily was organizing her data and faced a dilemma: should she use a list or a tuple? By understanding their properties, she realized that lists
were flexible, while tuples provided stability and immutability.

4. How can you concatenate two strings in Python?


Code:

1
2 string1 = "Hello"
3 string2 = "World"
4 concatenated_string = string1 + " " + string2
5 print(concatenated_string)
6

Hint: Use the operator that joins two strings together.

Riddle: I bring things together with a simple symbol. What am I?

Short Story: Alex wanted to create a greeting message by joining two strings. With a simple operator, he effortlessly combined them into a single message,
showcasing how powerful string manipulation can be.

5. What is the output of the following code snippet?


Code:

1
2 number = 5
3 result = number * 2
4 print(result)
5

Hint: Multiplying a number by 2 will double its value.

Riddle: If you take me and double me, I grow bigger. What am I?

Short Story: Mia was learning basic arithmetic operations in Python and discovered how multiplying a number could instantly change its value. This simple
operation helped her understand fundamental concepts better.

6. How do you convert a float to an integer?


Code:

1
2 float_value = 9.7
3 int_value = int(float_value)
4 print(int_value)
5

Hint: Use the function that truncates the decimal part of the float.

Riddle: I shorten a number by removing its fractional part. What am I?


Short Story: Liam needed to convert a floating-point number to an integer for his calculations. By using a conversion function, he successfully eliminated
the decimal part and simplified his data.

7. What will be the result of the following operation?


Code:

1
2 text = "Python"
3 number = 3
4 result = text * number
5 print(result)
6

Hint: Multiplying a string by a number will repeat the string.

Riddle: If you repeat me enough times, I’ll become longer. What am I?

Short Story: Olivia wanted to create a repetitive pattern using Python. By multiplying a string with a number, she was able to repeat the string as many times
as needed, demonstrating the power of string operations.

8. How do you check if a variable is of type list?


Code:

1
2 variable = [1, 2, 3]
3 is_list = isinstance(variable, list)
4 print(is_list)
5

Hint: Use the function that checks if a variable matches a specified type.

Riddle: I can tell you if something belongs to a specific type. What am I?

Short Story: Daniel was working with different data types and needed to verify if a variable was a list. By using the right function, he could confidently
check the type of his data and proceed with his work.

9. What is the difference between `==` and `is` in Python?


Code:

1
2 a = [1, 2, 3]
3 b = [1, 2, 3]
4 print(a == b) # True, because the contents are the same
5 print(a is b) # False, because they are different objects
6

Hint: `==` checks for equality of values, while `is` checks for identity of objects.

Riddle: One checks if two things are the same inside, while the other checks if they are the same object. What are they?

Short Story: Laura encountered confusion while comparing objects in Python. She learned that `==` was used for value comparison, while `is` checked if
two variables pointed to the same object in memory.
10. How do you create a dictionary in Python?
Code:

1
2 my_dict = {"name": "Alice", "age": 25}
3 print(my_dict)
4

Hint: Use curly braces and key-value pairs to create a dictionary.

Riddle: I hold pairs of keys and values, like a small data store. What am I?

Short Story: Kevin needed a way to store related data together, like names and ages. He discovered dictionaries in Python, which allowed him to pair keys
with corresponding values, making data management easier.

11. How do you convert a string to a float in Python?


Code:

1
2 string_value = "3.14"
3 float_value = float(string_value)
4 print(float_value)
5

Hint: Use the function that transforms a string representation of a number into a float.

Riddle: I turn a text number into a floating point. What am I?

Short Story: Emma needed to process some numeric data from a text file. She found out that converting the string representation of numbers to floats helped
her perform accurate calculations.

12. What is the output of the following code?


Code:

1
2 x = 10
3 y = 20
4 print(x > y)
5

Hint: This code compares two numbers and checks if the first is greater than the second.

Riddle: I compare two values and show if one is greater. What am I?

Short Story: Mark was learning about comparison operators and used them to compare values. This simple comparison helped him understand how to make
decisions based on numerical conditions.

13. How can you extract the integer part of a float?


Code:

1
2 float_value = 7.89
3 integer_part = int(float_value)
4 print(integer_part)
5

Hint: Use a function to remove the decimal part of a float.

Riddle: I leave behind the decimal part and keep only the whole number. What am I?
Short Story: Alice was dealing with float numbers but only needed the integer part for her calculations. By using a conversion function, she was able to
extract just what she needed.

14. What is the result of the following code?


Code:

1
2 x = "10"
3 y = 5
4 result = int(x) + y
5 print(result)
6

Hint: Convert the string to an integer before performing the addition.

Riddle: I mix a text number with a real number and add them together. What am I?

Short Story: Liam had a string that represented a number and wanted to add it to another integer. By converting the string to an integer, he managed to
perform the addition without errors.

15. How do you create an empty list in Python?


Code:

1
2 empty_list = []
3 print(empty_list)
4

Hint: Use square brackets to initialize an empty list.

Riddle: I start with nothing but can hold many items. What am I?

Short Story: Sarah wanted to start a new project with a blank slate. By creating an empty list, she had a fresh container to add and organize her data as her
project progressed.

16. What will the following code output?


Code:

1
2 value = "Hello"
3 print(value * 3)
4

Hint: Multiplying a string by a number will repeat the string.

Riddle: I can repeat myself multiple times when you ask. What am I?

Short Story: John found that repeating a string was useful for his text-based game. By multiplying the string, he quickly generated repeated patterns for his
game’s interface.

17. How do you check if a variable is of type integer?


Code:
1
2 variable = 42
3 is_integer = isinstance(variable, int)
4 print(is_integer)
5

Hint: Use a function to verify the type of the variable.

Riddle: I can tell you if something is an integer without guessing. What am I?

Short Story: Emma needed to verify data types to ensure compatibility in her program. Using the type-checking function, she confidently handled variables
and avoided type-related bugs.

18. How do you access the first element of a list?


Code:

1
2 my_list = [1, 2, 3, 4]
3 first_element = my_list[0]
4 print(first_element)
5

Hint: List indices start from 0.

Riddle: I am the starting point of a sequence, located at position zero. What am I?

Short Story: Mike was iterating through a list and needed to access the first item. By knowing that list indexing starts at zero, he quickly retrieved the first
element and used it in his application.

19. What is the difference between a string and a list in Python?


Code:

1
2 string_example = "Hello"
3 list_example = [1, 2, 3]
4 print(type(string_example))
5 print(type(list_example))
6

Hint: Strings are immutable sequences of characters, while lists are mutable sequences of items.

Riddle: One is a sequence of characters that can’t be changed, while the other holds items you can modify. What are they?

Short Story: Laura was working with different data types and needed to understand their differences. By exploring strings and lists, she learned that strings
are fixed and lists can be modified, which helped her choose the right data structure for her tasks.

20. How do you remove an item from a list by its value?


Code:

1
2 my_list = [1, 2, 3, 4]
3 my_list.remove(3)
4 print(my_list)
5

Hint: Use a method to remove the first occurrence of a value from the list.

Riddle: I can take away an item from a collection based on what it is, not where it is. What am I?

Short Story: Kevin wanted to clean up his list by removing a specific item. By using the `remove` method, he easily eliminated the value he no longer
needed, keeping his data organized.
21. How do you find the type of a variable in Python?
Code:

1
2 variable = 3.14
3 print(type(variable))
4

Hint: Use a built-in function to check the type of a variable.

Riddle: I reveal what kind of data you're dealing with. What am I?

Short Story: Sam needed to debug his code and was unsure of the types of some variables. By using a built-in function, he quickly identified the types and
fixed the issues.

22. What will the following code output?


Code:

1
2 x = [1, 2, 3]
3 y = x
4 [Link](4)
5 print(x)
6

Hint: When you assign one list to another, they both refer to the same object.

Riddle: If I change a shared item, everyone sees the change. What am I?

Short Story: Alex was working with lists and realized that changes to one list affected another list that was pointing to the same data. Understanding this
helped him manage data more effectively.

23. How do you create a tuple with a single element?


Code:

1
2 single_element_tuple = (5,)
3 print(single_element_tuple)
4

Hint: A trailing comma is needed to create a tuple with only one element.

Riddle: I’m a collection with one member, but I need a special mark to be recognized. What am I?

Short Story: Julia was learning about tuples and needed a way to represent a single item in a tuple. By adding a comma, she successfully created a one-
element tuple for her project.

24. What is the output of this code?


Code:

1
2 x = "Hello"
3 y = "World"
4 print(x + " " + y)
5

Hint: Concatenate the strings to form a complete message.

Riddle: I join two text fragments into a single line. What am I?


Short Story: Lily wanted to display a welcoming message. By concatenating strings, she crafted a greeting that combined different parts into a single,
friendly message.

25. How do you check if a variable is a string?


Code:

1
2 variable = "Sample"
3 is_string = isinstance(variable, str)
4 print(is_string)
5

Hint: Use a function to verify if the variable is of type `str`.

Riddle: I determine if a value is composed of characters. What am I?

Short Story: Mark needed to ensure that user input was a string. By checking the variable type, he confirmed the input type and handled it appropriately in
his program.

26. How do you convert a list to a string?


Code:

1
2 list_example = ['a', 'b', 'c']
3 string_example = ''.join(list_example)
4 print(string_example)
5

Hint: Use a method to concatenate all elements of the list into a single string.

Riddle: I combine list elements into one continuous text. What am I?

Short Story: Anna wanted to combine a list of characters into a single string. By using a join method, she easily transformed the list into a cohesive text.

27. What is the output of the following code?


Code:

1
2 x = 10
3 y = 2.5
4 result = x / y
5 print(result)
6

Hint: Division between an integer and a float results in a float.

Riddle: I divide a whole number by a fractional number to give a result with decimals. What am I?

Short Story: Emma was dividing different types of numbers in her calculations. She learned that dividing an integer by a float results in a float, which helped
her manage numerical precision in her work.

28. How do you check if a variable is a number?


Code:
1
2 variable = 42
3 is_number = isinstance(variable, (int, float))
4 print(is_number)
5

Hint: Use `isinstance` with a tuple of types to check for numbers.

Riddle: I determine if a value can be counted or measured. What am I?

Short Story: Jack needed to check if a variable was a number for his calculations. By using `isinstance`, he was able to confirm the variable’s type and avoid
errors in his math operations.

29. How do you convert an integer to a string?


Code:

1
2 integer_value = 123
3 string_value = str(integer_value)
4 print(string_value)
5

Hint: Use a function to change an integer into its string representation.

Riddle: I turn numbers into text. What am I?

Short Story: Lisa wanted to create a report that included numbers and text. By converting integers to strings, she was able to format her report with both
types of data seamlessly.

30. What will the following code output?


Code:

1
2 x = 1
3 y = 2
4 z = x + y
5 print(z * 2)
6

Hint: First, calculate the sum, then multiply the result.

Riddle: I sum two numbers and then double the result. What am I?

Short Story: Paul was working on a budgeting application. He needed to perform calculations involving sums and multiplications. By understanding how to
sequence operations, he managed his budget accurately.

31. How do you create a dictionary with integer keys and string values?
Code:

1
2 my_dict = {1: 'one', 2: 'two', 3: 'three'}
3 print(my_dict)
4

Hint: Use curly braces to define key-value pairs.

Riddle: I hold pairs of keys and values, and my keys are numbers. What am I?

Short Story: Nora needed a way to map integer keys to their string equivalents. By creating a dictionary, she efficiently stored and accessed the data she
needed for her application.
32. What will be the output of the following code?
Code:

1
2 a = "Python"
3 b = a[:3]
4 print(b)
5

Hint: String slicing allows you to extract parts of a string.

Riddle: I extract a portion of a text using indices. What am I?

Short Story: Maya was working on text processing and needed to extract a substring. By using slicing, she obtained the necessary part of the string for her
analysis.

33. How do you check if a variable is of type float?


Code:

1
2 variable = 3.14
3 is_float = isinstance(variable, float)
4 print(is_float)
5

Hint: Use `isinstance` to verify the type of a variable.

Riddle: I determine if a value has decimals. What am I?

Short Story: Jake needed to ensure that his calculations were done with floating-point numbers. By checking the variable type, he confirmed it was a float
and avoided potential errors.

34. What is the output of this code?


Code:

1
2 x = "Hello"
3 y = x * 3
4 print(y)
5

Hint: Multiplying a string replicates it multiple times.

Riddle: I repeat a string multiple times by using a multiplier. What am I?

Short Story: Olivia wanted to create a repeated pattern in her text-based game. By multiplying a string, she easily generated the repeated content she needed.

35. How do you convert a list of numbers to a list of strings?


Code:

1
2 numbers = [1, 2, 3]
3 strings = list(map(str, numbers))
4 print(strings)
5

Hint: Use the `map` function to apply a conversion to each element.

Riddle: I transform each number into text, one by one. What am I?


Short Story: Emma had a list of numbers and needed them as strings for display purposes. By using the `map` function, she converted the list efficiently.

36. What will be the result of the following code?


Code:

1
2 x = [1, 2, [3, 4]]
3 y = x[2]
4 [Link](5)
5 print(x)
6

Hint: Modifying a nested list will affect the original list.

Riddle: I alter an inner structure which reflects in the outer one. What am I?

Short Story: Rachel was working with nested lists and noticed that changes to an inner list affected the outer list. Understanding this helped her manage
complex data structures more effectively.

37. How do you convert a string to an integer?


Code:

1
2 string_value = "123"
3 integer_value = int(string_value)
4 print(integer_value)
5

Hint: Use a function to change a string to its integer equivalent.

Riddle: I turn text into numbers for mathematical operations. What am I?

Short Story: Chris needed to perform calculations with user input, which was in string form. By converting the string to an integer, he was able to perform
arithmetic operations.

38. What will be the output of the following code?


Code:

1
2 x = 5
3 y = 10
4 z = x * y / 2
5 print(z)
6

Hint: Follow the order of operations to calculate the result.

Riddle: I perform multiplication and division, following the rules of precedence. What am I?

Short Story: Sarah was working on a formula and needed to ensure correct calculations. By understanding the order of operations, she accurately computed
the result for her project.

39. How do you find the length of a string?


Code:
1
2 string_value = "Hello, World!"
3 length = len(string_value)
4 print(length)
5

Hint: Use a built-in function to get the number of characters.

Riddle: I measure how many characters are in a string. What am I?

Short Story: Kevin needed to determine the length of user input for validation. By using the `len` function, he quickly obtained the length and applied the
necessary checks.

40. What is the result of this code?


Code:

1
2 x = 3.14
3 y = round(x)
4 print(y)
5

Hint: Use a function to round a floating-point number to the nearest integer.

Riddle: I take a number with decimals and round it to the nearest whole number. What am I?

Short Story: Lisa needed to round a floating-point number to display a cleaner result. By using the `round` function, she simplified the number for user-
friendly output.

41. How do you concatenate two strings?


Code:

1
2 str1 = "Hello"
3 str2 = "World"
4 result = str1 + " " + str2
5 print(result)
6

Hint: Use the `+` operator to join strings together.

Riddle: I join two pieces of text together, separated by a space. What am I?

Short Story: Emma needed to combine two strings for a greeting message. By concatenating them with a space, she created a personalized welcome message
for her application.

42. What will be the output of this code?


Code:

1
2 a = 10
3 b = 3
4 result = a % b
5 print(result)
6

Hint: The `%` operator gives the remainder of division.

Riddle: I reveal what is left after dividing one number by another. What am I?
Short Story: Alex was working on a project where he needed to find the remainder of a division operation. By using the `%` operator, he efficiently obtained
the result he needed.

43. How do you convert a list of strings to a list of integers?


Code:

1
2 string_list = ["1", "2", "3"]
3 int_list = list(map(int, string_list))
4 print(int_list)
5

Hint: Use `map` to apply `int` conversion to each string in the list.

Riddle: I turn each text item in a list into numbers. What am I?

Short Story: Mia had a list of numeric strings and needed them as integers for processing. By using `map`, she converted the strings to integers for further
calculations.

44. What is the output of the following code?


Code:

1
2 x = [1, 2, 3]
3 [Link](4)
4 print(x)
5

Hint: The `append` method adds an element to the end of a list.

Riddle: I add an item to the end of a collection. What am I?

Short Story: Daniel was managing a list of numbers and needed to add a new element. By using the `append` method, he updated his list with the additional
number.

45. How do you create a tuple with a single element?


Code:

1
2 single_element_tuple = (1,)
3 print(single_element_tuple)
4

Hint: Include a comma after the single element to define a tuple.

Riddle: I hold just one item, but need a comma to be recognized. What am I?

Short Story: Julia needed a tuple with only one element for a function parameter. By using a trailing comma, she correctly created the single-element tuple
for her needs.

46. What will be the result of this code?


Code:
1
2 x = 2
3 y = 5
4 z = x ** y
5 print(z)
6

Hint: The `**` operator is used for exponentiation.

Riddle: I perform the operation of raising one number to the power of another. What am I?

Short Story: Sara was calculating exponential growth for her data analysis. By using the `**` operator, she computed the power and obtained the result
needed for her study.

47. How do you check if a value is of type boolean?


Code:

1
2 value = True
3 is_boolean = isinstance(value, bool)
4 print(is_boolean)
5

Hint: Use `isinstance` to check if a value is a boolean.

Riddle: I verify if a value represents truth or falsehood. What am I?

Short Story: Emma was dealing with conditional logic and needed to ensure a variable was a boolean. By using `isinstance`, she confirmed the type to
prevent logical errors in her code.

48. What is the result of this code?


Code:

1
2 x = "Hello"
3 y = "World"
4 result = f"{x} {y}"
5 print(result)
6

Hint: Use an f-string to format the output with variables.

Riddle: I embed variables into a string using a special format. What am I?

Short Story: Michael needed to format a greeting message with variables. By using an f-string, he easily inserted the variables into the string and displayed
the desired output.

49. How do you create a set in Python?


Code:

1
2 my_set = {1, 2, 3}
3 print(my_set)
4

Hint: Use curly braces to define a set.

Riddle: I contain unique items and don't care about order. What am I?

Short Story: Lisa needed a collection of unique items for her application. By using a set, she ensured that each item appeared only once and maintained the
required data structure.
50. What is the output of the following code?
Code:

1
2 x = [1, 2, 3]
3 [Link]([4, 5])
4 print(x)
5

Hint: The `extend` method adds elements from another iterable to a list.

Riddle: I add elements from one list to another, merging them. What am I?

Short Story: John was merging two lists for data processing. By using the `extend` method, he combined the lists and obtained the complete dataset he
needed.

51. How do you create a dictionary with default values?


Code:

1
2 from collections import defaultdict
3
4 my_dict = defaultdict(int)
5 my_dict['a'] += 1
6 print(my_dict)
7

Hint: Use `defaultdict` from the `collections` module to set default values.

Riddle: I provide a default value for missing keys in a dictionary. What am I?

Short Story: Alex needed a dictionary where missing keys had default values. By using `defaultdict`, he avoided errors and ensured every key had an initial
value.

52. How do you remove a key-value pair from a dictionary?


Code:

1
2 my_dict = {'a': 1, 'b': 2}
3 del my_dict['a']
4 print(my_dict)
5

Hint: Use the `del` statement to remove a key-value pair from a dictionary.

Riddle: I erase a specific entry from a collection of key-value pairs. What am I?

Short Story: Emma had a dictionary and needed to remove an obsolete entry. By using `del`, she cleaned up the dictionary and maintained relevant data.

53. What is the result of this code?


Code:

1
2 x = {1, 2, 3}
3 y = {3, 4, 5}
4 result = x & y
5 print(result)
6

Hint: The `&` operator is used to find the intersection of two sets.
Riddle: I find common elements between two groups. What am I?

Short Story: Michael needed to determine the shared elements between two sets for analysis. By using the `&` operator, he efficiently found the common
values.

54. How do you format a string with variable values?


Code:

1
2 name = "Alice"
3 age = 30
4 formatted_string = f"My name is {name} and I am {age} years old."
5 print(formatted_string)
6

Hint: Use an f-string to embed variables directly within a string.

Riddle: I embed values within a message to personalize it. What am I?

Short Story: Sarah wanted to create a message that included user-specific details. By using an f-string, she personalized the message with the user's name
and age.

55. What will be the output of this code?


Code:

1
2 x = [1, 2, 3]
3 [Link](2)
4 print(x)
5

Hint: The `remove` method deletes the first occurrence of a specified value from a list.

Riddle: I take away a specified item from a list. What am I?

Short Story: Daniel needed to remove a specific item from a list of numbers. By using the `remove` method, he deleted the unwanted element from the list.

56. How do you create a list of squares of numbers from 1 to 5?


Code:

1
2 squares = [x**2 for x in range(1, 6)]
3 print(squares)
4

Hint: Use list comprehension to generate squares of numbers.

Riddle: I create a list where each item is the square of a number. What am I?

Short Story: Lisa wanted a list of squared numbers for a mathematical computation. Using list comprehension, she quickly generated the list of squares.

57. What is the result of the following code?


Code:
1
2 x = "Python"
3 result = x[1:4]
4 print(result)
5

Hint: Use slicing to get a substring from a string.

Riddle: I extract a portion of a string using indices. What am I?

Short Story: Michael needed to extract a specific part of a string for processing. By using slicing, he obtained the substring he needed.

58. How do you create a list from a string where each character is an element?
Code:

1
2 my_string = "hello"
3 char_list = list(my_string)
4 print(char_list)
5

Hint: Convert the string to a list to get each character as an element.

Riddle: I turn each character of a string into an individual list item. What am I?

Short Story: Emma needed to process each character of a string individually. By converting the string to a list, she easily handled each character as a separate
element.

59. What will be the output of this code?


Code:

1
2 x = 10
3 y = 20
4 x, y = y, x
5 print(x, y)
6

Hint: Tuple unpacking allows for swapping variables.

Riddle: I swap the values of two variables. What am I?

Short Story: Sarah needed to exchange the values of two variables. By using tuple unpacking, she efficiently swapped their values without needing a
temporary variable.

60. How do you create an empty set?


Code:

1
2 empty_set = set()
3 print(empty_set)
4

Hint: Use the `set` constructor to create an empty set.

Riddle: I am a collection with no items initially. What am I?

Short Story: Emma started with an empty set to collect unique values. By using the `set` constructor, she prepared a clean slate for her data collection.
61. How do you check if a variable is of type integer?
Code:

1
2 value = 42
3 is_integer = isinstance(value, int)
4 print(is_integer)
5

Hint: Use `isinstance` to verify the type of a variable.

Riddle: I confirm if a variable holds whole numbers. What am I?

Short Story: Alex was verifying data types to ensure correct operations. By using `isinstance`, he confirmed that a variable was indeed an integer.

62. How do you concatenate two strings?


Code:

1
2 str1 = "Hello"
3 str2 = "World"
4 result = str1 + " " + str2
5 print(result)
6

Hint: Use the `+` operator to join strings.

Riddle: I combine two text strings into one. What am I?

Short Story: Lisa needed to create a complete greeting message. By concatenating two strings with the `+` operator, she formed a cohesive message.

63. What will be the result of the following code?


Code:

1
2 x = [1, 2, 3]
3 [Link](4)
4 print(x)
5

Hint: The `append` method adds an element to the end of a list.

Riddle: I add a new item to the end of a collection. What am I?

Short Story: Daniel needed to extend a list of numbers. By using the `append` method, he added a new item to the end of the list, expanding his data
collection.

64. How do you create a tuple with a single element?


Code:

1
2 single_element_tuple = (42,)
3 print(single_element_tuple)
4

Hint: Use a trailing comma to create a single-element tuple.

Riddle: I hold just one item and use a special syntax to denote it. What am I?

Short Story: Emma needed to create a tuple with a single value. By adding a trailing comma, she ensured the tuple was correctly defined with one item.
65. How do you convert a string to an integer?
Code:

1
2 str_number = "123"
3 int_number = int(str_number)
4 print(int_number)
5

Hint: Use the `int` function to convert a string to an integer.

Riddle: I change a text representation of a number into an integer. What am I?

Short Story: Sarah had a string that represented a number and needed to perform arithmetic operations. By using the `int` function, she converted the string
into an integer.

66. What is the output of this code?


Code:

1
2 x = {1, 2, 3}
3 y = {2, 3, 4}
4 result = x | y
5 print(result)
6

Hint: The `|` operator is used to find the union of two sets.

Riddle: I combine all unique elements from two sets into one. What am I?

Short Story: Michael needed a combined list of unique items from two sets. By using the `|` operator, he found the union of both sets efficiently.

67. How do you create a list of numbers from 1 to 10?


Code:

1
2 numbers = list(range(1, 11))
3 print(numbers)
4

Hint: Use `range` and convert it to a list to get a sequence of numbers.

Riddle: I generate a sequence of numbers within a specified range. What am I?

Short Story: Lisa wanted a list of numbers for a loop iteration. By using `range` and converting it to a list, she quickly obtained the sequence of numbers.

68. How do you check if a value is in a list?


Code:

1
2 value = 5
3 my_list = [1, 2, 3, 4, 5]
4 is_in_list = value in my_list
5 print(is_in_list)
6

Hint: Use the `in` keyword to check for membership in a list.

Riddle: I determine if a specific value exists within a collection. What am I?


Short Story: Emma needed to verify if a number was in a list of values. By using the `in` keyword, she quickly checked for the value's presence in the list.

69. How do you convert a list of characters into a string?


Code:

1
2 char_list = ['H', 'e', 'l', 'l', 'o']
3 string = ''.join(char_list)
4 print(string)
5

Hint: Use the `join` method to concatenate characters into a string.

Riddle: I combine characters from a list into a single text string. What am I?

Short Story: Sarah needed to merge a list of characters into a single string. By using the `join` method, she efficiently concatenated the characters into a
coherent message.

70. What is the output of this code?


Code:

1
2 x = "5"
3 y = "10"
4 result = int(x) + int(y)
5 print(result)
6

Hint: Convert strings to integers before performing arithmetic operations.

Riddle: I perform arithmetic on text representations of numbers by first converting them. What am I?

Short Story: Alex had numbers stored as strings and needed to add them. By converting the strings to integers, he was able to perform the arithmetic
operation and obtain the correct result.

71. How do you find the type of a variable?


Code:

1
2 variable = 3.14
3 print(type(variable))
4

Hint: Use the `type` function to check the type of a variable.

Riddle: I reveal the type of a variable, showing what kind of data it holds. What am I?

Short Story: Sarah wanted to confirm the data type of a variable for type-specific operations. By using the `type` function, she easily identified the variable's
type.

72. How do you create a list of tuples with paired elements?


Code:

1
2 list_of_tuples = [(1, 'a'), (2, 'b'), (3, 'c')]
3 print(list_of_tuples)
4
Hint: Use parentheses to define tuples and list brackets for the list.

Riddle: I organize paired elements into tuples within a list. What am I?

Short Story: Michael needed a structured list of paired elements for processing. By creating a list of tuples, he effectively grouped the data for further use.

73. How do you check the length of a string?


Code:

1
2 text = "Hello World"
3 length = len(text)
4 print(length)
5

Hint: Use the `len` function to find the length of a string.

Riddle: I measure the number of characters in a text. What am I?

Short Story: Emma needed to know the length of a string for formatting purposes. By using the `len` function, she easily obtained the number of characters
in the text.

74. How do you remove duplicates from a list?


Code:

1
2 my_list = [1, 2, 2, 3, 4, 4, 5]
3 unique_list = list(set(my_list))
4 print(unique_list)
5

Hint: Convert the list to a set to remove duplicates and then back to a list.

Riddle: I eliminate repeated values from a collection, leaving only unique items. What am I?

Short Story: Lisa needed to clean up a list with duplicate entries. By converting the list to a set and then back to a list, she removed all duplicate values
efficiently.

75. How do you sort a list in ascending order?


Code:

1
2 numbers = [4, 2, 9, 1, 5]
3 [Link]()
4 print(numbers)
5

Hint: Use the `sort` method to order elements in a list.

Riddle: I arrange the elements of a list from smallest to largest. What am I?

Short Story: Alex needed to order a list of numbers for analysis. By using the `sort` method, he arranged the numbers in ascending order for better
readability.
76. How do you find the maximum value in a list?
Code:

1
2 numbers = [1, 3, 7, 2, 5]
3 max_value = max(numbers)
4 print(max_value)
5

Hint: Use the `max` function to get the largest number from a list.

Riddle: I identify the highest value among a collection of numbers. What am I?

Short Story: Sarah needed to find the highest number in a list for her report. By using the `max` function, she quickly identified the maximum value among
the numbers.

77. How do you split a string into a list of words?


Code:

1
2 sentence = "Python is fun"
3 words = [Link]()
4 print(words)
5

Hint: Use the `split` method to divide a string into words.

Riddle: I break a sentence into individual words. What am I?

Short Story: Emma needed to process a sentence by separating it into words. By using the `split` method, she obtained a list of words from the original
sentence.

78. How do you count the occurrences of a specific character in a string?


Code:

1
2 text = "hello"
3 count = [Link]('l')
4 print(count)
5

Hint: Use the `count` method to find the number of occurrences of a character.

Riddle: I determine how many times a specific character appears in a string. What am I?

Short Story: Lisa needed to count how many times a character appeared in a string. By using the `count` method, she found the occurrences of the character
efficiently.

79. How do you reverse a list?


Code:

1
2 numbers = [1, 2, 3, 4, 5]
3 [Link]()
4 print(numbers)
5

Hint: Use the `reverse` method to invert the order of elements in a list.

Riddle: I change the order of items in a list to its opposite. What am I?


Short Story: Michael needed to reverse the order of items in a list for his analysis. By using the `reverse` method, he quickly inverted the order of the list's
elements.

80. How do you find the index of a specific item in a list?


Code:

1
2 my_list = ['apple', 'banana', 'cherry']
3 index = my_list.index('banana')
4 print(index)
5

Hint: Use the `index` method to locate the position of an item in a list.

Riddle: I determine the position of an item within a list. What am I?

Short Story: Sarah needed to find the position of an item in a list. By using the `index` method, she quickly identified the item's location in the list.

81. How do you create a dictionary with keys and values?


Code:

1
2 my_dict = {'name': 'Alice', 'age': 25}
3 print(my_dict)
4

Hint: Use curly braces to define a dictionary with key-value pairs.

Riddle: I store data in key-value pairs for easy access. What am I?

Short Story: Lisa needed to organize information with keys and values. By creating a dictionary, she structured the data for efficient access and
manipulation.

82. How do you get a list of all the keys in a dictionary?


Code:

1
2 my_dict = {'name': 'Alice', 'age': 25}
3 keys = my_dict.keys()
4 print(keys)
5

Hint: Use the `keys` method to retrieve the dictionary's keys.

Riddle: I provide access to the keys stored in a dictionary. What am I?

Short Story: Michael needed to view all the keys in a dictionary. By using the `keys` method, he obtained a list of all the keys in the dictionary.

83. How do you get a list of all the values in a dictionary?


Code:

1
2 my_dict = {'name': 'Alice', 'age': 25}
3 values = my_dict.values()
4 print(values)
5
Hint: Use the `values` method to retrieve the dictionary's values.

Riddle: I provide access to the values stored in a dictionary. What am I?

Short Story: Sarah needed to view all the values in a dictionary. By using the `values` method, she obtained a list of all the values stored in the dictionary.

84. How do you remove a key-value pair from a dictionary?


Code:

1
2 my_dict = {'name': 'Alice', 'age': 25}
3 del my_dict['age']
4 print(my_dict)
5

Hint: Use the `del` statement to remove a specific key-value pair from a dictionary.

Riddle: I remove a specific item from a dictionary. What am I?

Short Story: Emma needed to delete a key-value pair from a dictionary. By using the `del` statement, she efficiently removed the unwanted item from the
dictionary.

85. How do you merge two dictionaries?


Code:

1
2 dict1 = {'name': 'Alice', 'age': 25}
3 dict2 = {'city': 'Wonderland'}
4 merged_dict = {**dict1, **dict2}
5 print(merged_dict)
6

Hint: Use the `**` operator to merge dictionaries.

Riddle: I combine the items of two dictionaries into one. What am I?

Short Story: Lisa needed to combine two dictionaries for her project. By using the `**` operator, she merged the dictionaries into a single comprehensive
dictionary.

86. How do you check if a key exists in a dictionary?


Code:

1
2 my_dict = {'name': 'Alice', 'age': 25}
3 exists = 'name' in my_dict
4 print(exists)
5

Hint: Use the `in` operator to check for a key's existence in a dictionary.

Riddle: I determine whether a key is present in a dictionary. What am I?

Short Story: Michael needed to verify if a key was present in a dictionary. By using the `in` operator, he quickly checked for the key's existence.
87. How do you iterate over a dictionary's keys and values?
Code:

1
2 my_dict = {'name': 'Alice', 'age': 25}
3 for key, value in my_dict.items():
4 print(key, value)
5

Hint: Use the `items` method to iterate over key-value pairs in a dictionary.

Riddle: I help you access both keys and values in a dictionary simultaneously. What am I?

Short Story: Emma needed to process both keys and values in a dictionary. By using the `items` method, she iterated over the key-value pairs and accessed
each item effectively.

88. How do you create a set in Python?


Code:

1
2 my_set = {1, 2, 3, 4, 5}
3 print(my_set)
4

Hint: Use curly braces to define a set with unique elements.

Riddle: I store unique items in an unordered collection. What am I?

Short Story: Sarah needed to store unique values without any particular order. By creating a set, she efficiently managed the unique elements in her
collection.

89. How do you add an element to a set?


Code:

1
2 my_set = {1, 2, 3}
3 my_set.add(4)
4 print(my_set)
5

Hint: Use the `add` method to include an element in a set.

Riddle: I help you include a new item in a collection of unique elements. What am I?

Short Story: Lisa needed to add a new item to her set of unique elements. By using the `add` method, she efficiently included the new item in the set.

90. How do you remove an element from a set?


Code:

1
2 my_set = {1, 2, 3}
3 my_set.remove(2)
4 print(my_set)
5

Hint: Use the `remove` method to delete an element from a set.

Riddle: I help you delete an item from a collection of unique elements. What am I?

Short Story: Michael needed to remove an item from his set of unique values. By using the `remove` method, he efficiently deleted the unwanted item.
91. How do you check if a set contains a specific element?
Code:

1
2 my_set = {1, 2, 3}
3 contains = 2 in my_set
4 print(contains)
5

Hint: Use the `in` operator to check if an element is present in a set.

Riddle: I verify the presence of an item in a unique collection. What am I?

Short Story: Emma needed to check if an item was part of a set. By using the `in` operator, she quickly confirmed the presence of the element.

92. How do you clear all elements from a set?


Code:

1
2 my_set = {1, 2, 3}
3 my_set.clear()
4 print(my_set)
5

Hint: Use the `clear` method to remove all elements from a set.

Riddle: I remove every item from a unique collection. What am I?

Short Story: Sarah needed to empty a set for a fresh start. By using the `clear` method, she removed all elements from the set.

93. How do you find the length of a set?


Code:

1
2 my_set = {1, 2, 3}
3 length = len(my_set)
4 print(length)
5

Hint: Use the `len` function to get the number of elements in a set.

Riddle: I measure the number of unique items in a collection. What am I?

Short Story: Michael needed to know how many items were in a set. By using the `len` function, he quickly determined the set's length.

94. How do you perform a union operation on two sets?


Code:

1
2 set1 = {1, 2, 3}
3 set2 = {3, 4, 5}
4 union_set = [Link](set2)
5 print(union_set)
6

Hint: Use the `union` method to combine elements from two sets.

Riddle: I combine the elements of two unique collections into one. What am I?

Short Story: Emma needed to combine two sets for a comprehensive list. By using the `union` method, she efficiently merged the elements of both sets.
95. How do you perform an intersection operation on two sets?
Code:

1
2 set1 = {1, 2, 3}
3 set2 = {3, 4, 5}
4 intersection_set = [Link](set2)
5 print(intersection_set)
6

Hint: Use the `intersection` method to find common elements between two sets.

Riddle: I identify the elements shared by two unique collections. What am I?

Short Story: Michael needed to find common items between two sets. By using the `intersection` method, he quickly determined the shared elements.

96. How do you perform a difference operation on two sets?


Code:

1
2 set1 = {1, 2, 3}
3 set2 = {3, 4, 5}
4 difference_set = [Link](set2)
5 print(difference_set)
6

Hint: Use the `difference` method to find elements in one set but not in another.

Riddle: I find the items present in one unique collection but not in another. What am I?

Short Story: Emma needed to determine which items were unique to a set compared to another. By using the `difference` method, she identified the unique
elements.

97. How do you perform a symmetric difference operation on two sets?


Code:

1
2 set1 = {1, 2, 3}
3 set2 = {3, 4, 5}
4 symmetric_difference_set = set1.symmetric_difference(set2)
5 print(symmetric_difference_set)
6

Hint: Use the `symmetric_difference` method to find elements that are in either set but not both.

Riddle: I find the items that are unique to each collection, excluding those shared. What am I?

Short Story: Michael needed to identify items that were unique to each of two sets. By using the `symmetric_difference` method, he determined the elements
present in one set but not the other.

98. How do you check if one set is a subset of another?


Code:

1
2 set1 = {1, 2, 3}
3 set2 = {1, 2, 3, 4, 5}
4 is_subset = [Link](set2)
5 print(is_subset)
6
Hint: Use the `issubset` method to check if all elements of one set are in another set.

Riddle: I determine if one unique collection is entirely contained within another. What am I?

Short Story: Sarah needed to check if a set was completely contained within another set. By using the `issubset` method, she confirmed whether all elements
of the first set were present in the second set.

99. How do you check if one set is a superset of another?


Code:

1
2 set1 = {1, 2, 3, 4, 5}
3 set2 = {1, 2, 3}
4 is_superset = [Link](set2)
5 print(is_superset)
6

Hint: Use the `issuperset` method to check if a set contains all elements of another set.

Riddle: I determine if a unique collection contains all elements of another collection. What am I?

Short Story: Emma needed to check if one set contained all elements of another set. By using the `issuperset` method, she confirmed that the first set was
indeed a superset of the second.

100. How do you remove duplicates from a list while preserving the original order?
Code:

1
2 def remove_duplicates(lst):
3 seen = set()
4 result = []
5 for item in lst:
6 if item not in seen:
7 [Link](item)
8 [Link](item)
9 return result
10
11 my_list = [1, 2, 2, 3, 4, 4, 5]
12 unique_list = remove_duplicates(my_list)
13 print(unique_list)
14

Hint: Use a set to track seen elements while iterating through the list to preserve order.

Riddle: I help you clean up a list by removing duplicates and keeping the order intact. What am I?

Short Story: Lisa needed to clean up a list with repeated elements. By using a set to track seen items and preserving the original order, she effectively
removed duplicates from the list.

101. How do you create a list with a fixed number of elements initialized to zero?
Code:

1
2 fixed_size_list = [0] * 10
3 print(fixed_size_list)
4

Hint: Use multiplication to create a list with repeated elements.

Riddle: I help you create a list of a certain size, filled with zeros. What am I?

Short Story: Emma needed a list with ten elements, all set to zero. By multiplying a list with a single zero, she easily created the list she needed.
102. How do you find the index of the first occurrence of an element in a list?
Code:

1
2 my_list = [10, 20, 30, 20, 40]
3 index = my_list.index(20)
4 print(index)
5

Hint: Use the `index` method to find the position of an element in a list.

Riddle: I help you find where an item first appears in a list. What am I?

Short Story: Michael needed to locate the position of the first occurrence of an element. By using the `index` method, he quickly found the element's
position in the list.

103. How do you remove an element by value from a list?


Code:

1
2 my_list = [1, 2, 3, 4]
3 my_list.remove(3)
4 print(my_list)
5

Hint: Use the `remove` method to delete an element by its value.

Riddle: I help you delete a specific item from a list based on its value. What am I?

Short Story: Sarah needed to remove a specific item from a list. By using the `remove` method, she successfully deleted the item by its value.

104. How do you insert an element at a specific position in a list?


Code:

1
2 my_list = [1, 2, 4, 5]
3 my_list.insert(2, 3)
4 print(my_list)
5

Hint: Use the `insert` method to add an element at a specified index.

Riddle: I help you place an item at a precise location within a list. What am I?

Short Story: Emma needed to add an item to a specific position in a list. By using the `insert` method, she placed the item exactly where she wanted it.

105. How do you reverse the order of elements in a list?


Code:

1
2 my_list = [1, 2, 3, 4]
3 my_list.reverse()
4 print(my_list)
5

Hint: Use the `reverse` method to change the order of elements in a list.

Riddle: I help you flip the order of items in a list. What am I?

Short Story: Michael wanted to reverse the order of elements in a list. By using the `reverse` method, he achieved the desired result.
106. How do you sort a list in ascending order?
Code:

1
2 my_list = [4, 2, 3, 1]
3 my_list.sort()
4 print(my_list)
5

Hint: Use the `sort` method to arrange elements in ascending order.

Riddle: I help you arrange items from smallest to largest. What am I?

Short Story: Emma needed to sort a list of numbers in ascending order. By using the `sort` method, she easily organized the elements from smallest to
largest.

107. How do you create a tuple with elements?


Code:

1
2 my_tuple = (1, 2, 3, 4)
3 print(my_tuple)
4

Hint: Use parentheses to create a tuple with multiple elements.

Riddle: I am a collection that holds items in a fixed order. What am I?

Short Story: Sarah wanted to create a collection of items that couldn't be changed. By using parentheses, she created a tuple with the elements she needed.

108. How do you access an element in a tuple by index?


Code:

1
2 my_tuple = (1, 2, 3, 4)
3 element = my_tuple[2]
4 print(element)
5

Hint: Use square brackets and an index to access an element in a tuple.

Riddle: I allow you to retrieve an item from a fixed collection based on its position. What am I?

Short Story: Michael needed to access a specific item in a tuple. By using square brackets and the appropriate index, he retrieved the element he needed.

109. How do you concatenate two tuples?


Code:

1
2 tuple1 = (1, 2, 3)
3 tuple2 = (4, 5, 6)
4 concatenated_tuple = tuple1 + tuple2
5 print(concatenated_tuple)
6

Hint: Use the `+` operator to join two tuples together.

Riddle: I help you merge two fixed collections into one. What am I?

Short Story: Emma wanted to combine two tuples into a single collection. By using the `+` operator, she successfully merged the tuples.
110. How do you create a dictionary with keys and values?
Code:

1
2 my_dict = {'key1': 'value1', 'key2': 'value2'}
3 print(my_dict)
4

Hint: Use curly braces to define a dictionary with key-value pairs.

Riddle: I hold data in pairs, associating keys with values. What am I?

Short Story: Sarah needed to create a collection of key-value pairs. By using curly braces, she built a dictionary with the data she required.

111. How do you access a value in a dictionary by its key?


Code:

1
2 my_dict = {'key1': 'value1', 'key2': 'value2'}
3 value = my_dict['key1']
4 print(value)
5

Hint: Use square brackets with the key to retrieve the corresponding value from a dictionary.

Riddle: I allow you to find the value associated with a specific key. What am I?

Short Story: Michael needed to retrieve a value based on its key from a dictionary. By using square brackets with the key, he accessed the value he needed.

112. How do you add a new key-value pair to an existing dictionary?


Code:

1
2 my_dict = {'key1': 'value1'}
3 my_dict['key2'] = 'value2'
4 print(my_dict)
5

Hint: Assign a value to a new key to add it to the dictionary.

Riddle: I help you expand a collection by adding new key-value pairs. What am I?

Short Story: Emma wanted to add new information to her dictionary. By assigning a value to a new key, she successfully added the new key-value pair.

113. How do you remove a key-value pair from a dictionary?


Code:

1
2 my_dict = {'key1': 'value1', 'key2': 'value2'}
3 del my_dict['key1']
4 print(my_dict)
5

Hint: Use the `del` statement to remove a key-value pair from a dictionary.

Riddle: I assist you in removing a specific item from a collection of key-value pairs. What am I?

Short Story: Sarah needed to remove a specific entry from her dictionary. By using the `del` statement, she successfully deleted the key-value pair.
114. How do you get all the keys from a dictionary?
Code:

1
2 my_dict = {'key1': 'value1', 'key2': 'value2'}
3 keys = my_dict.keys()
4 print(keys)
5

Hint: Use the `keys` method to retrieve all keys from a dictionary.

Riddle: I help you retrieve all the identifiers from a collection of key-value pairs. What am I?

Short Story: Michael needed to get a list of all the keys in his dictionary. By using the `keys` method, he obtained the identifiers he needed.

115. How do you get all the values from a dictionary?


Code:

1
2 my_dict = {'key1': 'value1', 'key2': 'value2'}
3 values = my_dict.values()
4 print(values)
5

Hint: Use the `values` method to retrieve all values from a dictionary.

Riddle: I help you access all the data associated with keys in a collection. What am I?

Short Story: Emma wanted to retrieve all the values from her dictionary. By using the `values` method, she obtained all the data associated with the keys.

116. How do you check if a key exists in a dictionary?


Code:

1
2 my_dict = {'key1': 'value1', 'key2': 'value2'}
3 exists = 'key1' in my_dict
4 print(exists)
5

Hint: Use the `in` operator to check for the presence of a key in a dictionary.

Riddle: I help you verify if a specific identifier is part of a collection of key-value pairs. What am I?

Short Story: Michael needed to confirm whether a particular key was in his dictionary. By using the `in` operator, he checked the presence of the key
efficiently.

117. How do you create an empty dictionary?


Code:

1
2 empty_dict = {}
3 print(empty_dict)
4

Hint: Use empty curly braces to create an empty dictionary.

Riddle: I am a collection ready to hold key-value pairs, but currently, I am empty. What am I?

Short Story: Sarah needed an empty dictionary to start her new project. By using empty curly braces, she created a dictionary ready to be filled with data.
118. How do you merge two dictionaries into one?
Code:

1
2 dict1 = {'key1': 'value1'}
3 dict2 = {'key2': 'value2'}
4 merged_dict = {**dict1, **dict2}
5 print(merged_dict)
6

Hint: Use the unpacking operator to combine two dictionaries into one.

Riddle: I help you combine two collections of key-value pairs into a single one. What am I?

Short Story: Michael needed to merge two dictionaries into one. By using the unpacking operator, he successfully combined the two collections.

119. How do you create a set in Python?


Code:

1
2 my_set = {1, 2, 3, 4}
3 print(my_set)
4

Hint: Use curly braces or the `set` constructor to create a set.

Riddle: I am a collection of unique items with no duplicates. What am I?

Short Story: Emma wanted to create a collection of unique items. By using curly braces, she created a set with distinct elements.

120. How do you add an element to a set?


Code:

1
2 my_set = {1, 2, 3}
3 my_set.add(4)
4 print(my_set)
5

Hint: Use the `add` method to insert a new element into a set.

Riddle: I assist you in including a new item into a collection of unique elements. What am I?

Short Story: Sarah needed to add a new element to her set. By using the `add` method, she successfully included the item in her collection of unique
elements.

121. How do you remove an element from a set?


Code:

1
2 my_set = {1, 2, 3, 4}
3 my_set.remove(3)
4 print(my_set)
5

Hint: Use the `remove` method to delete an element from a set.

Riddle: I assist you in removing an item from a collection of unique elements. What am I?

Short Story: Emma needed to remove a specific number from her set. By using the `remove` method, she successfully deleted the item from her collection.
122. How do you check if an element exists in a set?
Code:

1
2 my_set = {1, 2, 3, 4}
3 exists = 3 in my_set
4 print(exists)
5

Hint: Use the `in` operator to check for the presence of an element in a set.

Riddle: I help you verify whether a specific item is part of a collection of unique elements. What am I?

Short Story: Michael needed to confirm if a particular number was in his set. By using the `in` operator, he checked the presence of the item efficiently.

123. How do you get the length of a set?


Code:

1
2 my_set = {1, 2, 3, 4}
3 length = len(my_set)
4 print(length)
5

Hint: Use the `len` function to find the number of elements in a set.

Riddle: I help you determine the number of unique items in a collection. What am I?

Short Story: Sarah wanted to find out how many elements were in her set. By using the `len` function, she quickly obtained the count of unique items.

124. How do you clear all elements from a set?


Code:

1
2 my_set = {1, 2, 3, 4}
3 my_set.clear()
4 print(my_set)
5

Hint: Use the `clear` method to remove all elements from a set.

Riddle: I assist you in emptying a collection of unique items. What am I?

Short Story: Emma needed to remove all elements from her set. By using the `clear` method, she emptied the collection completely.

125. How do you find the intersection of two sets?


Code:

1
2 set1 = {1, 2, 3}
3 set2 = {2, 3, 4}
4 intersection = set1 & set2
5 print(intersection)
6

Hint: Use the `&` operator to find common elements between two sets.

Riddle: I help you find the shared items between two collections of unique elements. What am I?

Short Story: Michael wanted to identify common elements between two sets. By using the `&` operator, he successfully found the intersection of the sets.
126. How do you find the union of two sets?
Code:

1
2 set1 = {1, 2, 3}
3 set2 = {2, 3, 4}
4 union = set1 | set2
5 print(union)
6

Hint: Use the `|` operator to combine all elements from two sets.

Riddle: I help you combine all items from two collections of unique elements. What am I?

Short Story: Sarah needed to merge two sets into one. By using the `|` operator, she combined all unique items from both sets.

127. How do you find the difference between two sets?


Code:

1
2 set1 = {1, 2, 3}
3 set2 = {2, 3, 4}
4 difference = set1 - set2
5 print(difference)
6

Hint: Use the `-` operator to find elements that are in one set but not in the other.

Riddle: I help you identify items present in one collection but absent in another. What am I?

Short Story: Michael wanted to find elements unique to one set compared to another. By using the `-` operator, he determined the difference between the two
sets.

128. How do you find the symmetric difference between two sets?
Code:

1
2 set1 = {1, 2, 3}
3 set2 = {2, 3, 4}
4 symmetric_difference = set1 ^ set2
5 print(symmetric_difference)
6

Hint: Use the `^` operator to find elements that are in either of the sets but not in both.

Riddle: I help you find items that are unique to each of two collections, excluding those that are common. What am I?

Short Story: Emma needed to identify elements that were unique to each of two sets. By using the `^` operator, she successfully found the symmetric
difference between them.

129. How do you create a set from a list?


Code:

1
2 my_list = [1, 2, 2, 3, 4]
3 my_set = set(my_list)
4 print(my_set)
5

Hint: Use the `set` constructor to convert a list into a set.


Riddle: I help you eliminate duplicates and create a collection of unique items from a list. What am I?

Short Story: Sarah wanted to convert her list into a set to remove duplicates. By using the `set` constructor, she successfully created a set from the list.

130. How do you check if a set is a subset of another set?


Code:

1
2 set1 = {1, 2}
3 set2 = {1, 2, 3, 4}
4 is_subset = [Link](set2)
5 print(is_subset)
6

Hint: Use the `issubset` method to check if all elements of one set are contained in another.

Riddle: I help you determine if all items from one collection are included in another. What am I?

Short Story: Michael needed to verify if one set was completely contained within another. By using the `issubset` method, he efficiently performed the
check.

131. How do you convert a string to an integer?


Code:

1
2 number_str = "42"
3 number_int = int(number_str)
4 print(number_int)
5

Hint: Use the `int()` function to convert a string to an integer.

Riddle: I transform a sequence of characters into a whole number. What am I?

Short Story: Jane had a string representing a number and needed to perform arithmetic operations. She used the `int()` function to convert the string to an
integer.

132. What is the result of dividing an integer by a float in Python?


Code:

1
2 result = 5 // 2.0
3 print(result)
4

Hint: Integer division with a float results in a float.

Riddle: When dividing a whole number by a decimal, what type of result do you get?

Short Story: Michael was curious about the result of dividing an integer by a float. He found that the result was a float, even though he started with an
integer.

133. How do you create a list of squares of numbers from 1 to 10?


Code:
1
2 squares = [x**2 for x in range(1, 11)]
3 print(squares)
4

Hint: Use list comprehension to generate a list of squares.

Riddle: I help you generate a list where each item is the square of numbers in a range. What am I?

Short Story: Sarah wanted to create a list of squares for a math problem. By using list comprehension, she quickly generated the list.

134. How do you use the modulus operator in Python?


Code:

1
2 remainder = 10 % 3
3 print(remainder)
4

Hint: Use the `%` operator to find the remainder of a division.

Riddle: I give you the leftover part after dividing two numbers. What am I?

Short Story: Emma wanted to find out the remainder of a division. She used the modulus operator to get the result.

135. How do you use the power operator in Python?


Code:

1
2 power = 2 ** 3
3 print(power)
4

Hint: Use the `**` operator to raise a number to a power.

Riddle: I help you raise a number to an exponent. What am I?

Short Story: Michael needed to compute powers for a calculation. By using the `**` operator, he obtained the desired result.

136. How do you concatenate two strings in Python?


Code:

1
2 str1 = "Hello"
3 str2 = "World"
4 result = str1 + " " + str2
5 print(result)
6

Hint: Use the `+` operator to join two strings together.

Riddle: I help you join two sequences of characters into one. What am I?

Short Story: Sarah wanted to combine two words into a greeting. She used the `+` operator to concatenate the strings.
137. How do you find the length of a list in Python?
Code:

1
2 my_list = [1, 2, 3, 4]
3 length = len(my_list)
4 print(length)
5

Hint: Use the `len()` function to get the number of items in a list.

Riddle: I help you count the number of items in a collection. What am I?

Short Story: Emma needed to determine how many items were in her list. By using the `len()` function, she got the count.

Control Structures

138. How do you use an `if` statement to check if a number is positive?


Code:

1
2 number = 10
3 if number > 0:
4 print("Positive")
5 else:
6 print("Not Positive")
7

Hint: Use the `if` keyword to perform a check and the `else` keyword to handle other cases.

Riddle: I help you decide actions based on a condition. What am I?

Short Story: Michael wanted to classify a number as positive or not. By using an `if` statement, he was able to check the condition and print the result.

139. How do you use an `if-else` statement to determine if a number is even or odd?
Code:

1
2 number = 7
3 if number % 2 == 0:
4 print("Even")
5 else:
6 print("Odd")
7

Hint: Use the modulus operator `%` to check for even or odd numbers.

Riddle: I help you figure out whether a number is divisible by 2 without a remainder. What am I?

Short Story: Sarah wanted to determine if a number was even or odd. By using an `if-else` statement and the modulus operator, she got the result.

140. How do you use a `for` loop to iterate over a list?


Code:

1
2 my_list = [1, 2, 3, 4]
3 for item in my_list:
4 print(item)
5
Hint: Use the `for` keyword to loop over each item in a list.

Riddle: I help you process each item in a collection one by one. What am I?

Short Story: Emma needed to print each item in a list. By using a `for` loop, she efficiently iterated over the list.

141. How do you use a `while` loop to print numbers from 1 to 5?


Code:

1
2 number = 1
3 while number <= 5:
4 print(number)
5 number += 1
6

Hint: Use the `while` keyword to repeat actions while a condition is true.

Riddle: I keep repeating an action until a condition is no longer met. What am I?

Short Story: Michael wanted to print numbers from 1 to 5. By using a `while` loop, he achieved this task with ease.

142. How do you handle errors using `try` and `except`?


Code:

1
2 try:
3 result = 10 / 0
4 except ZeroDivisionError:
5 print("You can't divide by zero!")
6

Hint: Use `try` to attempt a block of code and `except` to handle specific errors.

Riddle: I help you manage exceptions and errors in your code gracefully. What am I?

Short Story: Sarah needed to handle a division by zero error. By using `try` and `except`, she managed to handle the error without crashing her program.

143. How do you use `finally` to ensure code executes regardless of an error?
Code:

1
2 try:
3 file = open("[Link]", "r")
4 content = [Link]()
5 finally:
6 [Link]()
7 print("File closed.")
8

Hint: Use `finally` to ensure code runs after `try` and `except` blocks, regardless of whether an exception was raised.

Riddle: I ensure that certain code runs whether an exception occurs or not. What am I?

Short Story: Michael wanted to make sure a file was closed properly regardless of whether an error occurred. He used `finally` to ensure the file was closed.
Functions and Modules

144. How do you define a function in Python?


Code:

1
2 def greet(name):
3 return f"Hello, {name}!"
4
5 print(greet("Alice"))
6

Hint: Use the `def` keyword to define a function.

Riddle: I help you group a set of statements under a name to perform a task. What am I?

Short Story: Sarah wanted to create a reusable block of code to greet users. By defining a function, she was able to achieve this efficiently.

145. How do you return multiple values from a function?


Code:

1
2 def min_max(numbers):
3 return min(numbers), max(numbers)
4
5 result = min_max([1, 2, 3, 4, 5])
6 print(result)
7

Hint: Use a tuple to return multiple values from a function.

Riddle: I allow you to return more than one value from a function. What am I?

Short Story: Michael needed to get both the minimum and maximum values from a list. By returning a tuple from his function, he obtained both values.

146. How do you use default arguments in a function?


Code:

1
2 def greet(name, greeting="Hello"):
3 return f"{greeting}, {name}!"
4
5 print(greet("Alice"))
6 print(greet("Bob", "Hi"))
7

Hint: Set default values for function arguments to make them optional.

Riddle: I allow you to provide optional values for function parameters. What am I?

Short Story: Emma wanted to have a default greeting message but also allow custom messages. By using default arguments, she achieved this flexibility.

147. How do you use keyword arguments in a function?


Code:
1
2 def introduce(name, age):
3 return f"My name is {name} and I am {age} years old."
4
5 print(introduce(age=25, name="Alice"))
6

Hint: Use keyword arguments to specify which parameter you are providing a value for.

Riddle: I allow you to specify arguments by their names in a function call. What am I?

Short Story: Michael wanted to specify arguments in any order when calling his function. By using keyword arguments, he made his code more readable and
flexible.

148. How do you import a module in Python?


Code:

1
2 import math
3
4 print([Link](16))
5

Hint: Use the `import` keyword to include a module in your code.

Riddle: I help you bring in external code libraries into your program. What am I?

Short Story: Sarah needed to use mathematical functions in her program. She imported the `math` module and utilized its functions effectively.

149. How do you create your own module in Python?


Code:

1
2 # my_module.py
3 def add(a, b):
4 return a + b
5
6 # [Link]
7 import my_module
8
9 result = my_module.add(2, 3)
10 print(result)
11

Hint: Save your functions in a `.py` file and import it using the `import` keyword.

Riddle: I allow you to create reusable code that can be imported into other scripts. What am I?

Short Story: Michael wanted to organize his functions into a reusable module. He created a file with his functions and imported it into his main script.

Advanced Topics

150. How do you define a class in Python?


Code:
1
2 class Dog:
3 def __init__(self, name):
4 [Link] = name
5
6 def bark(self):
7 return f"{[Link]} says Woof!"
8
9 dog = Dog("Buddy")
10 print([Link]())
11

Hint: Use the `class` keyword to define a new class and `__init__` to initialize attributes.

Riddle: I help you create new types that bundle data and behavior. What am I?

Short Story: Sarah wanted to model a real-world entity in code. By defining a class, she was able to create a blueprint for her objects.

151. How do you inherit from a parent class in Python?


Code:

1
2 class Animal:
3 def speak(self):
4 return "Animal sound"
5
6 class Cat(Animal):
7 def meow(self):
8 return "Meow!"
9
10 cat = Cat()
11 print([Link]())
12 print([Link]())
13

Hint: Use parentheses to specify the parent class when defining a subclass.

Riddle: I allow a class to inherit attributes and methods from another class. What am I?

Short Story: Michael wanted his `Cat` class to reuse functionality from the `Animal` class. By inheriting from `Animal`, he achieved this efficiently.

152. How do you read from a file in Python?


Code:

1
2 with open("[Link]", "r") as file:
3 content = [Link]()
4 print(content)
5

Hint: Use the `open` function with the `'r'` mode to read from a file.

Riddle: I allow you to access the contents of a file for reading. What am I?

Short Story: Sarah needed to read the contents of a file. By using the `open` function, she was able to access and print the file's contents.

153. How do you write to a file in Python?


Code:
1
2 with open("[Link]", "w") as file:
3 [Link]("Hello, World!")
4

Hint: Use the `open` function with the `'w'` mode to write to a file.

Riddle: I allow you to save data to a file. What am I?

Short Story: Michael wanted to save some text to a file. By using the `open` function with write mode, he was able to write the text to the file.

154. How do you install and use third-party libraries in Python?


Code:

1
2 # Install with pip
3 # pip install requests
4
5 import requests
6
7 response = [Link]("[Link]
8 print([Link]())
9

Hint: Use `pip` to install libraries and `import` to include them in your code.

Riddle: I help you include and use external libraries in your project. What am I?

Short Story: Sarah needed to make HTTP requests in her program. She installed the `requests` library using `pip` and used it to fetch data from an API.

Data Management

155. How do you connect to a SQLite database in Python?


Code:

1
2 import sqlite3
3
4 connection = [Link]("[Link]")
5 cursor = [Link]()
6 [Link]("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
7 [Link]()
8 [Link]()
9

Hint: Use the `sqlite3` module to connect and interact with a SQLite database.

Riddle: I help you connect to and interact with a SQLite database. What am I?

Short Story: Sarah wanted to create a SQLite database. She used the `sqlite3` module to connect to the database and create a table.

156. How do you execute a SQL query using Python?


Code:
1
2 import sqlite3
3
4 connection = [Link]("[Link]")
5 cursor = [Link]()
6 [Link]("INSERT INTO users (name) VALUES ('Alice')")
7 [Link]()
8 [Link]()
9

Hint: Use a cursor object to execute SQL queries and commit changes.

Riddle: I help you run SQL commands to interact with a database. What am I?

Short Story: Michael needed to insert data into his database. He used a cursor object to execute an SQL query and committed the changes.

157. What is the SQL command to select all columns from a table?
Code:

1
2 SELECT * FROM users;
3

Hint: Use the `SELECT` keyword followed by `*` to select all columns.

Riddle: I help you retrieve all columns from a table in SQL. What am I?

Short Story: Sarah wanted to see all the data in her `users` table. She used the `SELECT *` command to retrieve all columns.

158. How do you filter records in SQL using a `WHERE` clause?


Code:

1
2 SELECT * FROM users WHERE name = 'Alice';
3

Hint: Use the `WHERE` clause to specify conditions for filtering records.

Riddle: I help you filter records based on a condition in SQL. What am I?

Short Story: Michael needed to find records where the name was 'Alice'. He used the `WHERE` clause to filter the results.

159. How do you load a CSV file into a Pandas DataFrame?


Code:

1
2 import pandas as pd
3
4 df = pd.read_csv("[Link]")
5 print([Link]())
6

Hint: Use the `pd.read_csv` function to load a CSV file into a DataFrame.

Riddle: I help you read CSV files into a structured DataFrame for analysis. What am I?

Short Story: Sarah needed to analyze data from a CSV file. She used Pandas to load the file into a DataFrame and inspected the first few rows.
160. How do you calculate the mean of a column in a Pandas DataFrame?
Code:

1
2 import pandas as pd
3
4 df = pd.read_csv("[Link]")
5 mean_value = df['column_name'].mean()
6 print(mean_value)
7

Hint: Use the `mean` method on a DataFrame column to calculate the average value.

Riddle: I help you find the average value of a column in a DataFrame. What am I?

Short Story: Michael wanted to find the average value of a specific column in his DataFrame. By using the `mean` method, he calculated the average easily.

Web Development

161. How do you create a simple Flask application?


Code:

1
2 from flask import Flask
3
4 app = Flask(__name__)
5
6 @[Link]('/')
7 def hello_world():
8 return "Hello, World!"
9
10 if __name__ == '__main__':
11 [Link]()
12

Hint: Use Flask's `Flask` class to create an application instance and define routes with the `@[Link]` decorator.

Riddle: I help you create a basic web application with Flask. What am I?

Short Story: Sarah wanted to build a web application. By creating a simple Flask app, she was able to serve "Hello, World!" at the root URL.

162. How do you add a new route in Flask?


Code:

1
2 from flask import Flask
3
4 app = Flask(__name__)
5
6 @[Link]('/')
7 def home():
8 return "Home Page"
9
10 @[Link]('/about')
11 def about():
12 return "About Page"
13
14 if __name__ == '__main__':
15 [Link]()
16

Hint: Use the `@[Link]` decorator to add new routes and define their corresponding view functions.

Riddle: I allow you to define multiple endpoints in a Flask application. What am I?


Short Story: Michael needed to create multiple pages for his Flask app. By adding new routes, he was able to handle different URLs and return different
content.

Variables and Data Types

165. What are the basic data types in Python?


Code:

1
2 # Basic data types in Python
3 integer = 42
4 floating_point = 3.14
5 string = "Hello, World!"
6 boolean = True
7
8 print(type(integer))
9 print(type(floating_point))
10 print(type(string))
11 print(type(boolean))
12

Hint: Common data types include integers, floating points, strings, and booleans.

Riddle: I represent numbers, text, and truth values in Python. What am I?

Short Story: Sarah was learning about Python's data types. She found that integers, floats, strings, and booleans were essential for her programs.

166. How do you convert a string to an integer in Python?


Code:

1
2 string_number = "123"
3 integer_number = int(string_number)
4 print(integer_number)
5

Hint: Use the `int()` function to convert a string to an integer.

Riddle: I help you transform a string of digits into a number. What am I?

Short Story: Michael needed to perform mathematical operations on a number stored as a string. By converting it to an integer, he could do calculations
easily.

Operators

167. What is the result of using the `+` operator with strings?
Code:

1
2 string1 = "Hello, "
3 string2 = "World!"
4 result = string1 + string2
5 print(result)
6

Hint: The `+` operator concatenates strings.

Riddle: I join two strings into one. What am I?

Short Story: Sarah wanted to create a welcoming message. By using the `+` operator, she concatenated "Hello, " and "World!" into a single message.
168. How do you find the length of a list in Python?
Code:

1
2 my_list = [1, 2, 3, 4, 5]
3 length = len(my_list)
4 print(length)
5

Hint: Use the `len()` function to find the length of a list.

Riddle: I tell you how many items are in a list. What am I?

Short Story: Michael needed to know how many elements were in his list. By using `len()`, he quickly found the number of items.

Strings and Lists

169. How do you access the first character of a string in Python?


Code:

1
2 my_string = "Python"
3 first_char = my_string[0]
4 print(first_char)
5

Hint: Use indexing to access characters in a string.

Riddle: I allow you to retrieve the character at a specific position in a string. What am I?

Short Story: Sarah needed the first letter of the word "Python". By indexing the string with `[0]`, she accessed the first character efficiently.

170. How do you create a list of the first 10 even numbers?


Code:

1
2 even_numbers = [i for i in range(0, 20, 2)]
3 print(even_numbers)
4

Hint: Use list comprehension to generate a list of even numbers.

Riddle: I help you generate a sequence of even numbers. What am I?

Short Story: Michael wanted a list of even numbers. By using list comprehension, he quickly generated the first 10 even numbers in a concise manner.

Conditional Statements

171. How do you write an `if` statement in Python?


Code:

1
2 x = 10
3 if x > 5:
4 print("x is greater than 5")
5 else:
6 print("x is 5 or less")
7

Hint: Use `if` followed by a condition to execute code based on that condition.
Riddle: I allow you to execute code only if a certain condition is true. What am I?

Short Story: Sarah wanted to print a message based on the value of `x`. By using an `if` statement, she checked if `x` was greater than 5 and printed the
appropriate message.

172. How do you write an `if-else` statement in Python?


Code:

1
2 y = 20
3 if y % 2 == 0:
4 print("y is even")
5 else:
6 print("y is odd")
7

Hint: Use `if-else` to handle two possible outcomes based on a condition.

Riddle: I help you choose between two paths based on a condition. What am I?

Short Story: Michael needed to determine if a number was even or odd. By using `if-else`, he was able to check the condition and print the result
accordingly.

Loops

173. How do you write a `for` loop in Python?


Code:

1
2 for i in range(5):
3 print(i)
4

Hint: Use `for` followed by a variable and an iterable to repeat code a specified number of times.

Riddle: I help you repeat a block of code multiple times. What am I?

Short Story: Sarah wanted to print numbers from 0 to 4. By using a `for` loop, she iterated through a range of numbers and printed each one.

174. How do you write a `while` loop in Python?


Code:

1
2 count = 0
3 while count < 5:
4 print(count)
5 count += 1
6

Hint: Use `while` followed by a condition to repeat code until the condition becomes false.

Riddle: I allow you to execute code as long as a condition remains true. What am I?

Short Story: Michael needed to print numbers from 0 to 4 using a condition. By using a `while` loop, he was able to repeatedly print and increment the count
until it reached 5.
Error Handling

175. How do you handle exceptions in Python?


Code:

1
2 try:
3 x = 1 / 0
4 except ZeroDivisionError:
5 print("You can't divide by zero!")
6 finally:
7 print("This will execute no matter what.")
8

Hint: Use `try`, `except`, and optionally `finally` to handle exceptions.

Riddle: I help you manage errors and ensure that some code always runs. What am I?

Short Story: Sarah was worried about a division by zero error. By using `try-except`, she was able to catch the error and provide a meaningful message,
while `finally` ensured some code always executed.

Functions and Modules

176. How do you define a function in Python?


Code:

1
2 def greet(name):
3 return f"Hello, {name}!"
4
5 print(greet("Alice"))
6

Hint: Use the `def` keyword to define a function and specify its parameters.

Riddle: I allow you to create reusable blocks of code that perform specific tasks. What am I?

Short Story: Michael wanted to greet users by name. By defining a `greet` function, he was able to reuse the greeting code and pass different names.

177. How do you import a module in Python?


Code:

1
2 import math
3
4 print([Link](16))
5

Hint: Use the `import` statement to bring in external modules.

Riddle: I let you use code from other files and libraries. What am I?

Short Story: Sarah wanted to use mathematical functions from a module. By using `import math`, she accessed functions like `sqrt` to perform calculations.
Object-Oriented Programming

178. How do you define a class in Python?


Code:

1
2 class Dog:
3 def __init__(self, name):
4 [Link] = name
5
6 def bark(self):
7 return f"{[Link]} says Woof!"
8
9 my_dog = Dog("Rex")
10 print(my_dog.bark())
11

Hint: Use the `class` keyword to define a class and `def` to define methods.

Riddle: I help you create objects and organize code into reusable blueprints. What am I?

Short Story: Michael wanted to model a dog. By defining a `Dog` class, he created a blueprint with attributes and methods to represent a dog in his program.

179. How do you create an instance of a class in Python?


Code:

1
2 class Car:
3 def __init__(self, model):
4 [Link] = model
5
6 my_car = Car("Toyota")
7 print(my_car.model)
8

Hint: Call the class name with arguments to create an instance.

Riddle: I represent a specific object created from a class. What am I?

Short Story: Sarah needed a specific car object. By creating an instance of the `Car` class, she instantiated a `Toyota` car with its own model attribute.

File Handling

180. How do you read a file in Python?


Code:

1
2 with open('[Link]', 'r') as file:
3 content = [Link]()
4 print(content)
5

Hint: Use the `open()` function with the `'r'` mode to read a file.

Riddle: I let you access the contents of a file for reading. What am I?

Short Story: Michael needed to read from a file. By using `open('[Link]', 'r')`, he was able to read the file's contents and print them to the console.
181. How do you write to a file in Python?
Code:

1
2 with open('[Link]', 'w') as file:
3 [Link]("Hello, World!")
4

Hint: Use the `open()` function with the `'w'` mode to write to a file.

Riddle: I help you save data to a file. What am I?

Short Story: Sarah needed to save some text to a file. By using `open('[Link]', 'w')`, she wrote "Hello, World!" into the file, creating or overwriting it.

Introduction to Databases

182. What is a database in Python?


Code:

1
2 import sqlite3
3
4 # Connect to a database (or create it if it doesn't exist)
5 connection = [Link]('[Link]')
6 cursor = [Link]()
7
8 # Create a table
9 [Link]('''
10 CREATE TABLE IF NOT EXISTS users (
11 id INTEGER PRIMARY KEY,
12 name TEXT
13 )
14 ''')
15
16 # Commit and close
17 [Link]()
18 [Link]()
19

Hint: Use SQLite for simple database tasks in Python.

Riddle: I store data in a structured way and allow you to perform queries. What am I?

Short Story: Michael wanted to store user information. By using SQLite, he created a database and a table to keep track of users in his application.

183. How do you perform a simple SQL query in Python?


Code:

1
2 import sqlite3
3
4 # Connect to the database
5 connection = [Link]('[Link]')
6 cursor = [Link]()
7
8 # Insert a record
9 [Link]("INSERT INTO users (name) VALUES ('Alice')")
10
11 # Query the records
12 [Link]("SELECT * FROM users")
13 rows = [Link]()
14 for row in rows:
15 print(row)
16
17 # Commit and close
18 [Link]()
19 [Link]()
20

Hint: Use `execute()` to perform SQL queries and `fetchall()` to retrieve results.

Riddle: I help you interact with a database using SQL commands. What am I?

Short Story: Sarah wanted to add and retrieve user records. By executing SQL queries with SQLite, she inserted a record and retrieved all users from the
database.

Control Structures

184. How do you use `if` statements in Python?


Code:

1
2 x = 10
3
4 if x > 5:
5 print("x is greater than 5")
6 elif x == 5:
7 print("x is equal to 5")
8 else:
9 print("x is less than 5")
10

Hint: Use `if`, `elif`, and `else` to handle multiple conditions.

Riddle: I help you make decisions in your code based on conditions. What am I?

Short Story: Sarah wanted to check if a number was greater than, equal to, or less than 5. By using `if` statements, she could handle each case appropriately.

185. How do you use `for` loops in Python?


Code:

1
2 for i in range(5):
3 print(i)
4

Hint: Use `for` to iterate over a sequence of elements.

Riddle: I allow you to iterate over a sequence and execute code multiple times. What am I?

Short Story: Michael needed to print numbers from 0 to 4. By using a `for` loop with `range`, he could efficiently iterate through the numbers and print
them.

186. How do you handle errors using `try-except`?


Code:

1
2 try:
3 result = 10 / 0
4 except ZeroDivisionError:
5 print("Cannot divide by zero!")
6

Hint: Use `try` to execute code that may cause an error and `except` to handle specific errors.

Riddle: I help you catch and manage errors that occur during program execution. What am I?
Short Story: Sarah wanted to prevent her program from crashing when dividing by zero. By using `try-except`, she caught the error and displayed a user-
friendly message.

Functions and Modules

187. How do you pass arguments to a function in Python?


Code:

1
2 def add(a, b):
3 return a + b
4
5 result = add(3, 4)
6 print(result)
7

Hint: Define parameters in the function definition and provide arguments when calling the function.

Riddle: I allow you to send values into a function for it to work with. What am I?

Short Story: Michael wanted to add two numbers. By defining a function `add` that accepts parameters `a` and `b`, he was able to pass values and get the
sum.

188. How do you use modules in Python?


Code:

1
2 import math
3
4 print([Link])
5 print([Link](25))
6

Hint: Import modules using the `import` statement to use their functions and variables.

Riddle: I allow you to use code from external files and libraries. What am I?

Short Story: Sarah wanted to use mathematical functions in her program. By importing the `math` module, she could access constants like `pi` and functions
like `sqrt`.

Object-Oriented Programming

189. How do you define a class in Python with attributes?


Code:

1
2 class Person:
3 def __init__(self, name, age):
4 [Link] = name
5 [Link] = age
6
7 person1 = Person("Alice", 30)
8 print([Link])
9 print([Link])
10

Hint: Define attributes in the `__init__` method and use `self` to refer to them.

Riddle: I help you define a blueprint with characteristics for objects. What am I?

Short Story: Michael wanted to create person objects with specific attributes. By defining a `Person` class with `name` and `age` attributes, he instantiated
and accessed the details of the person objects.
190. How do you create a method within a class in Python?
Code:

1
2 class Car:
3 def __init__(self, make, model):
4 [Link] = make
5 [Link] = model
6
7 def display_info(self):
8 return f"Car: {[Link]} {[Link]}"
9
10 my_car = Car("Toyota", "Camry")
11 print(my_car.display_info())
12

Hint: Define methods within the class using `def` and use `self` to access attributes.

Riddle: I allow you to define functions that belong to a class and operate on its attributes. What am I?

Short Story: Sarah wanted her car objects to display their details. By creating a `display_info` method in the `Car` class, she enabled each car object to show
its make and model.

File Handling

191. How do you handle file paths in Python?


Code:

1
2 import os
3
4 # Get the absolute path
5 abs_path = [Link]('[Link]')
6 print(abs_path)
7

Hint: Use the `[Link]` module to handle file paths and directories.

Riddle: I help you work with file paths and directories. What am I?

Short Story: Michael needed to find the absolute path of a file. By using the `[Link]` function, he retrieved the full path to `[Link]`.

192. How do you read a file line by line in Python?


Code:

1
2 with open('[Link]', 'r') as file:
3 for line in file:
4 print([Link]())
5

Hint: Use a `with` statement to open the file and a `for` loop to iterate through lines.

Riddle: I help you read each line of a file without loading the entire file into memory. What am I?

Short Story: Sarah needed to process a large file line by line. By using a `with` statement and `for` loop, she efficiently read and processed each line from
`[Link]`.
Introduction to Databases

193. How do you connect to a SQLite database in Python?


Code:

1
2 import sqlite3
3
4 connection = [Link]('[Link]')
5 cursor = [Link]()
6

Hint: Use `[Link]` to connect to a database file.

Riddle: I allow you to establish a connection to a database for executing SQL queries. What am I?

Short Story: Michael needed to interact with a SQLite database. By using `[Link]`, he connected to `[Link]` and prepared to execute SQL
queries.

194. How do you create a table in a SQLite database?


Code:

1
2 import sqlite3
3
4 connection = [Link]('[Link]')
5 cursor = [Link]()
6
7 [Link]('''
8 CREATE TABLE users (
9 id INTEGER PRIMARY KEY,
10 username TEXT,
11 email TEXT
12 )
13 ''')
14
15 [Link]()
16 [Link]()
17

Hint: Use the `CREATE TABLE` SQL statement to define the table structure.

Riddle: I help you define the structure of data in a database. What am I?

Short Story: Sarah wanted to set up a new table in her database to store user information. By executing the `CREATE TABLE` statement, she established a
`users` table with `id`, `username`, and `email` columns.

SQL Basics

195. How do you insert data into a SQLite table?


Code:

1
2 import sqlite3
3
4 connection = [Link]('[Link]')
5 cursor = [Link]()
6
7 [Link]('''
8 INSERT INTO users (username, email)
9 VALUES ('johndoe', 'johndoe@[Link]')
10 ''')
11
12 [Link]()
13 [Link]()
14

Hint: Use the `INSERT INTO` SQL statement to add new records to a table.

Riddle: I allow you to add new rows of data to a table in your database. What am I?

Short Story: Michael needed to add a new user record to the `users` table. By executing the `INSERT INTO` statement, he added `johndoe` with an email
address to the table.

196. How do you query data from a SQLite table?


Code:

1
2 import sqlite3
3
4 connection = [Link]('[Link]')
5 cursor = [Link]()
6
7 [Link]('SELECT * FROM users')
8 rows = [Link]()
9
10 for row in rows:
11 print(row)
12
13 [Link]()
14

Hint: Use the `SELECT` SQL statement to retrieve data from a table.

Riddle: I allow you to retrieve specific data from a database table. What am I?

Short Story: Sarah wanted to view all the records in the `users` table. By executing a `SELECT *` query, she retrieved and printed all user data from the
table.

Data Analysis with Pandas

197. How do you read a CSV file into a Pandas DataFrame?


Code:

1
2 import pandas as pd
3
4 df = pd.read_csv('[Link]')
5 print([Link]())
6

Hint: Use the `pd.read_csv` function to load CSV data into a DataFrame.

Riddle: I help you load and analyze tabular data from CSV files. What am I?

Short Story: Michael needed to analyze data from a CSV file. By using `pd.read_csv`, he loaded the data into a Pandas DataFrame and displayed the first
few rows.

198. How do you filter data in a Pandas DataFrame?


Code:
1
2 import pandas as pd
3
4 df = pd.read_csv('[Link]')
5 filtered_df = df[df['age'] > 30]
6 print(filtered_df)
7

Hint: Use conditional statements to filter rows in a DataFrame.

Riddle: I help you extract specific rows of data based on conditions. What am I?

Short Story: Sarah wanted to filter out users older than 30 from her dataset. By applying a condition on the `age` column, she retrieved the relevant records
from the DataFrame.

Introduction to Web Frameworks

199. What is Flask used for in web development?


Code:

1
2 from flask import Flask
3
4 app = Flask(__name__)
5
6 @[Link]('/')
7 def home():
8 return "Hello, Flask!"
9
10 if __name__ == '__main__':
11 [Link]()
12

Hint: Flask is a micro web framework for building web applications in Python.

Riddle: I help you create web applications with ease and flexibility. What am I?

Short Story: Michael wanted to create a simple web application. By using Flask, he set up a basic web server and defined a route that returned a greeting
message.

200. How do you make a GET request to an API in Python?


Code:

1
2 import requests
3
4 response = [Link]('[Link]
5 data = [Link]()
6 print(data)
7

Hint: Use the `requests` library to make HTTP requests and handle responses.

Riddle: I allow you to fetch data from a web service using HTTP. What am I?

Short Story: Sarah needed to retrieve data from an online API. By using the `requests` library, she sent a GET request and processed the JSON response to
access the data.
Introduction to Web APIs

201. How do you post data to an API using Python?


Code:

1
2 import requests
3
4 data = {'key': 'value'}
5 response = [Link]('[Link] json=data)
6 print(response.status_code)
7 print([Link]())
8

Hint: Use the `[Link]` method to send data to an API endpoint.

Riddle: I help you send data to a web service for processing or storage. What am I?

Short Story: Sarah needed to send user data to a web service. By using `[Link]`, she sent the data in JSON format and checked the response from the
server.

202. How do you handle JSON data in Python?


Code:

1
2 import json
3
4 # Convert JSON string to Python dictionary
5 json_data = '{"name": "Alice", "age": 25}'
6 data = [Link](json_data)
7 print(data)
8
9 # Convert Python dictionary to JSON string
10 dict_data = {"name": "Bob", "age": 30}
11 json_string = [Link](dict_data)
12 print(json_string)
13

Hint: Use the `json` module to parse and generate JSON data.

Riddle: I allow you to convert between JSON strings and Python objects. What am I?

Short Story: Michael needed to work with JSON data in his application. By using the `json` module, he easily converted JSON strings to dictionaries and
vice versa.

Web Development Basics

203. What is a RESTful API?


Answer:

A RESTful API (Representational State Transfer) is a web service that uses HTTP requests to perform CRUD (Create, Read, Update, Delete) operations. It
typically uses JSON or XML to transmit data and adheres to principles such as statelessness, client-server architecture, and uniform interface.

Hint: RESTful APIs are commonly used for web services and applications to communicate over the internet.

Riddle: I enable communication between web services using standard HTTP methods and data formats. What am I?

Short Story: Sarah was developing a web service and chose to use a RESTful API. This allowed her application to interact with other services over HTTP,
using methods like GET and POST to manage resources.
204. How do you handle form data in a Flask web application?
Code:

1
2 from flask import Flask, request, render_template
3
4 app = Flask(__name__)
5
6 @[Link]('/submit', methods=['GET', 'POST'])
7 def submit():
8 if [Link] == 'POST':
9 name = [Link]['name']
10 email = [Link]['email']
11 return f"Name: {name}, Email: {email}"
12 return render_template('[Link]')
13
14 if __name__ == '__main__':
15 [Link]()
16

Hint: Use the `[Link]` object to access form data submitted via POST requests.

Riddle: I allow you to retrieve user input from HTML forms in a web application. What am I?

Short Story: Michael created a web form for user submissions. By using Flask’s `[Link]`, he accessed the submitted data and displayed it back to the
user.

Advanced Topics

205. How do you implement a class in Python?


Code:

1
2 class Person:
3 def __init__(self, name, age):
4 [Link] = name
5 [Link] = age
6
7 def greet(self):
8 return f"Hello, my name is {[Link]} and I am {[Link]} years old."
9
10 # Creating an instance of the Person class
11 person = Person('Alice', 30)
12 print([Link]())
13

Hint: Use the `class` keyword to define a class and the `__init__` method to initialize attributes.

Riddle: I allow you to create custom objects with attributes and methods. What am I?

Short Story: Sarah wanted to model real-world entities in her application. By defining a `Person` class, she created objects with `name` and `age` attributes
and a method to greet.

206. How do you handle exceptions in Python?


Code:

1
2 try:
3 result = 10 / 0
4 except ZeroDivisionError:
5 print("Cannot divide by zero!")
6 finally:
7 print("This will always execute.")
8
Hint: Use `try`, `except`, and `finally` blocks to manage exceptions and ensure code execution.

Riddle: I help you manage errors and ensure that cleanup code runs regardless of exceptions. What am I?

Short Story: Michael needed to handle a potential division by zero error. By using `try` and `except`, he managed the error gracefully and ensured that
certain code executed no matter what.

207. How do you work with environment variables in Python?


Code:

1
2 import os
3
4 # Get an environment variable
5 database_url = [Link]('DATABASE_URL', 'default_value')
6 print(f"Database URL: {database_url}")
7
8 # Set an environment variable
9 [Link]['NEW_VAR'] = 'some_value'
10

Hint: Use the `os` module to access and modify environment variables.

Riddle: I allow you to retrieve and set system-level configuration settings in your application. What am I?

Short Story: Sarah needed to configure her application with environment-specific settings. By using the `os` module, she accessed and set environment
variables for her application’s configuration.

208. How do you perform file I/O operations in Python?


Code:

1
2 # Writing to a file
3 with open('[Link]', 'w') as file:
4 [Link]('Hello, world!')
5
6 # Reading from a file
7 with open('[Link]', 'r') as file:
8 content = [Link]()
9 print(content)
10

Hint: Use the `open` function with modes like `'r'` and `'w'` to read and write files.

Riddle: I allow you to create and access files on your filesystem. What am I?

Short Story: Michael needed to read and write data to a file. Using Python’s file handling capabilities, he efficiently managed file operations with context
managers to ensure proper resource handling.

209. How do you connect to a database in Python?


Code:

1
2 import sqlite3
3
4 # Connect to a SQLite database
5 conn = [Link]('[Link]')
6 cursor = [Link]()
7
8 # Create a table
9 [Link]('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)''')
10
11 # Insert a record
12 [Link]('''INSERT INTO users (name) VALUES ('Alice')''')
13
14 # Commit the changes and close the connection
15 [Link]()
16 [Link]()
17

Hint: Use a database connector library such as `sqlite3` for SQLite databases or `psycopg2` for PostgreSQL.

Riddle: I help you manage data within a database, creating tables and performing operations. What am I?

Short Story: Sarah was developing an application that required database interaction. By using `sqlite3`, she created a table, inserted records, and managed
database operations efficiently.

Data Management

210. What is SQL and how is it used with Python?


Answer:

SQL (Structured Query Language) is a standard language for managing and manipulating databases. In Python, SQL can be used with libraries like `sqlite3`,
`SQLAlchemy`, and `pymysql` to interact with databases. SQL statements are used to query, insert, update, and delete data within a database.

Hint: Use database libraries in Python to execute SQL queries and handle database interactions.

Riddle: I help you interact with databases using a specific language for querying and manipulation. What am I?

Short Story: Sarah needed to retrieve and manage data in her application. By using SQL with Python libraries, she could execute queries and handle database
operations efficiently.

211. How do you use Pandas for data analysis in Python?


Code:

1
2 import pandas as pd
3
4 # Create a DataFrame
5 data = {'Name': ['Alice', 'Bob', 'Charlie'],
6 'Age': [25, 30, 35]}
7 df = [Link](data)
8
9 # Perform data analysis
10 print([Link]())
11 print(df['Name'])
12

Hint: Use the `pandas` library to create and manipulate DataFrames for data analysis.

Riddle: I allow you to work with data in tabular form and perform various data analysis operations. What am I?

Short Story: Michael needed to analyze data for his project. By using Pandas, he created DataFrames and performed statistical analysis to gain insights from
the data.

Web Development

212. What is Flask and how do you use it to create a web application?
Code:
1
2 from flask import Flask, render_template
3
4 app = Flask(__name__)
5
6 @[Link]('/')
7 def home():
8 return render_template('[Link]')
9
10 if __name__ == '__main__':
11 [Link]()
12

Hint: Flask is a micro web framework for Python. Use it to define routes and render templates for web applications.

Riddle: I am a lightweight web framework that helps you build web applications quickly and easily. What am I?

Short Story: Sarah decided to use Flask for her new web application. By defining routes and rendering HTML templates, she created a simple yet effective
web app.

213. How do you handle user authentication in Django?


Code:

1
2 from [Link] import authenticate, login
3 from [Link] import HttpResponse
4 from [Link] import render
5
6 def login_view(request):
7 if [Link] == 'POST':
8 username = [Link]['username']
9 password = [Link]['password']
10 user = authenticate(request, username=username, password=password)
11 if user is not None:
12 login(request, user)
13 return HttpResponse("Logged in successfully.")
14 else:
15 return HttpResponse("Invalid credentials.")
16 return render(request, '[Link]')
17

Hint: Use Django’s authentication system to manage user login and authentication.

Riddle: I help you manage user access and verify credentials in a web application. What am I?

Short Story: Michael needed to add user authentication to his Django application. By using Django’s built-in authentication system, he managed user login
and credential verification effectively.

214. How do you make a REST API request in Python using the `requests` library?
Code:

1
2 import requests
3
4 response = [Link]('[Link]
5 if response.status_code == 200:
6 data = [Link]()
7 print(data)
8 else:
9 print(f"Failed to retrieve data: {response.status_code}")
10

Hint: Use the `requests` library to send HTTP requests and handle API responses.

Riddle: I allow you to interact with web services and APIs by sending and receiving HTTP requests. What am I?
Short Story: Sarah needed to retrieve data from an external API for her application. By using the `requests` library, she made a GET request and processed
the response to get the data she needed.

215. What is the purpose of a virtual environment in Python?


Answer:

A virtual environment is a self-contained directory that contains a Python installation for a particular version of Python, along with several additional
packages. It allows you to manage dependencies for different projects separately and avoid conflicts between packages.

Hint: Use virtual environments to isolate project dependencies and manage package versions independently.

Riddle: I help you create isolated environments for Python projects to manage dependencies separately. What am I?

Short Story: Michael was working on multiple Python projects. By using virtual environments, he isolated dependencies for each project, preventing version
conflicts and ensuring consistent behavior across projects.

216. How do you use `pip` to install packages?


Code:

1
2 # Install a package
3 pip install requests
4
5 # Install packages from a requirements file
6 pip install -r [Link]
7

Hint: Use `pip` to manage Python packages and dependencies by installing them from the Python Package Index (PyPI) or from a requirements file.

Riddle: I am a package manager for Python that helps you install and manage libraries and dependencies. What am I?

Short Story: Sarah needed to add new libraries to her project. By using `pip`, she installed packages from PyPI and managed her project’s dependencies
efficiently.

217. How do you create a simple API with Flask?


Code:

1
2 from flask import Flask, jsonify
3
4 app = Flask(__name__)
5
6 @[Link]('/api/data')
7 def get_data():
8 return jsonify({'message': 'Hello, World!'})
9
10 if __name__ == '__main__':
11 [Link]()
12

Hint: Use Flask’s `jsonify` function to return JSON responses from your API endpoints.

Riddle: I allow you to create endpoints that provide data in JSON format through a web application framework. What am I?

Short Story: Michael wanted to build an API for his application. By using Flask, he created an endpoint that returned data in JSON format, making it easy to
integrate with other services.
218. How do you debug a Python application?
Answer:

To debug a Python application, you can use various tools and techniques, such as:

Using print statements to output variable values and track code execution.
Using the built-in `pdb` module to set breakpoints and step through code.
Using integrated development environment (IDE) debuggers for advanced debugging features.

Hint: Use debugging tools to inspect and troubleshoot issues in your code effectively.

Riddle: I help you examine and fix issues in your code by allowing you to step through execution and inspect variables. What am I?

Short Story: Sarah was struggling with bugs in her application. By using debugging tools and techniques, she was able to identify and fix issues, ensuring
her application ran smoothly.

Advanced Topics

219. What is Object-Oriented Programming (OOP) and how is it implemented in Python?


Answer:

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects," which can contain data in the form of fields (attributes)
and code in the form of procedures (methods). Python supports OOP through its class system. Classes are used to create objects, and you can define methods
and attributes within these classes.

Code:

1
2 class Animal:
3 def __init__(self, name):
4 [Link] = name
5
6 def speak(self):
7 return f"{[Link]} makes a sound"
8
9 class Dog(Animal):
10 def speak(self):
11 return f"{[Link]} barks"
12
13 dog = Dog("Rex")
14 print([Link]())
15

Hint: Use classes to define objects and inheritance to extend functionality in Python.

Riddle: I am a paradigm that uses classes and objects to organize code and manage complexity. What am I?

Short Story: Sarah was designing a simulation game and used OOP principles to create different types of animals, each with its own behaviors and attributes,
making her code more organized and modular.

220. How do you handle file operations in Python?


Code:

1
2 # Writing to a file
3 with open('[Link]', 'w') as file:
4 [Link]("Hello, world!")
5
6 # Reading from a file
7 with open('[Link]', 'r') as file:
8 content = [Link]()
9 print(content)
10

Hint: Use the `open` function with modes like `'w'` for writing and `'r'` for reading. Use context managers (`with` statement) to handle files safely.
Riddle: I help you create, read, and write files in your application. What am I?

Short Story: Michael needed to store user data in a file. By using Python’s file handling functions, he could easily write data to files and read it back when
needed.

221. How do you work with external libraries in Python?


Answer:

To work with external libraries in Python, you typically install them using a package manager like `pip`. After installation, you import and use these libraries
in your code. Libraries provide pre-written code to perform common tasks, which saves development time and effort.

Code:

1
2 # Install an external library using pip
3 # pip install requests
4
5 import requests
6
7 response = [Link]('[Link]
8 print(response.status_code)
9

Hint: Use `pip` to install libraries and `import` to use them in your Python code.

Riddle: I help you extend the functionality of Python by adding pre-built packages to your project. What am I?

Short Story: Sarah wanted to use a library to simplify her HTTP requests. By installing and importing the `requests` library, she could make API calls
effortlessly.

Data Management

222. How do you perform basic SQL queries using SQLite in Python?
Code:

1
2 import sqlite3
3
4 # Connect to a database (or create it if it doesn't exist)
5 conn = [Link]('[Link]')
6 cursor = [Link]()
7
8 # Create a table
9 [Link]('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)''')
10
11 # Insert a record
12 [Link]('''INSERT INTO users (name) VALUES ('Alice')''')
13
14 # Query records
15 [Link]('''SELECT * FROM users''')
16 rows = [Link]()
17 for row in rows:
18 print(row)
19
20 [Link]()
21 [Link]()
22

Hint: Use `sqlite3` to connect to an SQLite database, execute SQL commands, and manage data.

Riddle: I help you create and manage a lightweight database using SQL queries in Python. What am I?

Short Story: Michael needed a simple way to store and retrieve user information. By using SQLite with Python, he could manage data efficiently without
needing a full-fledged database system.
223. What are some common libraries used for data analysis in Python?
Answer:

Common libraries used for data analysis in Python include:

Pandas: Provides data structures and data analysis tools.


Numpy: Supports large, multi-dimensional arrays and matrices.
Matplotlib: Used for creating static, animated, and interactive visualizations.
Seaborn: Builds on Matplotlib and provides a high-level interface for drawing attractive statistical graphics.

Hint: Explore libraries like Pandas, Numpy, and Matplotlib for effective data analysis and visualization.

Riddle: I offer tools and libraries for handling data, performing numerical computations, and creating visualizations in Python. What am I?

Short Story: Sarah was analyzing a large dataset and used libraries like Pandas and Matplotlib to clean, process, and visualize the data, gaining valuable
insights quickly.

Web Development

224. How do you set up a basic Django project?


Code:

1
2 # Install Django
3 # pip install django
4
5 # Create a new Django project
6 django-admin startproject myproject
7
8 # Navigate into the project directory
9 cd myproject
10
11 # Start the development server
12 python [Link] runserver
13

Hint: Use Django’s command-line tools to create a project and start the development server.

Riddle: I help you set up a web project with a built-in development server and a structured directory for your code. What am I?

Short Story: Michael wanted to build a web application quickly. By setting up a Django project, he had a ready-to-use framework to start building his
application.

225. How do you make an API request using the `requests` library?
Code:

1
2 import requests
3
4 response = [Link]('[Link]
5 if response.status_code == 200:
6 data = [Link]()
7 print(data)
8 else:
9 print('Failed to retrieve data')
10

Hint: Use the `requests` library to send HTTP requests and handle responses.

Riddle: I enable you to fetch data from web services by sending HTTP requests and processing the responses in Python. What am I?

Short Story: Sarah needed to integrate her application with an external service. By using the `requests` library, she could easily make API requests and
handle the responses.
Data Management

226. How do you perform data analysis with Pandas?


Code:

1
2 import pandas as pd
3
4 # Load data from a CSV file
5 df = pd.read_csv('[Link]')
6
7 # Display the first few rows of the dataframe
8 print([Link]())
9
10 # Calculate basic statistics
11 print([Link]())
12
13 # Filter data based on a condition
14 filtered_df = df[df['column_name'] > value]
15 print(filtered_df)
16

Hint: Use Pandas functions like `read_csv`, `describe`, and filtering operations to analyze and manipulate data.

Riddle: I help you analyze and manipulate data efficiently using dataframes and series. What am I?

Short Story: Sarah used Pandas to analyze her sales data. By loading the data into a dataframe, she could easily compute statistics and filter the information
to gain insights.

227. What are SQL basics you need to know?


Answer:

Some SQL basics include:

SELECT: Retrieve data from a database.


INSERT: Add new records to a table.
UPDATE: Modify existing records.
DELETE: Remove records from a table.
JOIN: Combine data from multiple tables.
WHERE: Filter records based on conditions.

Hint: Familiarize yourself with basic SQL commands to interact with databases.

Riddle: I am a language used to manage and manipulate relational databases. What am I?

Short Story: Michael was learning to interact with databases and found that understanding SQL basics was crucial for querying and managing his data
effectively.

228. How do you connect to a SQL database using Python?


Code:

1
2 import sqlite3
3
4 # Connect to a SQLite database
5 conn = [Link]('[Link]')
6 cursor = [Link]()
7
8 # Execute a SQL command
9 [Link]('''SELECT * FROM users''')
10 rows = [Link]()
11 for row in rows:
12 print(row)
13
14 [Link]()
15

Hint: Use the `sqlite3` module to connect to SQLite databases and perform SQL operations.

Riddle: I enable Python to interact with SQL databases by establishing connections and executing queries. What am I?

Short Story: Sarah needed to connect her Python application to a SQLite database. By using the `sqlite3` module, she was able to query and manage her data
effectively.

Web Development

229. What is the purpose of web frameworks like Flask and Django?
Answer:

Web frameworks like Flask and Django are designed to simplify web development by providing tools and libraries for common tasks, such as routing,
handling requests, and interacting with databases. They help developers build web applications quickly and efficiently by offering a structured approach and
reusable components.

Hint: Use web frameworks to streamline the development of web applications and manage common tasks easily.

Riddle: I provide a set of tools and libraries to help you build web applications efficiently, handling tasks like routing and data management. What am I?

Short Story: Michael wanted to develop a web application but needed a structured approach. By choosing Flask for a lightweight solution and Django for a
more feature-rich framework, he could build his applications more efficiently.

230. How do you handle user authentication in a Flask application?


Code:

1
2 from flask import Flask, request, redirect, url_for, session
3 from [Link] import generate_password_hash, check_password_hash
4
5 app = Flask(__name__)
6 app.secret_key = 'your_secret_key'
7
8 # Dummy user database
9 users = {'user1': generate_password_hash('password123')}
10
11 @[Link]('/login', methods=['GET', 'POST'])
12 def login():
13 if [Link] == 'POST':
14 username = [Link]['username']
15 password = [Link]['password']
16 if username in users and check_password_hash(users[username], password):
17 session['user'] = username
18 return redirect(url_for('welcome'))
19 else:
20 return 'Invalid credentials'
21 return '''
22
23 Username:
24 Password:
25
26
27 '''
28
29 @[Link]('/welcome')
30 def welcome():
31 if 'user' in session:
32 return f'Welcome, {session["user"]}!'
33 return redirect(url_for('login'))
34
35 if __name__ == '__main__':
36 [Link]()
37
Hint: Use `[Link]` for hashing passwords and Flask’s session management for user authentication.

Riddle: I help you manage user sessions and secure authentication processes in your web application. What am I?

Short Story: Sarah was building a login system for her Flask application. By using session management and password hashing, she ensured that user
authentication was secure and efficient.

Data Management (Continued)

231. How do you perform basic SQL operations in a database?


Code:

1
2 import sqlite3
3
4 # Connect to a database
5 conn = [Link]('[Link]')
6 cursor = [Link]()
7
8 # Create a table
9 [Link]('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
10
11 # Insert a record
12 [Link]('''INSERT INTO users (name, age) VALUES (?, ?)''', ('Alice', 30))
13
14 # Query records
15 [Link]('''SELECT * FROM users''')
16 print([Link]())
17
18 # Update a record
19 [Link]('''UPDATE users SET age = ? WHERE name = ?''', (31, 'Alice'))
20
21 # Delete a record
22 [Link]('''DELETE FROM users WHERE name = ?''', ('Alice',))
23
24 [Link]()
25 [Link]()
26

Hint: Use SQL commands for creating tables, inserting, updating, and deleting records in a database.

Riddle: I allow you to manage and manipulate data in a relational database by performing operations such as creating, inserting, updating, and deleting. What
am I?

Short Story: Michael was working on a project that required a database. By performing basic SQL operations, he managed to create tables, insert records,
and handle data efficiently.

232. How do you handle errors in a Python program?


Code:

1
2 try:
3 # Code that might raise an exception
4 result = 10 / 0
5 except ZeroDivisionError:
6 print('Error: Division by zero is not allowed.')
7 except Exception as e:
8 print(f'An unexpected error occurred: {e}')
9 finally:
10 print('This block is always executed.')
11

Hint: Use `try`, `except`, and `finally` blocks to handle exceptions and ensure your program runs smoothly even when errors occur.

Riddle: I help you manage unexpected issues in your code by allowing you to catch and handle exceptions gracefully. What am I?
Short Story: Sarah's application crashed due to a division by zero error. By implementing error handling with `try` and `except`, she ensured her program
could handle such issues without crashing.

Functions and Modules

233. How do you define a function in Python?


Code:

1
2 def greet(name):
3 return f'Hello, {name}!'
4
5 # Call the function
6 print(greet('Alice'))
7

Hint: Use the `def` keyword to define a function and specify parameters and return values.

Riddle: I am a reusable block of code that performs a specific task and can be called with different arguments. What am I?

Short Story: Michael needed a way to greet users in his application. By defining a function named `greet`, he could easily return a personalized greeting
message.

234. How do you import and use modules in Python?


Code:

1
2 import math
3
4 # Use functions from the math module
5 print([Link](16)) # Output: 4.0
6 print([Link]) # Output: 3.141592653589793
7

Hint: Use the `import` statement to bring in modules and access their functions and variables.

Riddle: I provide additional functionality by allowing you to use pre-written code from external files or libraries. What am I?

Short Story: Sarah needed to perform mathematical operations in her code. By importing the `math` module, she could use its functions and constants to
simplify her calculations.

235. How do you create a module in Python?


Code:

1
2 # Save this code in a file named [Link]
3 def add(a, b):
4 return a + b
5
6 def subtract(a, b):
7 return a - b
8

Hint: Create a new Python file with functions or variables, and import it into other scripts to use its functionality.

Riddle: I am a file containing Python code that can be imported and used in other Python scripts. What am I?

Short Story: Michael needed to reuse some functions across different projects. By creating a module named `mymodule`, he could easily import and use
those functions whenever needed.
236. How do you define a function with default arguments?
Code:

1
2 def greet(name='Guest'):
3 return f'Hello, {name}!'
4
5 # Call the function with and without an argument
6 print(greet()) # Output: Hello, Guest!
7 print(greet('Alice')) # Output: Hello, Alice!
8

Hint: Specify default values for parameters when defining a function, so they can be omitted when calling the function.

Riddle: I allow you to provide default values for function parameters, making them optional when calling the function. What am I?

Short Story: Sarah wanted to create a function that greeted users. By setting a default argument, she made it possible to greet guests if no specific name was
provided.

Advanced Topics

237. What is Object-Oriented Programming (OOP) in Python?


Answer:

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure code. In Python, OOP allows you to define classes
that encapsulate data and methods, promoting code reusability and organization. Key concepts include encapsulation, inheritance, and polymorphism.

Hint: OOP helps organize code into objects and classes, making it more modular and reusable.

Riddle: I am a programming paradigm that organizes code into objects, classes, and methods, helping to model real-world entities. What am I?

Short Story: Michael was building a complex application and found that OOP allowed him to organize his code into classes and objects, making it easier to
manage and extend his application.

238. How do you implement inheritance in Python?


Code:

1
2 class Animal:
3 def speak(self):
4 return 'Animal sound'
5
6 class Dog(Animal):
7 def speak(self):
8 return 'Woof'
9
10 # Create instances
11 animal = Animal()
12 dog = Dog()
13
14 print([Link]()) # Output: Animal sound
15 print([Link]()) # Output: Woof
16

Hint: Use parentheses to inherit from a parent class and override methods in the child class.

Riddle: I allow you to create a new class based on an existing class, inheriting its properties and methods. What am I?

Short Story: Sarah wanted to create a class for dogs that extended the functionality of a base animal class. By using inheritance, she was able to define
specific behaviors for dogs while reusing common features from the animal class.
239. What is polymorphism in Python?
Answer:

Polymorphism is a concept in programming that allows methods to do different things based on the object it is acting upon. In Python, polymorphism allows
methods to be overridden in child classes, providing different implementations for the same method name. It enables objects of different classes to be treated
as objects of a common superclass.

Hint: Polymorphism allows objects to use methods that are named the same but behave differently depending on the object.

Riddle: I allow a method to have different implementations based on the type of object that invokes it. What am I?

Short Story: Michael's application needed different behaviors for different types of objects. By implementing polymorphism, he was able to use the same
method name for different objects while providing specific functionality for each type.

240. How do you implement encapsulation in Python?


Code:

1
2 class Person:
3 def __init__(self, name):
4 self.__name = name # Private attribute
5
6 def get_name(self):
7 return self.__name
8
9 def set_name(self, name):
10 self.__name = name
11
12 # Create an instance
13 person = Person('Alice')
14 print(person.get_name()) # Output: Alice
15
16 # Modify name using setter method
17 person.set_name('Bob')
18 print(person.get_name()) # Output: Bob
19

Hint: Use double underscores to define private attributes and provide public methods to access or modify them.

Riddle: I help you hide the internal details of an object and only expose necessary methods for interaction. What am I?

Short Story: Sarah wanted to ensure that the internal details of her `Person` class were not exposed directly. By implementing encapsulation, she controlled
access to the class's attributes through getter and setter methods.

Project 1: Basic Calculator

Question:
Create a basic calculator that performs addition, subtraction, multiplication, and division.

Code:

1
2 def calculator():
3 operation = input('Enter operation (+, -, *, /): ')
4 num1 = float(input('Enter first number: '))
5 num2 = float(input('Enter second number: '))
6
7 if operation == '+':
8 print(f'The result is {num1 + num2}')
9 elif operation == '-':
10 print(f'The result is {num1 - num2}')
11 elif operation == '*':
12 print(f'The result is {num1 * num2}')
13 elif operation == '/':
14 if num2 != 0:
15 print(f'The result is {num1 / num2}')
16 else:
17 print('Error: Division by zero!')
18 else:
19 print('Invalid operation!')
20
21 calculator()
22

Hint: Use conditional statements to handle different operations.

Riddle: I take two numbers and an operation as input and provide the result based on the operation. What am I?

Short Story: Alice wanted to create a tool for quick calculations. By implementing a basic calculator, she could easily perform arithmetic operations and
solve math problems quickly.

Project 2: To-Do List

Question:
Create a simple to-do list application where users can add, remove, and view tasks.

Code:

1
2 tasks = []
3
4 def show_tasks():
5 if tasks:
6 print('To-Do List:')
7 for i, task in enumerate(tasks, 1):
8 print(f'{i}. {task}')
9 else:
10 print('No tasks in the list.')
11
12 def add_task():
13 task = input('Enter a task: ')
14 [Link](task)
15 print('Task added!')
16
17 def remove_task():
18 show_tasks()
19 try:
20 task_index = int(input('Enter the task number to remove: ')) - 1
21 if 0 <= task_index < len(tasks):
22 removed_task = [Link](task_index)
23 print(f'Task "{removed_task}" removed!')
24 else:
25 print('Invalid task number!')
26 except ValueError:
27 print('Invalid input!')
28
29 while True:
30 print('\n1. Show tasks\n2. Add task\n3. Remove task\n4. Quit')
31 choice = input('Enter your choice: ')
32
33 if choice == '1':
34 show_tasks()
35 elif choice == '2':
36 add_task()
37 elif choice == '3':
38 remove_task()
39 elif choice == '4':
40 break
41 else:
42 print('Invalid choice!')
43

Hint: Use a list to store tasks and provide options to add, remove, and display tasks.

Riddle: I help you manage your tasks by allowing you to add, remove, and view them. What am I?

Short Story: Sarah wanted to keep track of her daily tasks. By creating a to-do list application, she was able to stay organized and manage her time
effectively.
Project 3: Number Guessing Game

Question:
Create a number guessing game where the user has to guess a randomly generated number within a certain range.

Code:

1
2 import random
3
4 def guess_number():
5 number = [Link](1, 100)
6 attempts = 0
7 while True:
8 guess = int(input('Guess a number between 1 and 100: '))
9 attempts += 1
10 if guess < number:
11 print('Too low!')
12 elif guess > number:
13 print('Too high!')
14 else:
15 print(f'Congratulations! You guessed the number in {attempts} attempts.')
16 break
17
18 guess_number()
19

Hint: Use the `random` module to generate a random number and provide feedback based on the user’s guess.

Riddle: I challenge you to guess a hidden number with the help of hints about whether your guess is too high or too low. What am I?

Short Story: Michael wanted to create a fun game for his friends. By developing a number guessing game, he added an element of excitement and
competition to their gatherings.

Project 4: Simple Password Generator

Question:
Create a password generator that creates a random password with a specified length.

Code:

1
2 import random
3 import string
4
5 def generate_password(length):
6 characters = string.ascii_letters + [Link] + [Link]
7 return ''.join([Link](characters) for _ in range(length))
8
9 length = int(input('Enter the password length: '))
10 print('Generated password:', generate_password(length))
11

Hint: Use the `random` and `string` modules to generate a random combination of characters for the password.

Riddle: I create a secure combination of letters, digits, and symbols to protect your information. What am I?

Short Story: Sarah needed a secure password for her new accounts. By building a password generator, she ensured that her passwords were strong and
unique.
Project 5: BMI Calculator

Question:
Create a BMI (Body Mass Index) calculator that takes user weight and height as input and computes the BMI.

Code:

1
2 def calculate_bmi(weight, height):
3 return weight / (height ** 2)
4
5 weight = float(input('Enter your weight (kg): '))
6 height = float(input('Enter your height (m): '))
7 bmi = calculate_bmi(weight, height)
8 print(f'Your BMI is: {bmi:.2f}')
9
10 if bmi < 18.5:
11 print('You are underweight.')
12 elif 18.5 <= bmi < 24.9:
13 print('You have a normal weight.')
14 elif 25 <= bmi < 29.9:
15 print('You are overweight.')
16 else:
17 print('You are obese.')
18

Hint: BMI is calculated as weight divided by the square of height.

Riddle: I use your weight and height to tell you if you are underweight, normal weight, overweight, or obese. What am I?

Short Story: John wanted to monitor his health. By creating a BMI calculator, he could easily assess his weight status and make informed decisions about his
diet and exercise.

Project 6: Prime Number Checker

Question:
Write a program to check if a given number is a prime number.

Code:

1
2 def is_prime(number):
3 if number <= 1:
4 return False
5 for i in range(2, int(number ** 0.5) + 1):
6 if number % i == 0:
7 return False
8 return True
9
10 number = int(input('Enter a number: '))
11 if is_prime(number):
12 print(f'{number} is a prime number.')
13 else:
14 print(f'{number} is not a prime number.')
15

Hint: Check divisibility from 2 up to the square root of the number.

Riddle: I am a number greater than 1 that is only divisible by 1 and itself. What am I?

Short Story: Emily was learning about number theory and wanted to identify prime numbers. By writing a prime checker, she could easily test numbers and
understand the properties of primes.
Project 7: Currency Converter

Question:
Create a currency converter that converts an amount from one currency to another based on given exchange rates.

Code:

1
2 def convert_currency(amount, rate):
3 return amount * rate
4
5 amount = float(input('Enter amount in USD: '))
6 rate = float(input('Enter exchange rate to EUR: '))
7 converted_amount = convert_currency(amount, rate)
8 print(f'Amount in EUR: {converted_amount:.2f}')
9

Hint: Multiply the amount by the exchange rate to get the converted value.

Riddle: I take an amount and a rate to convert it into another currency. What am I?

Short Story: Daniel was traveling to Europe and needed to convert his dollars to euros. By creating a currency converter, he could quickly see how much he
would have in the local currency.

Project 8: Text File Reader

Question:
Write a program to read and display the contents of a text file.

Code:

1
2 filename = input('Enter the filename: ')
3
4 try:
5 with open(filename, 'r') as file:
6 contents = [Link]()
7 print('File contents:')
8 print(contents)
9 except FileNotFoundError:
10 print('File not found.')
11 except IOError:
12 print('Error reading the file.')
13

Hint: Use the `open` function in read mode and handle exceptions if the file does not exist or cannot be read.

Riddle: I allow you to view the contents of a file stored on your computer. What am I?

Short Story: Laura needed to review a document she had saved earlier. By creating a text file reader, she could easily open and display the content of her
files without needing additional software.

Project 9: Email Validator

Question:
Create a program to validate if an input string is a properly formatted email address.

Code:
1
2 import re
3
4 def is_valid_email(email):
5 pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
6 return [Link](pattern, email) is not None
7
8 email = input('Enter an email address: ')
9 if is_valid_email(email):
10 print('Valid email address.')
11 else:
12 print('Invalid email address.')
13

Hint: Use regular expressions to match the email pattern.

Riddle: I check if an email address is formatted correctly with an @ symbol and a domain name. What am I?

Short Story: Mike needed to validate user email addresses for his application. By writing an email validator, he could ensure that all inputted addresses were
in the correct format before processing them further.

Project 10: Rock, Paper, Scissors Game

Question:
Implement the classic game of Rock, Paper, Scissors where the user plays against the computer.

Code:

1
2 import random
3
4 def play_rps():
5 choices = ['rock', 'paper', 'scissors']
6 user_choice = input('Enter rock, paper, or scissors: ').lower()
7 if user_choice not in choices:
8 print('Invalid choice!')
9 return
10
11 computer_choice = [Link](choices)
12 print(f'Computer chose: {computer_choice}')
13
14 if user_choice == computer_choice:
15 print('It\'s a tie!')
16 elif (user_choice == 'rock' and computer_choice == 'scissors') or \
17 (user_choice == 'paper' and computer_choice == 'rock') or \
18 (user_choice == 'scissors' and computer_choice == 'paper'):
19 print('You win!')
20 else:
21 print('You lose!')
22
23 play_rps()
24

Hint: Use conditional statements to determine the winner based on the choices made by the user and the computer.

Riddle: I am a game where you choose rock, paper, or scissors to play against the computer. What am I?

Short Story: Alex wanted to create a fun and interactive game for friends. By developing Rock, Paper, Scissors, he was able to provide entertainment and
practice programming skills at the same time.
Project 11: Simple Quiz

Question:
Develop a simple quiz program where users answer multiple-choice questions, and the program scores their answers.

Code:

1
2 def ask_question(question, options, correct_option):
3 print(question)
4 for idx, option in enumerate(options, 1):
5 print(f'{idx}. {option}')
6
7 answer = int(input('Enter the number of your choice: '))
8 return answer == correct_option
9
10 score = 0
11 questions = [
12 {"question": "What is the capital of France?", "options": ["Berlin", "Madrid", "Paris", "Lisbon"], "correct_option":
3},
13 {"question": "What is 2 + 2?", "options": ["3", "4", "5", "6"], "correct_option": 2}
14 ]
15
16 for q in questions:
17 if ask_question(q["question"], q["options"], q["correct_option"]):
18 print('Correct!')
19 score += 1
20 else:
21 print('Wrong!')
22
23 print(f'Your score: {score}/{len(questions)}')
24

Hint: Use a loop to iterate through questions and keep track of the user's score.

Riddle: I ask questions and check if your answers are correct. What am I?

Short Story: Sarah wanted to create a fun quiz for her friends. By writing a simple quiz program, she could challenge their knowledge and keep track of their
scores.

Project 12: Number Guessing Game

Question:
Write a number guessing game where the user tries to guess a randomly generated number within a certain range.

Code:

1
2 import random
3
4 def guess_number():
5 number = [Link](1, 100)
6 attempts = 0
7 while True:
8 guess = int(input('Guess the number (between 1 and 100): '))
9 attempts += 1
10 if guess < number:
11 print('Too low!')
12 elif guess > number:
13 print('Too high!')
14 else:
15 print(f'Congratulations! You guessed the number in {attempts} attempts.')
16 break
17
18 guess_number()
19

Hint: Use a loop to allow multiple guesses and provide feedback based on whether the guess is too high or too low.

Riddle: I am a game where you guess a number and receive hints until you find the correct one. What am I?
Short Story: Mark enjoyed challenging his friends with guessing games. By creating a number guessing game, he added a fun element to his programming
projects.

Project 13: Contact Book

Question:
Create a simple contact book where you can add, view, and delete contacts. Each contact should have a name and phone number.

Code:

1
2 contacts = {}
3
4 def add_contact(name, phone):
5 contacts[name] = phone
6
7 def view_contacts():
8 for name, phone in [Link]():
9 print(f'Name: {name}, Phone: {phone}')
10
11 def delete_contact(name):
12 if name in contacts:
13 del contacts[name]
14 else:
15 print('Contact not found.')
16
17 while True:
18 action = input('Choose an action: add, view, delete, or quit: ').lower()
19 if action == 'add':
20 name = input('Enter contact name: ')
21 phone = input('Enter phone number: ')
22 add_contact(name, phone)
23 elif action == 'view':
24 view_contacts()
25 elif action == 'delete':
26 name = input('Enter contact name to delete: ')
27 delete_contact(name)
28 elif action == 'quit':
29 break
30 else:
31 print('Invalid action.')
32

Hint: Use a dictionary to store contacts and provide options for adding, viewing, and deleting them.

Riddle: I help you keep track of names and phone numbers, letting you add, view, or remove them as needed. What am I?

Short Story: Lisa wanted to manage her contacts more effectively. By creating a contact book, she could easily keep track of important phone numbers and
information.

Project 14: To-Do List

Question:
Build a to-do list application that allows users to add, view, and mark tasks as completed.

Code:

1
2 tasks = []
3
4 def add_task(task):
5 [Link]({"task": task, "completed": False})
6
7 def view_tasks():
8 for idx, task in enumerate(tasks):
9 status = 'Completed' if task['completed'] else 'Not Completed'
10 print(f'{idx + 1}. {task["task"]} - {status}')
11
12 def complete_task(index):
13 if 0 <= index < len(tasks):
14 tasks[index]['completed'] = True
15 else:
16 print('Task not found.')
17
18 while True:
19 action = input('Choose an action: add, view, complete, or quit: ').lower()
20 if action == 'add':
21 task = input('Enter the task: ')
22 add_task(task)
23 elif action == 'view':
24 view_tasks()
25 elif action == 'complete':
26 index = int(input('Enter task number to mark as completed: ')) - 1
27 complete_task(index)
28 elif action == 'quit':
29 break
30 else:
31 print('Invalid action.')
32

Hint: Use a list to store tasks and a dictionary to keep track of their completion status.

Riddle: I help you manage tasks by allowing you to add, view, and complete them. What am I?

Short Story: Tom wanted to organize his daily tasks better. By developing a to-do list application, he could keep track of what needed to be done and monitor
his progress.

Project 15: Basic Calculator

Question:
Develop a basic calculator that can perform addition, subtraction, multiplication, and division based on user input.

Code:

1
2 def calculate(a, b, operator):
3 if operator == '+':
4 return a + b
5 elif operator == '-':
6 return a - b
7 elif operator == '*':
8 return a * b
9 elif operator == '/':
10 if b != 0:
11 return a / b
12 else:
13 return 'Error: Division by zero.'
14 else:
15 return 'Invalid operator.'
16
17 a = float(input('Enter first number: '))
18 b = float(input('Enter second number: '))
19 operator = input('Enter operator (+, -, *, /): ')
20 result = calculate(a, b, operator)
21 print(f'Result: {result}')
22

Hint: Use conditional statements to perform the operation based on the chosen operator.

Riddle: I can perform basic arithmetic operations including addition, subtraction, multiplication, and division. What am I?

Short Story: Rachel needed a simple tool for performing calculations quickly. By creating a basic calculator, she could easily perform mathematical
operations without needing a separate application.
Project 16: Temperature Converter

Question:
Create a program that converts temperatures between Celsius, Fahrenheit, and Kelvin.

Code:

1
2 def celsius_to_fahrenheit(celsius):
3 return (celsius * 9/5) + 32
4
5 def fahrenheit_to_celsius(fahrenheit):
6 return (fahrenheit - 32) * 5/9
7
8 def celsius_to_kelvin(celsius):
9 return celsius + 273.15
10
11 def kelvin_to_celsius(kelvin):
12 return kelvin - 273.15
13
14 temp = float(input('Enter temperature: '))
15 unit = input('Enter unit (C/F/K): ').upper()
16
17 if unit == 'C':
18 print(f'Fahrenheit: {celsius_to_fahrenheit(temp)}')
19 print(f'Kelvin: {celsius_to_kelvin(temp)}')
20 elif unit == 'F':
21 print(f'Celsius: {fahrenheit_to_celsius(temp)}')
22 elif unit == 'K':
23 print(f'Celsius: {kelvin_to_celsius(temp)}')
24 else:
25 print('Invalid unit.')
26

Hint: Use functions to convert between units and prompt the user for input.

Riddle: I convert temperatures from one scale to another, ensuring you can work with Celsius, Fahrenheit, and Kelvin. What am I?

Short Story: Emily needed to compare temperatures in different scales for her science project. By creating a temperature converter, she could quickly switch
between Celsius, Fahrenheit, and Kelvin.

Project 17: Palindrome Checker

Question:
Write a program that checks if a given string is a palindrome (a word that reads the same backward as forward).

Code:

1
2 def is_palindrome(s):
3 s = [Link]()
4 return s == s[::-1]
5
6 string = input('Enter a string: ')
7 if is_palindrome(string):
8 print('The string is a palindrome.')
9 else:
10 print('The string is not a palindrome.')
11

Hint: Check if the string reads the same forward and backward by reversing it.

Riddle: I am a word or phrase that reads the same forwards and backwards. What am I?

Short Story: John was fascinated by palindromes and wanted to check if a word or phrase met this criteria. By writing a palindrome checker, he could
explore various palindromic sequences.
Project 18: Simple Bank Account

Question:
Create a simple bank account program where users can deposit, withdraw, and check their balance.

Code:

1
2 class BankAccount:
3 def __init__(self):
4 [Link] = 0
5
6 def deposit(self, amount):
7 [Link] += amount
8 print(f'Deposited ${amount}. New balance: ${[Link]}')
9
10 def withdraw(self, amount):
11 if amount <= [Link]:
12 [Link] -= amount
13 print(f'Withdrew ${amount}. New balance: ${[Link]}')
14 else:
15 print('Insufficient funds.')
16
17 def check_balance(self):
18 print(f'Current balance: ${[Link]}')
19
20 account = BankAccount()
21
22 while True:
23 action = input('Choose an action: deposit, withdraw, check, or quit: ').lower()
24 if action == 'deposit':
25 amount = float(input('Enter amount to deposit: '))
26 [Link](amount)
27 elif action == 'withdraw':
28 amount = float(input('Enter amount to withdraw: '))
29 [Link](amount)
30 elif action == 'check':
31 account.check_balance()
32 elif action == 'quit':
33 break
34 else:
35 print('Invalid action.')
36

Hint: Use a class to encapsulate account details and methods for deposit, withdrawal, and balance checking.

Riddle: I manage your money, allowing you to deposit, withdraw, and check your balance. What am I?

Short Story: Olivia wanted to keep track of her finances more effectively. By creating a simple bank account program, she could manage her deposits,
withdrawals, and balance with ease.

Project 19: Countdown Timer

Question:
Build a countdown timer that counts down from a specified number of seconds and alerts the user when time is up.

Code:

1
2 import time
3
4 def countdown_timer(seconds):
5 while seconds:
6 mins, secs = divmod(seconds, 60)
7 timeformat = '{:02d}:{:02d}'.format(mins, secs)
8 print(timeformat, end='\r')
9 [Link](1)
10 seconds -= 1
11
12 print('Time\'s up!')
13
14 seconds = int(input('Enter the number of seconds for the countdown: '))
15 countdown_timer(seconds)
16

Hint: Use a loop and `[Link]()` to create a countdown effect and display the remaining time.

Riddle: I count down from a given number of seconds, showing the time left and notifying you when it reaches zero. What am I?

Short Story: David needed a way to time his cooking. By creating a countdown timer, he could easily monitor the cooking time and receive a notification
when it was over.

Project 20: Random Password Generator

Question:
Write a program that generates a random password with a mix of letters, numbers, and special characters.

Code:

1
2 import random
3 import string
4
5 def generate_password(length):
6 characters = string.ascii_letters + [Link] + [Link]
7 return ''.join([Link](characters) for i in range(length))
8
9 length = int(input('Enter the length of the password: '))
10 print(f'Generated password: {generate_password(length)}')
11

Hint: Use the `random` module to select characters from a set of letters, digits, and symbols to generate a secure password.

Riddle: I generate a secure password using a combination of letters, numbers, and special characters. What am I?

Short Story: Sarah wanted to ensure her online accounts were secure. By creating a random password generator, she could easily generate strong and unique
passwords for each of her accounts.

Project 21: Contact Book

Question:
Create a contact book application that allows users to add, delete, and search for contacts.

Code:

1
2 class ContactBook:
3 def __init__(self):
4 [Link] = {}
5
6 def add_contact(self, name, phone):
7 [Link][name] = phone
8 print(f'Contact {name} added.')
9
10 def delete_contact(self, name):
11 if name in [Link]:
12 del [Link][name]
13 print(f'Contact {name} deleted.')
14 else:
15 print('Contact not found.')
16
17 def search_contact(self, name):
18 return [Link](name, 'Contact not found.')
19
20 book = ContactBook()
21
22 while True:
23 action = input('Choose an action: add, delete, search, or quit: ').lower()
24 if action == 'add':
25 name = input('Enter name: ')
26 phone = input('Enter phone number: ')
27 book.add_contact(name, phone)
28 elif action == 'delete':
29 name = input('Enter name: ')
30 book.delete_contact(name)
31 elif action == 'search':
32 name = input('Enter name: ')
33 print(f'Phone number: {book.search_contact(name)}')
34 elif action == 'quit':
35 break
36 else:
37 print('Invalid action.')
38

Hint: Use a dictionary to store contact names and phone numbers, and implement methods for adding, deleting, and searching contacts.

Riddle: I store names and phone numbers, allowing you to add, delete, and search for contacts. What am I?

Short Story: Lisa wanted a way to keep track of her friends' phone numbers. By creating a contact book application, she could easily manage her contacts
and find their numbers whenever needed.

Project 22: Unit Converter

Question:
Build a unit converter that can convert between different units of measurement, such as length, weight, and volume.

Code:

1
2 def convert_length(value, unit_from, unit_to):
3 conversion_factors = {
4 'm_to_km': 0.001,
5 'km_to_m': 1000,
6 'm_to_cm': 100,
7 'cm_to_m': 0.01
8 }
9 key = f'{unit_from}_to_{unit_to}'
10 return value * conversion_factors.get(key, 1)
11
12 value = float(input('Enter value to convert: '))
13 unit_from = input('Enter from unit (m, km, cm): ')
14 unit_to = input('Enter to unit (m, km, cm): ')
15 print(f'Converted value: {convert_length(value, unit_from, unit_to)} {unit_to}')
16

Hint: Create conversion factors for different units and apply the appropriate conversion based on user input.

Riddle: I transform values between various units of measurement, helping you switch between meters, kilometers, and centimeters. What am I?

Short Story: Mark needed to convert measurements for his DIY project. By creating a unit converter, he could easily switch between different units of
length, weight, and volume.

Project 23: Todo List Application

Question:
Create a to-do list application where users can add, remove, and view tasks.

Code:

1
2 class TodoList:
3 def __init__(self):
4 [Link] = []
5
6 def add_task(self, task):
7 [Link](task)
8 print(f'Task "{task}" added.')
9
10 def remove_task(self, task):
11 if task in [Link]:
12 [Link](task)
13 print(f'Task "{task}" removed.')
14 else:
15 print('Task not found.')
16
17 def view_tasks(self):
18 print('Tasks:')
19 for task in [Link]:
20 print(f'- {task}')
21
22 todo_list = TodoList()
23
24 while True:
25 action = input('Choose an action: add, remove, view, or quit: ').lower()
26 if action == 'add':
27 task = input('Enter task: ')
28 todo_list.add_task(task)
29 elif action == 'remove':
30 task = input('Enter task: ')
31 todo_list.remove_task(task)
32 elif action == 'view':
33 todo_list.view_tasks()
34 elif action == 'quit':
35 break
36 else:
37 print('Invalid action.')
38

Hint: Use a list to store tasks and implement methods for adding, removing, and viewing tasks.

Riddle: I keep track of your tasks, allowing you to add, remove, and view them whenever you like. What am I?

Short Story: Jessica wanted to stay organized and manage her tasks effectively. By creating a to-do list application, she could keep track of her daily
activities and never miss a deadline.

Project 24: Basic Calculator

Question:
Develop a basic calculator that can perform addition, subtraction, multiplication, and division.

Code:

1
2 def add(x, y):
3 return x + y
4
5 def subtract(x, y):
6 return x - y
7
8 def multiply(x, y):
9 return x * y
10
11 def divide(x, y):
12 if y != 0:
13 return x / y
14 else:
15 return 'Error: Division by zero.'
16
17 print('Select operation:')
18 print('1. Add')
19 print('2. Subtract')
20 print('3. Multiply')
21 print('4. Divide')
22
23 choice = input('Enter choice (1/2/3/4): ')
24
25 num1 = float(input('Enter first number: '))
26 num2 = float(input('Enter second number: '))
27
28 if choice == '1':
29 print(f'Result: {add(num1, num2)}')
30 elif choice == '2':
31 print(f'Result: {subtract(num1, num2)}')
32 elif choice == '3':
33 print(f'Result: {multiply(num1, num2)}')
34 elif choice == '4':
35 print(f'Result: {divide(num1, num2)}')
36 else:
37 print('Invalid input.')
38

Hint: Define functions for each arithmetic operation and use user input to select the operation and numbers.

Riddle: I perform basic arithmetic operations, allowing you to add, subtract, multiply, and divide numbers. What am I?

Short Story: Alex needed a simple tool for performing basic arithmetic operations. By creating a basic calculator, he could quickly perform calculations and
solve math problems.

Project 25: Weather App

Question:
Build a weather application that fetches and displays the current weather for a given location using a weather API.

Code:

1
2 import requests
3
4 def get_weather(city):
5 api_key = 'your_api_key_here'
6 base_url = '[Link]
7 params = {'q': city, 'appid': api_key, 'units': 'metric'}
8 response = [Link](base_url, params=params)
9 data = [Link]()
10
11 if data['cod'] == 200:
12 temperature = data['main']['temp']
13 weather_description = data['weather'][0]['description']
14 print(f'Temperature: {temperature}°C')
15 print(f'Weather: {weather_description}')
16 else:
17 print('City not found.')
18
19 city = input('Enter city name: ')
20 get_weather(city)
21

Hint: Use the `requests` library to fetch weather data from an API and parse the response to display the temperature and weather description.

Riddle: I provide current weather information for any city using data from an online source. What am I?

Short Story: Maria wanted to know the current weather before heading out. By creating a weather app, she could easily check the weather for any city and
plan her day accordingly.

Project 26: Quiz Game

Question:
Develop a quiz game where users answer multiple-choice questions and receive a score at the end.

Code:

1
2 questions = [
3 {'question': 'What is the capital of France?', 'choices': ['Paris', 'London', 'Rome', 'Berlin'], 'answer': 'Paris'},
4 {'question': 'What is 2 + 2?', 'choices': ['3', '4', '5', '6'], 'answer': '4'},
5 {'question': 'What is the largest planet in our solar system?', 'choices': ['Earth', 'Mars', 'Jupiter', 'Saturn'],
'answer': 'Jupiter'}
6 ]
7
8 score = 0
9
10 for q in questions:
11 print(q['question'])
12 for i, choice in enumerate(q['choices']):
13 print(f'{i + 1}. {choice}')
14
15 answer = input('Enter your choice (1/2/3/4): ')
16 if q['choices'][int(answer) - 1] == q['answer']:
17 score += 1
18 print('Correct!')
19 else:
20 print('Wrong!')
21
22 print(f'Your final score is {score}/{len(questions)}')
23

Hint: Create a list of questions and choices, and keep track of the score based on user responses.

Riddle: I test your knowledge with questions and choices, giving you a score at the end. What am I?

Short Story: John wanted a fun way to test his knowledge. By building a quiz game, he could challenge himself with questions and keep track of his score.

Project 27: Expense Tracker

Question:
Create an expense tracker application that records expenses and displays a summary of total spending.

Code:

1
2 expenses = []
3
4 def add_expense(amount, category):
5 [Link]({'amount': amount, 'category': category})
6 print(f'Expense of ${amount} added to category {category}.')
7
8 def show_summary():
9 total = sum(expense['amount'] for expense in expenses)
10 print(f'Total spending: ${total}')
11 for category in set(expense['category'] for expense in expenses):
12 category_total = sum(expense['amount'] for expense in expenses if expense['category'] == category)
13 print(f'{category}: ${category_total}')
14
15 while True:
16 action = input('Choose an action: add, summary, or quit: ').lower()
17 if action == 'add':
18 amount = float(input('Enter amount: '))
19 category = input('Enter category: ')
20 add_expense(amount, category)
21 elif action == 'summary':
22 show_summary()
23 elif action == 'quit':
24 break
25 else:
26 print('Invalid action.')
27

Hint: Store expenses in a list of dictionaries and provide methods to add expenses and display a summary.

Riddle: I keep track of your spending and categorize your expenses, showing you a summary of your total costs. What am I?

Short Story: Emma wanted to keep her finances in check. By developing an expense tracker, she could easily record her expenses and monitor her spending
habits.
Project 28: Digital Diary

Question:
Build a digital diary application where users can write and save journal entries.

Code:

1
2 entries = []
3
4 def add_entry(title, content):
5 [Link]({'title': title, 'content': content})
6 print(f'Entry "{title}" added.')
7
8 def view_entries():
9 for entry in entries:
10 print(f'Title: {entry["title"]}')
11 print(f'Content: {entry["content"]}')
12 print('---')
13
14 while True:
15 action = input('Choose an action: add, view, or quit: ').lower()
16 if action == 'add':
17 title = input('Enter title: ')
18 content = input('Enter content: ')
19 add_entry(title, content)
20 elif action == 'view':
21 view_entries()
22 elif action == 'quit':
23 break
24 else:
25 print('Invalid action.')
26

Hint: Use a list to store journal entries, and implement methods to add and view entries.

Riddle: I store your thoughts and memories in written form, allowing you to view them whenever you wish. What am I?

Short Story: Sarah wanted a private place to record her thoughts. By creating a digital diary application, she could easily jot down her experiences and
reflect on them later.

Project 29: Password Generator

Question:
Develop a password generator that creates strong, random passwords of varying lengths.

Code:

1
2 import random
3 import string
4
5 def generate_password(length):
6 characters = string.ascii_letters + [Link] + [Link]
7 return ''.join([Link](characters) for _ in range(length))
8
9 length = int(input('Enter password length: '))
10 print(f'Generated password: {generate_password(length)}')
11

Hint: Use the `random` and `string` libraries to generate a random password with letters, digits, and punctuation.

Riddle: I create secure and random passwords of any length, making it harder for anyone to guess. What am I?

Short Story: Alex wanted a way to generate strong passwords for his online accounts. By building a password generator, he could create secure passwords
quickly and easily.
Project 30: Number Guessing Game

Question:
Build a number guessing game where users try to guess a randomly generated number within a certain number of attempts.

Code:

1
2 import random
3
4 def number_guessing_game():
5 number = [Link](1, 100)
6 attempts = 0
7 while True:
8 guess = int(input('Guess the number (between 1 and 100): '))
9 attempts += 1
10 if guess < number:
11 print('Too low!')
12 elif guess > number:
13 print('Too high!')
14 else:
15 print(f'Congratulations! You guessed the number in {attempts} attempts.')
16 break
17
18 number_guessing_game()
19

Hint: Generate a random number and give feedback to the user based on their guesses until they find the correct number.

Riddle: I challenge you to guess a number with hints, and reward you when you find the right answer. What am I?

Short Story: Emma enjoyed playing guessing games and wanted to create her own. By developing a number guessing game, she could test her intuition and
improve her guessing skills.

Project 31: Currency Converter

Question:
Create a currency converter that converts an amount from one currency to another using real-time exchange rates from an API.

Code:

1
2 import requests
3
4 def convert_currency(amount, from_currency, to_currency):
5 api_key = 'your_api_key_here'
6 base_url = '[Link]
7 response = [Link](base_url + from_currency)
8 data = [Link]()
9 rate = data['rates'].get(to_currency, 1)
10 return amount * rate
11
12 amount = float(input('Enter amount: '))
13 from_currency = input('Enter from currency code (e.g., USD): ')
14 to_currency = input('Enter to currency code (e.g., EUR): ')
15 converted_amount = convert_currency(amount, from_currency, to_currency)
16 print(f'{amount} {from_currency} is equal to {converted_amount:.2f} {to_currency}')
17

Hint: Use an API to get real-time exchange rates and perform the currency conversion based on user input.

Riddle: I help you convert money between different currencies, providing up-to-date rates for accurate conversion. What am I?

Short Story: Tom needed to travel abroad and wanted to know how much his money would be worth in different countries. By building a currency converter,
he could easily calculate the conversion rates and plan his budget.
Project 32: Task Manager

Question:
Develop a task manager application that allows users to add, view, and delete tasks from a to-do list.

Code:

1
2 tasks = []
3
4 def add_task(task):
5 [Link](task)
6 print(f'Task "{task}" added.')
7
8 def view_tasks():
9 print('Tasks:')
10 for i, task in enumerate(tasks):
11 print(f'{i + 1}. {task}')
12
13 def delete_task(index):
14 if 0 <= index < len(tasks):
15 removed_task = [Link](index)
16 print(f'Task "{removed_task}" deleted.')
17 else:
18 print('Invalid index.')
19
20 while True:
21 action = input('Choose an action: add, view, delete, or quit: ').lower()
22 if action == 'add':
23 task = input('Enter task: ')
24 add_task(task)
25 elif action == 'view':
26 view_tasks()
27 elif action == 'delete':
28 index = int(input('Enter task number to delete: ')) - 1
29 delete_task(index)
30 elif action == 'quit':
31 break
32 else:
33 print('Invalid action.')
34

Hint: Use a list to store tasks and implement methods to add, view, and delete tasks from the list.

Riddle: I keep track of your to-do items, letting you add, view, and remove tasks from your list. What am I?

Short Story: Jane had a lot of tasks to manage and needed a way to stay organized. By creating a task manager, she could keep track of her to-do list and
ensure nothing important was forgotten.

Project 33: Calendar Application

Question:
Build a calendar application that allows users to add, view, and remove events on a monthly calendar view.

Code:

1
2 import calendar
3
4 events = {}
5
6 def add_event(day, event):
7 if day in events:
8 events[day].append(event)
9 else:
10 events[day] = [event]
11 print(f'Event "{event}" added for day {day}.')
12
13 def view_calendar(year, month):
14 cal = [Link](year, month)
15 print(cal)
16 for day, event_list in [Link]():
17 print(f'Events on {day}:')
18 for event in event_list:
19 print(f' - {event}')
20
21 def remove_event(day, event):
22 if day in events and event in events[day]:
23 events[day].remove(event)
24 if not events[day]:
25 del events[day]
26 print(f'Event "{event}" removed from day {day}.')
27 else:
28 print('Event not found.')
29
30 year = int(input('Enter year: '))
31 month = int(input('Enter month (1-12): '))
32
33 while True:
34 action = input('Choose an action: add, view, remove, or quit: ').lower()
35 if action == 'add':
36 day = int(input('Enter day: '))
37 event = input('Enter event: ')
38 add_event(day, event)
39 elif action == 'view':
40 view_calendar(year, month)
41 elif action == 'remove':
42 day = int(input('Enter day: '))
43 event = input('Enter event to remove: ')
44 remove_event(day, event)
45 elif action == 'quit':
46 break
47 else:
48 print('Invalid action.')
49

Hint: Use a dictionary to store events by day, and provide methods to add, view, and remove events from the calendar.

Riddle: I let you manage your events on a monthly calendar, making sure you never forget an important date. What am I?

Short Story: Alice wanted to keep track of her appointments and events. By developing a calendar application, she could easily organize her schedule and
stay on top of her commitments.

Project 34: Recipe Book

Question:
Create a recipe book application where users can add, view, and search for recipes based on ingredients.

Code:

1
2 recipes = {}
3
4 def add_recipe(name, ingredients, instructions):
5 recipes[name] = {'ingredients': ingredients, 'instructions': instructions}
6 print(f'Recipe "{name}" added.')
7
8 def view_recipe(name):
9 recipe = [Link](name)
10 if recipe:
11 print(f'Recipe: {name}')
12 print('Ingredients:')
13 for ingredient in recipe['ingredients']:
14 print(f' - {ingredient}')
15 print('Instructions:')
16 print(recipe['instructions'])
17 else:
18 print('Recipe not found.')
19
20 def search_recipes(ingredient):
21 found_recipes = [name for name, recipe in [Link]() if ingredient in recipe['ingredients']]
22 if found_recipes:
23 print('Recipes containing', ingredient, ':')
24 for name in found_recipes:
25 print(f' - {name}')
26 else:
27 print('No recipes found containing', ingredient)
28
29 while True:
30 action = input('Choose an action: add, view, search, or quit: ').lower()
31 if action == 'add':
32 name = input('Enter recipe name: ')
33 ingredients = input('Enter ingredients (comma-separated): ').split(',')
34 instructions = input('Enter instructions: ')
35 add_recipe(name, ingredients, instructions)
36 elif action == 'view':
37 name = input('Enter recipe name to view: ')
38 view_recipe(name)
39 elif action == 'search':
40 ingredient = input('Enter ingredient to search: ')
41 search_recipes(ingredient)
42 elif action == 'quit':
43 break
44 else:
45 print('Invalid action.')
46

Hint: Store recipes in a dictionary and provide methods to add, view, and search recipes based on ingredients.

Riddle: I help you organize your favorite recipes and find new ones based on ingredients you have. What am I?

Short Story: Lily loved cooking and wanted to keep track of her favorite recipes. By building a recipe book application, she could easily store and search for
recipes based on ingredients.

Project 35: Alarm Clock

Question:
Develop an alarm clock application that allows users to set alarms and get notified when the time arrives.

Code:

1
2 import time
3 from datetime import datetime
4
5 def set_alarm(alarm_time):
6 print(f'Alarm set for {alarm_time}')
7 while True:
8 current_time = [Link]().strftime('%H:%M')
9 if current_time == alarm_time:
10 print('Alarm ringing!')
11 break
12 [Link](30)
13
14 alarm_time = input('Enter alarm time (HH:MM): ')
15 set_alarm(alarm_time)
16

Hint: Use the `datetime` module to check the current time and compare it with the alarm time to trigger notifications.

Riddle: I wake you up at the exact time you set, helping you start your day on schedule. What am I?

Short Story: Mark wanted to create an alarm clock application to wake him up at specific times. By developing this app, he could ensure he never missed an
important meeting or event.
Project 36: Weather Dashboard

Question:
Build a weather dashboard that displays current weather information for a given city using an API.

Code:

1
2 import requests
3
4 def get_weather(city):
5 api_key = 'your_api_key_here'
6 url = f'[Link]
7 response = [Link](url)
8 data = [Link]()
9 if data['cod'] == 200:
10 weather = data['weather'][0]['description']
11 temp = data['main']['temp'] - 273.15 # Convert from Kelvin to Celsius
12 print(f'Weather in {city}: {weather}')
13 print(f'Temperature: {temp:.2f}°C')
14 else:
15 print('City not found.')
16
17 city = input('Enter city name: ')
18 get_weather(city)
19

Hint: Use the OpenWeatherMap API to fetch and display current weather data for a specified city.

Riddle: I show you the current weather and temperature for any city, helping you plan your day accordingly. What am I?

Short Story: Emily wanted to know the weather before heading out. By building a weather dashboard, she could quickly check the weather conditions for
any city and plan her day.

Project 37: Personal Budget Tracker

Question:
Create a personal budget tracker that allows users to record their income and expenses and view their current balance.

Code:

1
2 budget = {'income': 0, 'expenses': 0}
3
4 def record_income(amount):
5 budget['income'] += amount
6 print(f'Income recorded: {amount}')
7
8 def record_expense(amount):
9 budget['expenses'] += amount
10 print(f'Expense recorded: {amount}')
11
12 def view_balance():
13 balance = budget['income'] - budget['expenses']
14 print(f'Current balance: {balance}')
15
16 while True:
17 action = input('Choose an action: income, expense, balance, or quit: ').lower()
18 if action == 'income':
19 amount = float(input('Enter income amount: '))
20 record_income(amount)
21 elif action == 'expense':
22 amount = float(input('Enter expense amount: '))
23 record_expense(amount)
24 elif action == 'balance':
25 view_balance()
26 elif action == 'quit':
27 break
28 else:
29 print('Invalid action.')
30

Hint: Maintain a dictionary to keep track of income and expenses and calculate the current balance based on user inputs.

Riddle: I help you keep track of your finances by recording your income and expenses, showing your current balance. What am I?

Short Story: Sarah wanted to manage her personal finances better. By creating a budget tracker, she could keep track of her income and expenses, helping
her stay on top of her financial situation.

Project 38: Habit Tracker

Question:
Develop a habit tracker application that allows users to record their daily habits and view their progress over time.

Code:

1
2 import datetime
3
4 habits = {}
5
6 def add_habit(habit):
7 habits[habit] = []
8
9 def record_habit(habit, date):
10 if habit in habits:
11 habits[habit].append(date)
12 print(f'Habit "{habit}" recorded for {date}.')
13 else:
14 print('Habit not found.')
15
16 def view_progress():
17 today = [Link]().strftime('%Y-%m-%d')
18 print(f'Progress for {today}:')
19 for habit, dates in [Link]():
20 print(f'{habit}: {len(dates)} times')
21
22 while True:
23 action = input('Choose an action: add, record, view, or quit: ').lower()
24 if action == 'add':
25 habit = input('Enter habit to add: ')
26 add_habit(habit)
27 elif action == 'record':
28 habit = input('Enter habit to record: ')
29 date = input('Enter date (YYYY-MM-DD): ')
30 record_habit(habit, date)
31 elif action == 'view':
32 view_progress()
33 elif action == 'quit':
34 break
35 else:
36 print('Invalid action.')
37

Hint: Use a dictionary to track habits and the dates they were performed. Implement functions to add, record, and view progress on habits.

Riddle: I help you keep track of your daily habits, letting you record and review your progress over time. What am I?

Short Story: Emma wanted to build better habits and monitor her progress. By developing a habit tracker, she could easily keep track of her daily habits and
stay motivated.
Project 39: Simple Chatbot

Question:
Create a simple chatbot that can respond to basic questions and have a conversation with the user.

Code:

1
2 def chatbot_response(user_input):
3 responses = {
4 'hi': 'Hello! How can I help you today?',
5 'how are you': 'I am just a bot, but I am doing well. How about you?',
6 'bye': 'Goodbye! Have a great day!',
7 }
8 return [Link](user_input.lower(), 'I am not sure how to respond to that.')
9
10 while True:
11 user_input = input('You: ')
12 response = chatbot_response(user_input)
13 print(f'Bot: {response}')
14 if user_input.lower() == 'bye':
15 break
16

Hint: Use a dictionary to store predefined responses and match user input to provide appropriate replies.

Riddle: I am a digital assistant that responds to your messages with pre-set answers, helping you with basic queries. What am I?

Short Story: Kevin wanted a way to interact with his computer using natural language. By creating a simple chatbot, he could have basic conversations and
get responses to common questions.

Project 40: Markdown to HTML Converter

Question:
Develop a program that converts Markdown text into HTML format.

Code:

1
2 import markdown
3
4 def convert_markdown_to_html(markdown_text):
5 return [Link](markdown_text)
6
7 markdown_text = '''# Sample Markdown
8 **Bold Text**
9 *Italic Text*
10 - List item 1
11 - List item 2'''
12
13 html = convert_markdown_to_html(markdown_text)
14 print(html)
15

Hint: Use the `markdown` library to convert Markdown text to HTML.

Riddle: I transform text written in Markdown into structured HTML format, making it suitable for web pages. What am I?

Short Story: Laura wanted a tool to convert her Markdown notes into HTML for her blog. By creating this converter, she could easily publish her formatted
content online.
Project 41: Password Generator

Question:
Write a program to generate strong, random passwords of a given length.

Code:

1
2 import random
3 import string
4
5 def generate_password(length):
6 characters = string.ascii_letters + [Link] + [Link]
7 return ''.join([Link](characters) for _ in range(length))
8
9 length = int(input('Enter the desired length of the password: '))
10 print(f'Generated Password: {generate_password(length)}')
11

Hint: Use the `random` and `string` modules to generate a password with a mix of letters, digits, and punctuation.

Riddle: I create strong, random strings of characters to help you secure your accounts. What am I?

Short Story: Tom needed a secure password for his online accounts. By building a password generator, he could easily create strong passwords to enhance
his security.

Project 42: Contact Book

Question:
Build a contact book application that allows users to add, view, and search for contacts.

Code:

1
2 contacts = {}
3
4 def add_contact(name, phone):
5 contacts[name] = phone
6 print(f'Contact "{name}" added.')
7
8 def view_contacts():
9 for name, phone in [Link]():
10 print(f'Name: {name}, Phone: {phone}')
11
12 def search_contact(name):
13 phone = [Link](name)
14 if phone:
15 print(f'Contact found: {name} - {phone}')
16 else:
17 print('Contact not found.')
18
19 while True:
20 action = input('Choose an action: add, view, search, or quit: ').lower()
21 if action == 'add':
22 name = input('Enter contact name: ')
23 phone = input('Enter phone number: ')
24 add_contact(name, phone)
25 elif action == 'view':
26 view_contacts()
27 elif action == 'search':
28 name = input('Enter contact name to search: ')
29 search_contact(name)
30 elif action == 'quit':
31 break
32 else:
33 print('Invalid action.')
34

Hint: Store contacts in a dictionary and provide methods to add, view, and search for contacts.
Riddle: I keep track of your friends and family’s phone numbers, allowing you to add, view, and search for contacts. What am I?

Short Story: Sarah wanted a way to manage her contacts. By creating a contact book application, she could easily add, view, and search for contact
information.

Project 43: Expense Tracker

Question:
Design an expense tracker that allows users to record their daily expenses and view a summary of their spending.

Code:

1
2 expenses = []
3
4 def add_expense(amount, description):
5 [Link]({'amount': amount, 'description': description})
6 print(f'Expense of {amount} added: {description}')
7
8 def view_summary():
9 total = sum(expense['amount'] for expense in expenses)
10 print(f'Total Expenses: {total}')
11 for expense in expenses:
12 print(f'{expense["amount"]}: {expense["description"]}')
13
14 while True:
15 action = input('Choose an action: add, summary, or quit: ').lower()
16 if action == 'add':
17 amount = float(input('Enter expense amount: '))
18 description = input('Enter expense description: ')
19 add_expense(amount, description)
20 elif action == 'summary':
21 view_summary()
22 elif action == 'quit':
23 break
24 else:
25 print('Invalid action.')
26

Hint: Use a list to store expenses and implement functions to add and view a summary of expenses.

Riddle: I help you manage your daily spending by recording your expenses and summarizing your total spending. What am I?

Short Story: Lily wanted to keep track of her expenses and manage her budget better. By creating an expense tracker, she could record and review her daily
spending efficiently.

Project 44: Online Quiz

Question:
Create an online quiz application that presents users with multiple-choice questions and calculates their score based on their answers.

Code:

1
2 questions = {
3 'What is the capital of France?': ['Paris', 'London', 'Berlin', 'Rome'],
4 'Which planet is known as the Red Planet?': ['Mars', 'Venus', 'Earth', 'Jupiter']
5 }
6
7 def ask_questions():
8 score = 0
9 for question, options in [Link]():
10 print(question)
11 for i, option in enumerate(options):
12 print(f'{i + 1}. {option}')
13 answer = int(input('Enter your answer (1-4): ')) - 1
14 if options[answer] == 'Paris' or options[answer] == 'Mars': # Correct answers
15 score += 1
16 print(f'Your score: {score}/{len(questions)}')
17
18 ask_questions()
19

Hint: Use a dictionary to store questions and multiple-choice options, and calculate the score based on user answers.

Riddle: I present you with questions and options, then calculate your score based on your answers. What am I?

Short Story: John wanted to test his knowledge and have some fun. By creating an online quiz, he could answer questions and see how well he did.

Project 45: To-Do List Manager

Question:
Develop a to-do list manager that allows users to add, view, and mark tasks as completed.

Code:

1
2 tasks = {}
3
4 def add_task(task):
5 tasks[task] = False
6 print(f'Task "{task}" added.')
7
8 def mark_completed(task):
9 if task in tasks:
10 tasks[task] = True
11 print(f'Task "{task}" marked as completed.')
12 else:
13 print('Task not found.')
14
15 def view_tasks():
16 for task, completed in [Link]():
17 status = 'Completed' if completed else 'Pending'
18 print(f'{task}: {status}')
19
20 while True:
21 action = input('Choose an action: add, complete, view, or quit: ').lower()
22 if action == 'add':
23 task = input('Enter task description: ')
24 add_task(task)
25 elif action == 'complete':
26 task = input('Enter task to mark as completed: ')
27 mark_completed(task)
28 elif action == 'view':
29 view_tasks()
30 elif action == 'quit':
31 break
32 else:
33 print('Invalid action.')
34

Hint: Use a dictionary to manage tasks and their completion status, with functions to add, complete, and view tasks.

Riddle: I help you keep track of your tasks, allowing you to add, complete, and review them. What am I?

Short Story: Mark wanted a way to stay organized and keep track of his tasks. By building a to-do list manager, he could efficiently manage his daily
activities.

Project 46: URL Shortener

Question:
Create a URL shortener that converts long URLs into shorter, more manageable ones.

Code:

1
2 import hashlib
3
4 urls = {}
5
6 def shorten_url(long_url):
7 short_hash = hashlib.md5(long_url.encode()).hexdigest()[:6]
8 short_url = f'[Link]
9 urls[short_url] = long_url
10 return short_url
11
12 def get_long_url(short_url):
13 return [Link](short_url, 'URL not found.')
14
15 long_url = input('Enter long URL to shorten: ')
16 short_url = shorten_url(long_url)
17 print(f'Shortened URL: {short_url}')
18

Hint: Use hashing to create unique short URLs and store the mapping between long and short URLs.

Riddle: I transform long, unwieldy URLs into short, easy-to-share links. What am I?

Short Story: Alex needed a way to shorten long URLs for sharing on social media. By creating a URL shortener, he could generate compact links for easier
distribution.

Project 47: Currency Converter

Question:
Develop a currency converter that allows users to convert amounts from one currency to another.

Code:

1
2 exchange_rates = {
3 'USD': 1.0,
4 'EUR': 0.85,
5 'JPY': 110.0,
6 }
7
8 def convert_currency(amount, from_currency, to_currency):
9 if from_currency in exchange_rates and to_currency in exchange_rates:
10 converted_amount = amount * (exchange_rates[to_currency] / exchange_rates[from_currency])
11 return converted_amount
12 else:
13 return 'Currency not supported.'
14
15 amount = float(input('Enter amount to convert: '))
16 from_currency = input('Enter from currency (USD, EUR, JPY): ')
17 to_currency = input('Enter to currency (USD, EUR, JPY): ')
18 result = convert_currency(amount, from_currency, to_currency)
19 print(f'Converted Amount: {result}')
20

Hint: Use a dictionary to store exchange rates and implement a function to convert between currencies based on user input.

Riddle: I help you convert amounts between different currencies, making it easier to handle foreign exchange. What am I?

Short Story: Maria needed to convert currencies for her travels. By creating a currency converter, she could easily convert amounts and manage her money
in different countries.

Project 48: Calendar Event Organizer

Question:
Create a calendar event organizer that allows users to add, view, and manage their events.

Code:

1
2 events = {}
3
4 def add_event(date, event):
5 if date in events:
6 events[date].append(event)
7 else:
8 events[date] = [event]
9 print(f'Event "{event}" added on {date}.')
10
11 def view_events(date):
12 if date in events:
13 for event in events[date]:
14 print(f'Event on {date}: {event}')
15 else:
16 print('No events on this date.')
17
18 while True:
19 action = input('Choose an action: add, view, or quit: ').lower()
20 if action == 'add':
21 date = input('Enter event date (YYYY-MM-DD): ')
22 event = input('Enter event description: ')
23 add_event(date, event)
24 elif action == 'view':
25 date = input('Enter date to view events (YYYY-MM-DD): ')
26 view_events(date)
27 elif action == 'quit':
28 break
29 else:
30 print('Invalid action.')
31

Hint: Use a dictionary to store events by date and provide functions to add and view events.

Riddle: I help you organize and keep track of your calendar events, letting you add and review events for specific dates. What am I?

Short Story: Jane needed a way to manage her appointments and events. By creating a calendar event organizer, she could easily add, view, and track her
important dates.

Project 49: Simple Email Sender

Question:
Write a program that can send an email with a subject and body to a specified recipient.

Code:

1
2 import smtplib
3 from [Link] import MIMEText
4 from [Link] import MIMEMultipart
5
6 def send_email(subject, body, to_email):
7 from_email = 'your_email@[Link]'
8 password = 'your_password'
9
10 msg = MIMEMultipart()
11 msg['From'] = from_email
12 msg['To'] = to_email
13 msg['Subject'] = subject
14 [Link](MIMEText(body, 'plain'))
15
16 with [Link]('[Link]', 587) as server:
17 [Link]()
18 [Link](from_email, password)
19 server.send_message(msg)
20 print('Email sent successfully.')
21
22 subject = input('Enter email subject: ')
23 body = input('Enter email body: ')
24 to_email = input('Enter recipient email address: ')
25 send_email(subject, body, to_email)
26
Hint: Use the `smtplib` library to send emails and the `email` library to create the email content.

Riddle: I send emails with a subject and body to a recipient's address, using your email account. What am I?

Short Story: Alice needed to send emails programmatically. By building a simple email sender, she could automate sending messages with a subject and
content to any recipient.

Project 50: Basic Calculator

Question:
Develop a basic calculator that performs addition, subtraction, multiplication, and division.

Code:

1
2 def calculator():
3 while True:
4 operation = input('Enter operation (+, -, *, /) or "quit" to exit: ').strip()
5 if operation == 'quit':
6 break
7 if operation in ('+', '-', '*', '/'):
8 try:
9 num1 = float(input('Enter first number: '))
10 num2 = float(input('Enter second number: '))
11
12 if operation == '+':
13 result = num1 + num2
14 elif operation == '-':
15 result = num1 - num2
16 elif operation == '*':
17 result = num1 * num2
18 elif operation == '/':
19 result = num1 / num2
20
21 print(f'Result: {result}')
22 except ValueError:
23 print('Invalid input. Please enter numbers only.')
24 except ZeroDivisionError:
25 print('Error: Division by zero is not allowed.')
26 else:
27 print('Invalid operation.')
28
29 calculator()
30

Hint: Implement basic arithmetic operations and handle errors such as invalid input and division by zero.

Riddle: I help you perform basic arithmetic operations like addition, subtraction, multiplication, and division. What am I?

Short Story: John wanted a simple way to perform calculations. By creating a basic calculator, he could easily add, subtract, multiply, and divide numbers on
the go.

Project 51: Binary Search Algorithm

Question:
Implement a binary search algorithm to find an element in a sorted list.

Code:

1
2 def binary_search(arr, target):
3 left, right = 0, len(arr) - 1
4 while left <= right:
5 mid = (left + right) // 2
6 if arr[mid] == target:
7 return mid
8 elif arr[mid] < target:
9 left = mid + 1
10 else:
11 right = mid - 1
12 return -1
13
14 arr = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
15 target = int(input('Enter number to search: '))
16 result = binary_search(arr, target)
17 print(f'Element found at index: {result}' if result != -1 else 'Element not found.')
18

Hint: The binary search algorithm divides the search interval in half repeatedly until the target value is found.

Riddle: I find elements in a sorted list by repeatedly dividing the search space in half. What am I?

Short Story: Laura needed to search for numbers in a large list quickly. By implementing a binary search algorithm, she could efficiently locate the elements
she was interested in.

Project 52: Simple Password Generator

Question:
Create a simple password generator that generates a random password with a specified length.

Code:

1
2 import random
3 import string
4
5 def generate_password(length):
6 characters = string.ascii_letters + [Link] + [Link]
7 password = ''.join([Link](characters) for i in range(length))
8 return password
9
10 length = int(input('Enter password length: '))
11 print(f'Generated Password: {generate_password(length)}')
12

Hint: Use the `random` and `string` libraries to generate a password with a mix of letters, digits, and special characters.

Riddle: I create strong, random passwords with letters, digits, and symbols to keep your accounts secure. What am I?

Short Story: Sarah wanted to generate strong passwords for her accounts. By creating a password generator, she could easily create secure passwords for her
online profiles.

Project 53: Sudoku Solver

Question:
Write a Sudoku solver that fills in the empty cells of a Sudoku puzzle.

Code:

1
2 def print_board(board):
3 for row in board:
4 print(' '.join(str(num) if num != 0 else '.' for num in row))
5
6 def is_valid(board, row, col, num):
7 for i in range(9):
8 if board[row][i] == num or board[i][col] == num:
9 return False
10 start_row, start_col = 3 * (row // 3), 3 * (col // 3)
11 for i in range(start_row, start_row + 3):
12 for j in range(start_col, start_col + 3):
13 if board[i][j] == num:
14 return False
15 return True
16
17 def solve_sudoku(board):
18 empty = find_empty_location(board)
19 if not empty:
20 return True
21 row, col = empty
22 for num in range(1, 10):
23 if is_valid(board, row, col, num):
24 board[row][col] = num
25 if solve_sudoku(board):
26 return True
27 board[row][col] = 0
28 return False
29
30 def find_empty_location(board):
31 for i in range(9):
32 for j in range(9):
33 if board[i][j] == 0:
34 return (i, j)
35 return None
36
37 # Example Sudoku Board
38 board = [
39 [5, 3, 0, 0, 7, 0, 0, 0, 0],
40 [6, 0, 0, 1, 9, 5, 0, 0, 0],
41 [0, 9, 8, 0, 0, 0, 0, 6, 0],
42 [8, 0, 0, 0, 6, 0, 0, 0, 3],
43 [4, 0, 0, 8, 0, 3, 0, 0, 1],
44 [7, 0, 0, 0, 2, 0, 0, 0, 6],
45 [0, 6, 0, 0, 0, 0, 2, 8, 0],
46 [0, 0, 0, 4, 1, 9, 0, 0, 5],
47 [0, 0, 0, 0, 8, 0, 0, 7, 9]
48 ]
49
50 if solve_sudoku(board):
51 print_board(board)
52 else:
53 print('No solution exists.')
54

Hint: Use backtracking to solve the Sudoku puzzle by trying possible numbers in each empty cell and checking if they are valid.

Riddle: I solve puzzles by filling in the empty cells with numbers, ensuring no repeats in rows, columns, or sub-grids. What am I?

Short Story: Tom enjoyed solving Sudoku puzzles but wanted an automated way to solve them. By creating a Sudoku solver, he could easily find solutions
to even the most challenging puzzles.

Project 54: Markdown to HTML Converter

Question:
Create a simple converter that converts Markdown text to HTML.

Code:

1
2 import markdown
3
4 def convert_markdown_to_html(markdown_text):
5 html = [Link](markdown_text)
6 return html
7
8 markdown_text = '''
9 # Heading 1
10 ## Heading 2
11 **Bold Text**
12 *Italic Text*
13 - List item 1
14 - List item 2
15 '''
16
17 print('Converted HTML:')
18 print(convert_markdown_to_html(markdown_text))
19
Hint: Use the `markdown` library to convert Markdown text to HTML format.

Riddle: I transform Markdown text into HTML format, enabling formatted text and structure. What am I?

Short Story: Emily wanted to publish her Markdown notes as HTML. By creating a Markdown to HTML converter, she could easily convert her formatted
text into web-ready HTML.

Project 55: Quiz Application

Question:
Build a simple quiz application that asks multiple-choice questions and keeps track of the score.

Code:

1
2 questions = {
3 "What is the capital of France?": ["a) Berlin", "b) Madrid", "c) Paris", "d) Rome"],
4 "What is 2 + 2?": ["a) 3", "b) 4", "c) 5", "d) 6"]
5 }
6
7 def ask_question(question, options):
8 print(question)
9 for option in options:
10 print(option)
11 answer = input('Enter your answer (e.g., a, b, c, d): ')
12 return answer
13
14 def run_quiz(questions):
15 score = 0
16 for question, options in [Link]():
17 answer = ask_question(question, options)
18 if answer == 'c': # assuming 'c' is the correct answer for simplicity
19 score += 1
20 print(f'Your score: {score}/{len(questions)}')
21
22 run_quiz(questions)
23

Hint: Use a dictionary to store questions and multiple-choice options, then check the user's answer to keep track of their score.

Riddle: I test your knowledge by asking questions and keeping track of your score. What am I?

Short Story: Alex wanted to create a fun quiz for his friends. By building a quiz application, he could challenge them with questions and see who scored the
highest.

Project 56: Weather Information Fetcher

Question:
Create a program that fetches and displays the current weather information for a given city using a weather API.

Code:

1
2 import requests
3
4 def get_weather(city):
5 api_key = 'your_api_key' # replace with your API key
6 url = f'[Link]
7 response = [Link](url)
8 data = [Link]()
9 if data['cod'] == 200:
10 temp = data['main']['temp']
11 description = data['weather'][0]['description']
12 return f'Temperature: {temp}°C\nDescription: {description}'
13 else:
14 return 'City not found.'
15
16 city = input('Enter city name: ')
17 print(get_weather(city))
18

Hint: Use the `requests` library to make an API call and fetch weather information. Remember to handle errors for invalid city names.

Riddle: I provide you with the current temperature and weather description for any city you choose. What am I?

Short Story: Maria wanted to check the weather before her trip. By creating a weather information fetcher, she could easily get current weather updates for
any city.

Project 57: Expense Tracker

Question:
Develop an expense tracker application that records expenses and displays a summary of total expenses.

Code:

1
2 def add_expense(expenses, amount, description):
3 [Link]({'amount': amount, 'description': description})
4
5 def display_expenses(expenses):
6 total = sum(expense['amount'] for expense in expenses)
7 print(f'Total Expenses: {total}')
8 for expense in expenses:
9 print(f"Description: {expense['description']}, Amount: {expense['amount']}")
10
11 expenses = []
12 while True:
13 amount = float(input('Enter expense amount: '))
14 description = input('Enter expense description: ')
15 add_expense(expenses, amount, description)
16 more = input('Add more expenses? (yes/no): ')
17 if [Link]() != 'yes':
18 break
19
20 display_expenses(expenses)
21

Hint: Store expenses in a list of dictionaries and calculate the total expenses using a loop.

Riddle: I help you keep track of your spending and show you how much you've spent in total. What am I?

Short Story: Lisa wanted to manage her finances better. By building an expense tracker, she could easily record and review her spending habits.

Project 58: Simple Chatbot

Question:
Build a simple chatbot that responds to user input with predefined responses.

Code:

1
2 def chatbot_response(user_input):
3 responses = {
4 'hello': 'Hi there!',
5 'how are you?': 'I am good, thank you!',
6 'bye': 'Goodbye!'
7 }
8 return [Link](user_input.lower(), 'Sorry, I did not understand that.')
9
10 def chatbot():
11 print('Chatbot: Hello! Type "bye" to exit.')
12 while True:
13 user_input = input('You: ')
14 response = chatbot_response(user_input)
15 print(f'Chatbot: {response}')
16 if user_input.lower() == 'bye':
17 break
18
19 chatbot()
20

Hint: Use a dictionary to map user inputs to predefined responses. Ensure the chatbot can handle various inputs.

Riddle: I converse with you using fixed responses and can say "hello" and "goodbye". What am I?

Short Story: Dave wanted a fun project to interact with users. By creating a simple chatbot, he could have engaging conversations with his friends.

Project 59: Email Sender

Question:
Create a program to send an email using the SMTP protocol.

Code:

1
2 import smtplib
3 from [Link] import MIMEText
4 from [Link] import MIMEMultipart
5
6 def send_email(subject, body, to_email):
7 from_email = 'your_email@[Link]'
8 password = 'your_password'
9
10 msg = MIMEMultipart()
11 msg['From'] = from_email
12 msg['To'] = to_email
13 msg['Subject'] = subject
14
15 [Link](MIMEText(body, 'plain'))
16
17 with [Link]('[Link]', 587) as server:
18 [Link]()
19 [Link](from_email, password)
20 [Link](from_email, to_email, msg.as_string())
21
22 subject = 'Test Email'
23 body = 'This is a test email sent from Python.'
24 to_email = 'recipient@[Link]'
25 send_email(subject, body, to_email)
26

Hint: Use the `smtplib` and `email` libraries to send emails. Replace placeholders with your actual email details.

Riddle: I help you send emails programmatically using Python. What am I?

Short Story: Alice needed to automate sending emails for her work. By creating an email sender program, she could easily dispatch emails with minimal
effort.

Project 60: URL Shortener

Question:
Build a simple URL shortener that converts long URLs into short, shareable links.

Code:
1
2 import hashlib
3
4 def shorten_url(url):
5 return hashlib.md5([Link]()).hexdigest()[:6]
6
7 long_url = input('Enter a URL to shorten: ')
8 short_url = shorten_url(long_url)
9 print(f'Short URL: {short_url}')
10

Hint: Use hashing to generate a short version of the URL. Ensure that the shortened URL is unique.

Riddle: I transform long URLs into short, easy-to-share links. What am I?

Short Story: Michael wanted to share links easily on social media. By creating a URL shortener, he could convert long URLs into concise, shareable links.

Project 61: Personal Diary

Question:
Create a personal diary application where users can write, read, and delete diary entries.

Code:

1
2 diary = []
3
4 def add_entry(entry):
5 [Link](entry)
6
7 def view_entries():
8 for i, entry in enumerate(diary, start=1):
9 print(f'Entry {i}: {entry}')
10
11 def delete_entry(index):
12 if 0 <= index < len(diary):
13 [Link](index)
14 else:
15 print('Invalid index.')
16
17 while True:
18 action = input('What would you like to do? (add/view/delete/quit): ')
19 if action == 'add':
20 entry = input('Write your diary entry: ')
21 add_entry(entry)
22 elif action == 'view':
23 view_entries()
24 elif action == 'delete':
25 index = int(input('Enter the index of the entry to delete: ')) - 1
26 delete_entry(index)
27 elif action == 'quit':
28 break
29 else:
30 print('Invalid action.')
31

Hint: Use a list to store diary entries and provide options to add, view, or delete entries.

Riddle: I keep your thoughts and memories, allowing you to write, read, and delete as you wish. What am I?

Short Story: Emma wanted a private space to record her thoughts. By creating a personal diary application, she could easily manage her entries and reflect
on her experiences.
Project 62: Random Password Generator

Question:
Develop a program to generate a random, secure password with a specified length.

Code:

1
2 import random
3 import string
4
5 def generate_password(length):
6 characters = string.ascii_letters + [Link] + [Link]
7 return ''.join([Link](characters) for i in range(length))
8
9 length = int(input('Enter password length: '))
10 print(f'Generated Password: {generate_password(length)}')
11

Hint: Use the `random` module and `string` constants to create a secure password with a mix of letters, digits, and punctuation.

Riddle: I create a secure, random combination of characters to protect your accounts. What am I?

Short Story: Jake wanted to ensure his online accounts were secure. By developing a random password generator, he could create strong passwords to keep
his information safe.

Project 63: Unit Converter

Question:
Build a unit converter that can convert between different units of length, weight, and temperature.

Code:

1
2 def convert_length(value, unit_from, unit_to):
3 conversion_factors = {
4 'm_to_cm': 100,
5 'cm_to_m': 0.01,
6 'km_to_m': 1000,
7 'm_to_km': 0.001
8 }
9 return value * conversion_factors.get(f'{unit_from}_to_{unit_to}', 1)
10
11 def convert_weight(value, unit_from, unit_to):
12 conversion_factors = {
13 'kg_to_g': 1000,
14 'g_to_kg': 0.001,
15 'lb_to_kg': 0.453592,
16 'kg_to_lb': 2.20462
17 }
18 return value * conversion_factors.get(f'{unit_from}_to_{unit_to}', 1)
19
20 def convert_temperature(value, unit_from, unit_to):
21 if unit_from == 'C' and unit_to == 'F':
22 return (value * 9/5) + 32
23 elif unit_from == 'F' and unit_to == 'C':
24 return (value - 32) * 5/9
25 elif unit_from == 'C' and unit_to == 'K':
26 return value + 273.15
27 elif unit_from == 'K' and unit_to == 'C':
28 return value - 273.15
29 elif unit_from == 'F' and unit_to == 'K':
30 return (value - 32) * 5/9 + 273.15
31 elif unit_from == 'K' and unit_to == 'F':
32 return (value - 273.15) * 9/5 + 32
33 else:
34 return value
35
36 value = float(input('Enter value to convert: '))
37 unit_from = input('Enter unit from (length: m, cm, km; weight: kg, g, lb; temperature: C, F, K): ')
38 unit_to = input('Enter unit to (length: m, cm, km; weight: kg, g, lb; temperature: C, F, K): ')
39
40 if unit_from in ['m', 'cm', 'km'] and unit_to in ['m', 'cm', 'km']:
41 print(f'Converted value: {convert_length(value, unit_from, unit_to)}')
42 elif unit_from in ['kg', 'g', 'lb'] and unit_to in ['kg', 'g', 'lb']:
43 print(f'Converted value: {convert_weight(value, unit_from, unit_to)}')
44 elif unit_from in ['C', 'F', 'K'] and unit_to in ['C', 'F', 'K']:
45 print(f'Converted value: {convert_temperature(value, unit_from, unit_to)}')
46 else:
47 print('Invalid units.')
48

Hint: Use dictionaries to define conversion factors for different units and provide appropriate formulas for temperature conversion.

Riddle: I transform measurements from one unit to another, be it length, weight, or temperature. What am I?

Short Story: Sarah needed a tool to convert various units for her research. By creating a unit converter, she could easily switch between different
measurements in her projects.

Project 64: Tic-Tac-Toe Game

Question:
Develop a simple text-based Tic-Tac-Toe game where two players can play against each other.

Code:

1
2 def print_board(board):
3 for row in board:
4 print(' | '.join(row))
5 print('-' * 5)
6
7 def check_winner(board, player):
8 # Check rows, columns, and diagonals
9 for i in range(3):
10 if all([cell == player for cell in board[i]]) or all([board[j][i] == player for j in range(3)]):
11 return True
12 if board[0][0] == board[1][1] == board[2][2] == player or board[0][2] == board[1][1] == board[2][0] == player:
13 return True
14 return False
15
16 def tic_tac_toe():
17 board = [[' ' for _ in range(3)] for _ in range(3)]
18 players = ['X', 'O']
19 turn = 0
20
21 while True:
22 print_board(board)
23 player = players[turn % 2]
24 row = int(input(f'Player {player}, enter row (0-2): '))
25 col = int(input(f'Player {player}, enter column (0-2): '))
26 if board[row][col] == ' ':
27 board[row][col] = player
28 if check_winner(board, player):
29 print_board(board)
30 print(f'Player {player} wins!')
31 break
32 elif all(cell != ' ' for row in board for cell in row):
33 print_board(board)
34 print('It\'s a draw!')
35 break
36 turn += 1
37 else:
38 print('Cell already occupied. Try again.')
39
40 tic_tac_toe()
41

Hint: Create a board as a list of lists and implement functions to check for a winner or a draw.

Riddle: I am a game where two players take turns marking spaces on a 3x3 grid. What am I?
Short Story: Tom and Jerry wanted to play a game during their lunch break. They created a simple Tic-Tac-Toe game to enjoy their time together and
challenge each other.

Project 65: Email Sender

Question:
Create a Python script to send an email with an attachment using the `smtplib` and `email` libraries.

Code:

1
2 import smtplib
3 from [Link] import MIMEMultipart
4 from [Link] import MIMEText
5 from [Link] import MIMEBase
6 from email import encoders
7
8 def send_email(subject, body, to_email, attachment_path=None):
9 from_email = 'your_email@[Link]'
10 password = 'your_password'
11
12 msg = MIMEMultipart()
13 msg['From'] = from_email
14 msg['To'] = to_email
15 msg['Subject'] = subject
16
17 [Link](MIMEText(body, 'plain'))
18
19 if attachment_path:
20 attachment = open(attachment_path, 'rb')
21 part = MIMEBase('application', 'octet-stream')
22 part.set_payload([Link]())
23 encoders.encode_base64(part)
24 part.add_header('Content-Disposition', f'attachment; filename= {attachment_path}')
25 [Link](part)
26
27 with [Link]('[Link]', 587) as server:
28 [Link]()
29 [Link](from_email, password)
30 server.send_message(msg)
31
32 subject = 'Test Email'
33 body = 'This is a test email with an attachment.'
34 to_email = 'recipient@[Link]'
35 attachment_path = 'path/to/[Link]'
36
37 send_email(subject, body, to_email, attachment_path)
38

Hint: Use `smtplib` to send the email and `email` to construct the email message and attachments.

Riddle: I allow you to send messages and files over the internet. What am I?

Short Story: Jessica needed to send an important document to her colleague. She developed a script to send emails with attachments efficiently, saving her
time and effort.

Project 66: URL Shortener

Question:
Create a URL shortener that converts long URLs into shorter ones and keeps track of the original URL.

Code:

1
2 import random
3 import string
4
5 url_mapping = {}
6
7 def shorten_url(original_url):
8 short_url = ''.join([Link](string.ascii_letters + [Link], k=6))
9 url_mapping[short_url] = original_url
10 return short_url
11
12 def get_original_url(short_url):
13 return url_mapping.get(short_url, 'URL not found.')
14
15 original_url = input('Enter the URL to shorten: ')
16 short_url = shorten_url(original_url)
17 print(f'Short URL: {short_url}')
18
19 short_url_input = input('Enter short URL to retrieve original URL: ')
20 print(f'Original URL: {get_original_url(short_url_input)}')
21

Hint: Use a dictionary to map short URLs to original URLs and generate random strings for short URLs.

Riddle: I turn long URLs into short, memorable links. What am I?

Short Story: Alex wanted a way to shorten URLs for easier sharing. By creating a URL shortener, he could quickly convert long links into short, easy-to-
remember ones.

Project 67: Expense Tracker

Question:
Create a simple expense tracker that allows users to input expenses and view a summary of their spending.

Code:

1
2 expenses = []
3
4 def add_expense(amount, description):
5 [Link]({'amount': amount, 'description': description})
6
7 def view_expenses():
8 total = sum(expense['amount'] for expense in expenses)
9 print('Expense Summary:')
10 for expense in expenses:
11 print(f"{expense['description']}: ${expense['amount']:.2f}")
12 print(f'Total: ${total:.2f}')
13
14 while True:
15 action = input('What would you like to do? (add/view/quit): ')
16 if action == 'add':
17 amount = float(input('Enter expense amount: '))
18 description = input('Enter expense description: ')
19 add_expense(amount, description)
20 elif action == 'view':
21 view_expenses()
22 elif action == 'quit':
23 break
24 else:
25 print('Invalid action.')
26

Hint: Use a list to store expense records and provide options to add or view them.

Riddle: I help you track and summarize your spending to manage your budget. What am I?

Short Story: Laura wanted to keep track of her expenses more effectively. She created an expense tracker to manage her spending and see how much she was
saving each month.
Project 68: Currency Converter

Question:
Build a currency converter that converts an amount from one currency to another using predefined conversion rates.

Code:

1
2 conversion_rates = {
3 'USD_to_EUR': 0.85,
4 'EUR_to_USD': 1.18,
5 'USD_to_GBP': 0.76,
6 'GBP_to_USD': 1.32
7 }
8
9 def convert_currency(amount, from_currency, to_currency):
10 key = f'{from_currency}_to_{to_currency}'
11 rate = conversion_rates.get(key)
12 if rate:
13 return amount * rate
14 else:
15 return 'Conversion rate not available.'
16
17 amount = float(input('Enter amount: '))
18 from_currency = input('Enter currency to convert from (USD, EUR, GBP): ')
19 to_currency = input('Enter currency to convert to (USD, EUR, GBP): ')
20 print(f'Converted amount: {convert_currency(amount, from_currency, to_currency)}')
21

Hint: Use a dictionary to define conversion rates between currencies and perform the conversion based on user input.

Riddle: I convert money from one currency to another, helping you understand its value in different countries. What am I?

Short Story: David often traveled abroad and needed a way to convert currencies easily. He built a currency converter to quickly translate amounts between
different currencies.

Project 69: Stopwatch

Question:
Create a simple stopwatch that can start, stop, and reset the time.

Code:

1
2 import time
3
4 def stopwatch():
5 start_time = None
6 elapsed_time = 0
7
8 while True:
9 action = input('Enter action (start/stop/reset/quit): ')
10 if action == 'start':
11 start_time = [Link]()
12 print('Stopwatch started.')
13 elif action == 'stop':
14 if start_time:
15 elapsed_time += [Link]() - start_time
16 print(f'Stopwatch stopped. Time elapsed: {elapsed_time:.2f} seconds.')
17 start_time = None
18 else:
19 print('Stopwatch is not running.')
20 elif action == 'reset':
21 start_time = None
22 elapsed_time = 0
23 print('Stopwatch reset.')
24 elif action == 'quit':
25 break
26 else:
27 print('Invalid action.')
28
29 stopwatch()
30

Hint: Use the `time` module to measure elapsed time and provide options to start, stop, or reset the stopwatch.

Riddle: I measure time intervals and can be started, stopped, or reset at your command. What am I?

Short Story: Mike wanted to keep track of his workout durations precisely. He built a stopwatch to monitor his exercise times and improve his performance.

Project 70: Alarm Clock

Question:
Create an alarm clock application that allows users to set an alarm for a specific time.

Code:

1
2 import time
3 from datetime import datetime
4
5 def set_alarm(alarm_time):
6 while True:
7 now = [Link]().strftime('%H:%M:%S')
8 if now == alarm_time:
9 print('Alarm ringing!')
10 break
11 [Link](1)
12
13 alarm_time = input('Enter alarm time in HH:MM:SS format: ')
14 set_alarm(alarm_time)
15

Hint: Use the `datetime` module to get the current time and compare it with the alarm time to trigger the alarm.

Riddle: I ring at a specific time to wake you up or remind you of an event. What am I?

Short Story: Emily needed a way to wake up on time for her early meetings. She developed an alarm clock application that would alert her at the set time.

Project 71: To-Do List

Question:
Create a to-do list application where users can add, view, and delete tasks.

Code:

1
2 tasks = []
3
4 def add_task(task):
5 [Link](task)
6
7 def view_tasks():
8 if tasks:
9 print('To-Do List:')
10 for i, task in enumerate(tasks, start=1):
11 print(f'{i}. {task}')
12 else:
13 print('No tasks in the list.')
14
15 def delete_task(index):
16 if 0 <= index < len(tasks):
17 [Link](index)
18 else:
19 print('Invalid index.')
20
21 while True:
22 action = input('What would you like to do? (add/view/delete/quit): ')
23 if action == 'add':
24 task = input('Enter task: ')
25 add_task(task)
26 elif action == 'view':
27 view_tasks()
28 elif action == 'delete':
29 index = int(input('Enter the index of the task to delete: ')) - 1
30 delete_task(index)
31 elif action == 'quit':
32 break
33 else:
34 print('Invalid action.')
35

Hint: Use a list to store tasks and provide options to add, view, or delete them from the list.

Riddle: I help you organize and manage tasks that need to be completed. What am I?

Short Story: John wanted a way to keep track of his daily tasks. He created a to-do list application to manage his responsibilities and stay organized.

Project 72: Simple Calculator

Question:
Develop a basic calculator that can perform addition, subtraction, multiplication, and division.

Code:

1
2 def calculator():
3 while True:
4 operation = input('Enter operation (+, -, *, /) or quit to exit: ')
5 if operation == 'quit':
6 break
7 if operation in ['+', '-', '*', '/']:
8 num1 = float(input('Enter first number: '))
9 num2 = float(input('Enter second number: '))
10 if operation == '+':
11 print(f'Result: {num1 + num2}')
12 elif operation == '-':
13 print(f'Result: {num1 - num2}')
14 elif operation == '*':
15 print(f'Result: {num1 * num2}')
16 elif operation == '/':
17 if num2 != 0:
18 print(f'Result: {num1 / num2}')
19 else:
20 print('Error: Division by zero.')
21 else:
22 print('Invalid operation.')
23
24 calculator()
25

Hint: Use conditional statements to perform calculations based on user input and handle division by zero errors.

Riddle: I perform arithmetic operations like addition and multiplication. What am I?

Short Story: Sarah wanted a simple tool for performing quick calculations. She built a basic calculator to help with her everyday math problems.

Project 73: Weather App

Question:
Create a weather application that fetches and displays the current weather for a given location using an API.

Code:

1
2 import requests
3
4 def get_weather(location):
5 api_key = 'your_api_key'
6 url = f'[Link]
7 response = [Link](url)
8 data = [Link]()
9 if 'error' in data:
10 return data['error']['message']
11 else:
12 temp = data['current']['temp_c']
13 condition = data['current']['condition']['text']
14 return f'Temperature: {temp}°C, Condition: {condition}'
15
16 location = input('Enter location: ')
17 print(get_weather(location))
18

Hint: Use the `requests` library to fetch weather data from an API and parse the JSON response.

Riddle: I provide current weather information for any location when asked. What am I?

Short Story: Lisa wanted to know the weather conditions before planning her day. She built a weather app that retrieves and displays the current weather for
any location.

Project 74: Quiz Game

Question:
Design a quiz game where users answer multiple-choice questions and get a score at the end.

Code:

1
2 questions = [
3 {'question': 'What is the capital of France?', 'options': ['A. Paris', 'B. London', 'C. Berlin'], 'answer': 'A'},
4 {'question': 'What is 2 + 2?', 'options': ['A. 3', 'B. 4', 'C. 5'], 'answer': 'B'}
5 ]
6
7 def quiz_game():
8 score = 0
9 for q in questions:
10 print(q['question'])
11 for option in q['options']:
12 print(option)
13 answer = input('Your answer (A, B, C): ').strip().upper()
14 if answer == q['answer']:
15 score += 1
16 print(f'Your score: {score}/{len(questions)}')
17
18 quiz_game()
19

Hint: Use a list of dictionaries to store questions, options, and correct answers. Iterate through the list to present questions and check answers.

Riddle: I ask you questions and keep track of your answers to calculate a score. What am I?

Short Story: James enjoyed testing his knowledge with quizzes. He developed a quiz game to challenge his friends and see who scored the highest.

Project 75: Simple Chatbot

Question:
Build a basic chatbot that can respond to a few predefined questions.

Code:

1
2 responses = {
3 'hi': 'Hello!',
4 'how are you?': 'I am good, thank you!',
5 'bye': 'Goodbye!'
6 }
7
8 def chatbot():
9 while True:
10 user_input = input('You: ').lower()
11 if user_input in responses:
12 print('Bot:', responses[user_input])
13 elif user_input == 'quit':
14 break
15 else:
16 print('Bot: I do not understand that.')
17
18 chatbot()
19

Hint: Use a dictionary to store predefined responses and match user input to provide appropriate replies.

Riddle: I can hold simple conversations and answer specific questions based on preset responses. What am I?

Short Story: Sarah wanted a fun way to interact with her computer. She built a simple chatbot to have quick conversations and provide basic responses.

Project 76: Fibonacci Sequence Generator

Question:
Create a program that generates the Fibonacci sequence up to a given number.

Code:

1
2 def fibonacci(n):
3 a, b = 0, 1
4 while a < n:
5 print(a, end=' ')
6 a, b = b, a + b
7 print()
8
9 limit = int(input('Enter the upper limit for Fibonacci sequence: '))
10 fibonacci(limit)
11

Hint: Use a loop to generate and print the Fibonacci sequence up to the specified limit.

Riddle: I produce a sequence where each number is the sum of the two preceding ones. What am I?

Short Story: Oliver wanted to explore mathematical sequences. He created a Fibonacci sequence generator to see how numbers in the sequence grow.

Project 77: Palindrome Checker

Question:
Develop a function that checks if a given string is a palindrome.

Code:

1
2 def is_palindrome(s):
3 return s == s[::-1]
4
5 string = input('Enter a string: ')
6 if is_palindrome(string):
7 print('The string is a palindrome.')
8 else:
9 print('The string is not a palindrome.')
10

Hint: Use string slicing to reverse the string and compare it with the original.
Riddle: I am a word or phrase that reads the same backward as forward. What am I?

Short Story: Emma was intrigued by palindromes and wanted to check if a string was one. She wrote a function to verify if a given string is a palindrome.

Project 78: Prime Number Checker

Question:
Create a program to check if a given number is a prime number.

Code:

1
2 def is_prime(n):
3 if n <= 1:
4 return False
5 for i in range(2, int(n ** 0.5) + 1):
6 if n % i == 0:
7 return False
8 return True
9
10 number = int(input('Enter a number: '))
11 if is_prime(number):
12 print('The number is a prime number.')
13 else:
14 print('The number is not a prime number.')
15

Hint: Check divisibility up to the square root of the number to determine if it is prime.

Riddle: I am a number greater than 1 that cannot be divided evenly by any number other than 1 and itself. What am I?

Short Story: Lucas was curious about prime numbers and wanted to identify them easily. He developed a prime number checker to find out if numbers were
prime.

Project 79: Word Frequency Counter

Question:
Write a program that counts the frequency of each word in a given text.

Code:

1
2 from collections import Counter
3
4 def word_frequency(text):
5 words = [Link]()
6 return Counter(words)
7
8 text = input('Enter text: ')
9 freq = word_frequency(text)
10 for word, count in [Link]():
11 print(f'{word}: {count}')
12

Hint: Use the `Counter` class from the `collections` module to count word frequencies.

Riddle: I tell you how many times each word appears in a text. What am I?

Short Story: Mia needed to analyze text data for her project. She wrote a program to count the frequency of each word in a text to understand its content
better.
Project 80: Simple To-Do List

Question:
Create a simple to-do list application where users can add, view, and remove tasks.

Code:

1
2 tasks = []
3
4 def display_tasks():
5 if tasks:
6 for idx, task in enumerate(tasks, 1):
7 print(f'{idx}. {task}')
8 else:
9 print('No tasks.')
10
11 def add_task(task):
12 [Link](task)
13
14 def remove_task(index):
15 if 0 < index <= len(tasks):
16 [Link](index - 1)
17 else:
18 print('Invalid task number.')
19
20 while True:
21 print('1. View tasks')
22 print('2. Add task')
23 print('3. Remove task')
24 print('4. Exit')
25 choice = input('Enter your choice: ')
26
27 if choice == '1':
28 display_tasks()
29 elif choice == '2':
30 task = input('Enter task: ')
31 add_task(task)
32 elif choice == '3':
33 index = int(input('Enter task number to remove: '))
34 remove_task(index)
35 elif choice == '4':
36 break
37 else:
38 print('Invalid choice.')
39

Hint: Use a list to store tasks and provide options to view, add, and remove tasks.

Riddle: I help you keep track of your tasks and manage them effectively. What am I?

Short Story: Alex wanted a simple way to manage his daily tasks. He developed a to-do list application to organize and keep track of his tasks easily.

Project 81: Simple Bank Account

Question:
Create a simple bank account simulation that allows users to deposit, withdraw, and check their balance.

Code:

1
2 class BankAccount:
3 def __init__(self):
4 [Link] = 0
5
6 def deposit(self, amount):
7 [Link] += amount
8 print(f'Deposited: ${amount}')
9
10 def withdraw(self, amount):
11 if amount <= [Link]:
12 [Link] -= amount
13 print(f'Withdrew: ${amount}')
14 else:
15 print('Insufficient funds.')
16
17 def check_balance(self):
18 print(f'Current balance: ${[Link]}')
19
20 account = BankAccount()
21 while True:
22 print('1. Deposit')
23 print('2. Withdraw')
24 print('3. Check balance')
25 print('4. Exit')
26 choice = input('Enter your choice: ')
27
28 if choice == '1':
29 amount = float(input('Enter amount to deposit: '))
30 [Link](amount)
31 elif choice == '2':
32 amount = float(input('Enter amount to withdraw: '))
33 [Link](amount)
34 elif choice == '3':
35 account.check_balance()
36 elif choice == '4':
37 break
38 else:
39 print('Invalid choice.')
40

Hint: Create a class to manage bank account operations and allow users to interact with it through a menu.

Riddle: I manage your money by keeping track of deposits, withdrawals, and balance. What am I?

Short Story: Mia wanted to manage her finances better. She created a simple bank account simulation to track her deposits and withdrawals.

Project 82: Basic Todo List with File I/O

Question:
Develop a to-do list application that saves and loads tasks from a file.

Code:

1
2 def load_tasks():
3 try:
4 with open('[Link]', 'r') as file:
5 return [[Link]() for line in file]
6 except FileNotFoundError:
7 return []
8
9 def save_tasks(tasks):
10 with open('[Link]', 'w') as file:
11 for task in tasks:
12 [Link](task + '\n')
13
14 tasks = load_tasks()
15
16 while True:
17 print('1. View tasks')
18 print('2. Add task')
19 print('3. Remove task')
20 print('4. Exit')
21 choice = input('Enter your choice: ')
22
23 if choice == '1':
24 if tasks:
25 for idx, task in enumerate(tasks, 1):
26 print(f'{idx}. {task}')
27 else:
28 print('No tasks.')
29 elif choice == '2':
30 task = input('Enter task: ')
31 [Link](task)
32 save_tasks(tasks)
33 elif choice == '3':
34 index = int(input('Enter task number to remove: '))
35 if 0 < index <= len(tasks):
36 [Link](index - 1)
37 save_tasks(tasks)
38 else:
39 print('Invalid task number.')
40 elif choice == '4':
41 break
42 else:
43 print('Invalid choice.')
44

Hint: Use file I/O to save and load tasks, so they persist between program runs.

Riddle: I help you keep track of tasks and remember them even after you close the program. What am I?

Short Story: Emma wanted her to-do list to be persistent. She created a to-do list application that saves tasks to a file so they are available the next time she
opens the app.

Project 83: Simple Budget Tracker

Question:
Create a budget tracker that allows users to record income and expenses and see their current balance.

Code:

1
2 class BudgetTracker:
3 def __init__(self):
4 [Link] = 0
5
6 def add_income(self, amount):
7 [Link] += amount
8 print(f'Added income: ${amount}')
9
10 def add_expense(self, amount):
11 [Link] -= amount
12 print(f'Added expense: ${amount}')
13
14 def check_balance(self):
15 print(f'Current balance: ${[Link]}')
16
17 tracker = BudgetTracker()
18 while True:
19 print('1. Add income')
20 print('2. Add expense')
21 print('3. Check balance')
22 print('4. Exit')
23 choice = input('Enter your choice: ')
24
25 if choice == '1':
26 amount = float(input('Enter income amount: '))
27 tracker.add_income(amount)
28 elif choice == '2':
29 amount = float(input('Enter expense amount: '))
30 tracker.add_expense(amount)
31 elif choice == '3':
32 tracker.check_balance()
33 elif choice == '4':
34 break
35 else:
36 print('Invalid choice.')
37

Hint: Use a class to manage income and expenses and keep track of the balance.

Riddle: I help you manage your finances by tracking your income and expenses. What am I?

Short Story: John wanted to keep track of his spending and saving. He built a budget tracker to monitor his finances and manage his money effectively.
Project 84: Number Guessing Game

Question:
Create a number guessing game where the user tries to guess a randomly generated number within a certain number of attempts.

Code:

1
2 import random
3
4 def number_guessing_game():
5 number = [Link](1, 100)
6 attempts = 10
7
8 while attempts > 0:
9 guess = int(input('Guess a number between 1 and 100: '))
10 if guess < number:
11 print('Too low!')
12 elif guess > number:
13 print('Too high!')
14 else:
15 print('Congratulations! You guessed the number.')
16 return
17 attempts -= 1
18 print(f'Attempts remaining: {attempts}')
19
20 print('Sorry, you ran out of attempts. The number was', number)
21
22 number_guessing_game()
23

Hint: Use the `random` module to generate a random number and provide feedback based on the user's guesses.

Riddle: I challenge you to guess a hidden number within a limited number of tries. What am I?

Short Story: Jane wanted a fun game to play. She created a number guessing game where players try to guess a randomly generated number before running
out of attempts.

Project 85: Basic Contact Book

Question:
Develop a contact book that allows users to add, view, and delete contacts.

Code:

1
2 contacts = {}
3
4 def add_contact(name, phone):
5 contacts[name] = phone
6
7 def view_contacts():
8 if contacts:
9 for name, phone in [Link]():
10 print(f'{name}: {phone}')
11 else:
12 print('No contacts.')
13
14 def delete_contact(name):
15 if name in contacts:
16 del contacts[name]
17 print(f'Contact {name} deleted.')
18 else:
19 print('Contact not found.')
20
21 while True:
22 print('1. View contacts')
23 print('2. Add contact')
24 print('3. Delete contact')
25 print('4. Exit')
26 choice = input('Enter your choice: ')
27
28 if choice == '1':
29 view_contacts()
30 elif choice == '2':
31 name = input('Enter contact name: ')
32 phone = input('Enter contact phone number: ')
33 add_contact(name, phone)
34 elif choice == '3':
35 name = input('Enter contact name to delete: ')
36 delete_contact(name)
37 elif choice == '4':
38 break
39 else:
40 print('Invalid choice.')
41

Hint: Use a dictionary to store contact names and phone numbers, and provide options to manage the contact list.

Riddle: I help you keep track of people’s names and phone numbers. What am I?

Short Story: Tom wanted an easy way to manage his contacts. He built a contact book application to add, view, and delete contacts as needed.

Project 86: Currency Converter

Question:
Create a currency converter that converts an amount from one currency to another using a fixed conversion rate.

Code:

1
2 def convert_currency(amount, rate):
3 return amount * rate
4
5 rate = 1.1 # Example conversion rate from USD to EUR
6 amount = float(input('Enter amount in USD: '))
7 converted_amount = convert_currency(amount, rate)
8 print(f'Amount in EUR: {converted_amount:.2f}')
9

Hint: Define a conversion rate and use it to convert the amount from one currency to another.

Riddle: I transform money from one currency to another using a conversion rate. What am I?

Short Story: Alice wanted to convert her US dollars to euros. She created a currency converter to easily perform the conversion based on a fixed rate.

Project 87: Simple Calculator

Question:
Build a simple calculator that can perform addition, subtraction, multiplication, and division.

Code:

1
2 def calculator():
3 while True:
4 print('1. Addition')
5 print('2. Subtraction')
6 print('3. Multiplication')
7 print('4. Division')
8 print('5. Exit')
9 choice = input('Enter your choice: ')
10
11 if choice == '5':
12 break
13
14 num1 = float(input('Enter first number: '))
15 num2 = float(input('Enter second number: '))
16
17 if choice == '1':
18 print(f'Result: {num1 + num2}')
19 elif choice == '2':
20 print(f'Result: {num1 - num2}')
21 elif choice == '3':
22 print(f'Result: {num1 * num2}')
23 elif choice == '4':
24 if num2 != 0:
25 print(f'Result: {num1 / num2}')
26 else:
27 print('Error: Division by zero.')
28 else:
29 print('Invalid choice.')
30
31 calculator()
32

Hint: Use conditional statements to perform the chosen arithmetic operation based on user input.

Riddle: I can add, subtract, multiply, and divide numbers. What am I?

Short Story: Sarah needed a tool for basic arithmetic operations. She built a simple calculator to perform addition, subtraction, multiplication, and division.

Project 88: Prime Number Checker

Question:
Create a program to check if a number is prime or not.

Code:

1
2 def is_prime(n):
3 if n <= 1:
4 return False
5 for i in range(2, int(n ** 0.5) + 1):
6 if n % i == 0:
7 return False
8 return True
9
10 number = int(input('Enter a number: '))
11 if is_prime(number):
12 print(f'{number} is a prime number.')
13 else:
14 print(f'{number} is not a prime number.')
15

Hint: A prime number is only divisible by 1 and itself. Use a loop to check divisibility.

Riddle: I can tell you whether a number is only divisible by itself and 1. What am I?

Short Story: David was interested in prime numbers. He wrote a program to check if a given number was prime or not for his mathematical studies.

Project 89: Temperature Converter

Question:
Develop a temperature converter that can convert between Celsius and Fahrenheit.

Code:

1
2 def celsius_to_fahrenheit(celsius):
3 return (celsius * 9/5) + 32
4
5 def fahrenheit_to_celsius(fahrenheit):
6 return (fahrenheit - 32) * 5/9
7
8 temp = float(input('Enter temperature: '))
9 unit = input('Enter unit (C for Celsius, F for Fahrenheit): ')
10
11 if [Link]() == 'C':
12 print(f'Temperature in Fahrenheit: {celsius_to_fahrenheit(temp):.2f}')
13 elif [Link]() == 'F':
14 print(f'Temperature in Celsius: {fahrenheit_to_celsius(temp):.2f}')
15 else:
16 print('Invalid unit.')
17

Hint: Use the conversion formulas for Celsius to Fahrenheit and vice versa to perform the conversion.

Riddle: I can convert temperatures between Celsius and Fahrenheit. What am I?

Short Story: Lisa wanted to convert temperatures for her weather report. She built a temperature converter to switch between Celsius and Fahrenheit easily.

Project 90: Simple Quiz Game

Question:
Create a simple quiz game that asks the user a series of questions and provides feedback on their answers.

Code:

1
2 questions = {
3 'What is the capital of France?': 'Paris',
4 'What is 2 + 2?': '4',
5 'What is the largest planet in our solar system?': 'Jupiter'
6 }
7
8 score = 0
9
10 for question, answer in [Link]():
11 user_answer = input(question + ' ')
12 if user_answer.lower() == [Link]():
13 print('Correct!')
14 score += 1
15 else:
16 print('Wrong! The correct answer is', answer)
17
18 print(f'Your final score is {score}/{len(questions)}')
19

Hint: Use a dictionary to store questions and answers, and compare user input with the correct answers.

Riddle: I test your knowledge with questions and tell you how many you got right. What am I?

Short Story: Emily wanted to create a fun quiz game. She designed a simple quiz game that asks questions and keeps track of the score based on the user's
answers.

Project 91: Simple Stopwatch

Question:
Build a simple stopwatch that can start, stop, and reset the timer.

Code:

1
2 import time
3
4 def stopwatch():
5 start_time = None
6 while True:
7 print('1. Start')
8 print('2. Stop')
9 print('3. Reset')
10 print('4. Exit')
11 choice = input('Enter your choice: ')
12
13 if choice == '1':
14 if start_time is None:
15 start_time = [Link]()
16 print('Stopwatch started.')
17 else:
18 print('Stopwatch is already running.')
19 elif choice == '2':
20 if start_time is not None:
21 elapsed_time = [Link]() - start_time
22 print(f'Stopwatch stopped. Time elapsed: {elapsed_time:.2f} seconds')
23 start_time = None
24 else:
25 print('Stopwatch is not running.')
26 elif choice == '3':
27 start_time = None
28 print('Stopwatch reset.')
29 elif choice == '4':
30 break
31 else:
32 print('Invalid choice.')
33
34 stopwatch()
35

Hint: Use the `time` module to measure elapsed time and provide options to start, stop, and reset the stopwatch.

Riddle: I measure how much time has passed and can be started, stopped, or reset. What am I?

Short Story: Lucas wanted a tool to track time during his experiments. He built a simple stopwatch that could start, stop, and reset to measure elapsed time
accurately.

Project 92: Basic To-Do List with Persistence

Question:
Create a to-do list application that allows adding, viewing, and removing tasks, and saves the list to a file so it persists between runs.

Code:

1
2 import json
3
4 def load_tasks(filename):
5 try:
6 with open(filename, 'r') as file:
7 return [Link](file)
8 except FileNotFoundError:
9 return []
10
11 def save_tasks(filename, tasks):
12 with open(filename, 'w') as file:
13 [Link](tasks, file)
14
15 def todo_list():
16 tasks = load_tasks('[Link]')
17 while True:
18 print('1. Add Task')
19 print('2. View Tasks')
20 print('3. Remove Task')
21 print('4. Exit')
22 choice = input('Enter your choice: ')
23
24 if choice == '1':
25 task = input('Enter task: ')
26 [Link](task)
27 save_tasks('[Link]', tasks)
28 elif choice == '2':
29 if tasks:
30 for i, task in enumerate(tasks, 1):
31 print(f'{i}. {task}')
32 else:
33 print('No tasks to display.')
34 elif choice == '3':
35 if tasks:
36 for i, task in enumerate(tasks, 1):
37 print(f'{i}. {task}')
38 task_num = int(input('Enter task number to remove: '))
39 if 1 <= task_num <= len(tasks):
40 [Link](task_num - 1)
41 save_tasks('[Link]', tasks)
42 else:
43 print('Invalid task number.')
44 else:
45 print('No tasks to remove.')
46 elif choice == '4':
47 break
48 else:
49 print('Invalid choice.')
50
51 todo_list()
52

Hint: Use JSON to store tasks so that the to-do list persists even after the program is closed.

Riddle: I keep track of tasks and save them so that they persist between sessions. What am I?

Short Story: Michael needed a way to manage his daily tasks. He developed a to-do list application that saved tasks to a file so he could keep track of them
even after closing the app.

Project 93: Simple Number Guessing Game

Question:
Create a number guessing game where the user has to guess a randomly generated number within a certain range.

Code:

1
2 import random
3
4 def number_guessing_game():
5 number_to_guess = [Link](1, 100)
6 attempts = 0
7
8 while True:
9 guess = int(input('Guess the number (between 1 and 100): '))
10 attempts += 1
11
12 if guess < number_to_guess:
13 print('Too low!')
14 elif guess > number_to_guess:
15 print('Too high!')
16 else:
17 print(f'Congratulations! You guessed the number in {attempts} attempts.')
18 break
19
20 number_guessing_game()
21

Hint: Use the `random` module to generate a random number and compare user guesses with the generated number.

Riddle: I generate a random number and let you guess it, providing feedback on whether your guess is too high or too low. What am I?

Short Story: Emma wanted a fun way to challenge her friends. She created a number guessing game where users guessed a random number, and she
provided hints until they got it right.
Project 94: Simple File Reader

Question:
Write a program to read the contents of a file and display them to the user.

Code:

1
2 def read_file(filename):
3 try:
4 with open(filename, 'r') as file:
5 content = [Link]()
6 print(content)
7 except FileNotFoundError:
8 print('File not found.')
9
10 filename = input('Enter the filename: ')
11 read_file(filename)
12

Hint: Use the `open` function to read the contents of a file and handle exceptions if the file does not exist.

Riddle: I read the content of a file and display it to you. What am I?

Short Story: Liam needed to view the contents of a file for his project. He wrote a simple file reader to open and display file contents to make his work
easier.

Project 95: Basic Unit Converter

Question:
Create a unit converter that can convert between different units of length (e.g., meters to feet, centimeters to inches).

Code:

1
2 def meters_to_feet(meters):
3 return meters * 3.28084
4
5 def centimeters_to_inches(centimeters):
6 return centimeters / 2.54
7
8 length = float(input('Enter length: '))
9 unit = input('Enter unit (M for meters, CM for centimeters): ')
10
11 if [Link]() == 'M':
12 print(f'Length in feet: {meters_to_feet(length):.2f}')
13 elif [Link]() == 'CM':
14 print(f'Length in inches: {centimeters_to_inches(length):.2f}')
15 else:
16 print('Invalid unit.')
17

Hint: Implement conversion functions for different units and allow users to choose the unit they want to convert from.

Riddle: I convert measurements from one unit to another, such as meters to feet. What am I?

Short Story: Jack wanted to convert lengths between different units. He created a unit converter that could easily switch between meters, feet, centimeters,
and inches.
Project 96: Simple Expense Tracker

Question:
Develop a basic expense tracker that allows users to add and view expenses, and saves the data to a file.

Code:

1
2 import json
3
4 def load_expenses(filename):
5 try:
6 with open(filename, 'r') as file:
7 return [Link](file)
8 except FileNotFoundError:
9 return []
10
11 def save_expenses(filename, expenses):
12 with open(filename, 'w') as file:
13 [Link](expenses, file)
14
15 def expense_tracker():
16 expenses = load_expenses('[Link]')
17 while True:
18 print('1. Add Expense')
19 print('2. View Expenses')
20 print('3. Exit')
21 choice = input('Enter your choice: ')
22
23 if choice == '1':
24 name = input('Enter expense name: ')
25 amount = float(input('Enter amount: '))
26 [Link]({'name': name, 'amount': amount})
27 save_expenses('[Link]', expenses)
28 elif choice == '2':
29 if expenses:
30 for expense in expenses:
31 print(f'{expense["name"]}: ${expense["amount"]:.2f}')
32 else:
33 print('No expenses to display.')
34 elif choice == '3':
35 break
36 else:
37 print('Invalid choice.')
38
39 expense_tracker()
40

Hint: Use JSON to store and load expense data, and provide options to add and view expenses.

Riddle: I track and record expenses and save the data to a file. What am I?

Short Story: Nora needed a way to manage her spending. She created a simple expense tracker that allowed her to add and view expenses, keeping track of
her spending efficiently.

Project 97: Simple Interest Calculator

Question:
Write a program to calculate simple interest given the principal amount, rate of interest, and time period.

Code:
1
2 def calculate_simple_interest(principal, rate, time):
3 return principal * rate * time / 100
4
5 principal = float(input('Enter principal amount: '))
6 rate = float(input('Enter rate of interest: '))
7 time = float(input('Enter time period (in years): '))
8
9 interest = calculate_simple_interest(principal, rate, time)
10 print(f'Simple Interest: ${interest:.2f}')
11

Hint: Use the formula for simple interest: `principal * rate * time / 100` to perform the calculation.

Riddle: I calculate the interest earned on a principal amount over a period of time. What am I?

Short Story: Liam wanted to know how much interest he would earn on his savings. He wrote a simple interest calculator to quickly compute the interest
based on his principal, interest rate, and time.

Project 98: Basic Temperature Converter

Question:
Create a temperature converter that converts between Celsius and Fahrenheit.

Code:

1
2 def celsius_to_fahrenheit(celsius):
3 return (celsius * 9/5) + 32
4
5 def fahrenheit_to_celsius(fahrenheit):
6 return (fahrenheit - 32) * 5/9
7
8 temperature = float(input('Enter temperature: '))
9 unit = input('Enter unit (C for Celsius, F for Fahrenheit): ')
10
11 if [Link]() == 'C':
12 print(f'Temperature in Fahrenheit: {celsius_to_fahrenheit(temperature):.2f}')
13 elif [Link]() == 'F':
14 print(f'Temperature in Celsius: {fahrenheit_to_celsius(temperature):.2f}')
15 else:
16 print('Invalid unit.')
17

Hint: Implement conversion functions for Celsius and Fahrenheit, and allow users to choose the unit they want to convert from.

Riddle: I convert temperatures between Celsius and Fahrenheit. What am I?

Short Story: Sarah needed to convert temperatures for her weather research. She created a temperature converter that allowed her to switch between Celsius
and Fahrenheit easily.

Project 99: Simple Calculator with GUI

Question:
Develop a simple calculator with a graphical user interface (GUI) that performs basic arithmetic operations like addition, subtraction, multiplication, and
division.

Code:

1
2 import tkinter as tk
3
4 def add():
5 try:
6 num1 = float([Link]())
7 num2 = float([Link]())
8 [Link](num1 + num2)
9 except ValueError:
10 [Link]('Error')
11
12 def subtract():
13 try:
14 num1 = float([Link]())
15 num2 = float([Link]())
16 [Link](num1 - num2)
17 except ValueError:
18 [Link]('Error')
19
20 def multiply():
21 try:
22 num1 = float([Link]())
23 num2 = float([Link]())
24 [Link](num1 * num2)
25 except ValueError:
26 [Link]('Error')
27
28 def divide():
29 try:
30 num1 = float([Link]())
31 num2 = float([Link]())
32 if num2 != 0:
33 [Link](num1 / num2)
34 else:
35 [Link]('Error')
36 except ValueError:
37 [Link]('Error')
38
39 app = [Link]()
40 [Link]('Simple Calculator')
41
42 entry1 = [Link](app)
43 [Link]()
44
45 entry2 = [Link](app)
46 [Link]()
47
48 result = [Link]()
49 result_label = [Link](app, textvariable=result)
50 result_label.pack()
51
52 [Link](app, text='+', command=add).pack()
53 [Link](app, text='-', command=subtract).pack()
54 [Link](app, text='*', command=multiply).pack()
55 [Link](app, text='/', command=divide).pack()
56
57 [Link]()
58

Hint: Use the `tkinter` library to create the GUI and handle basic arithmetic operations.

Riddle: I perform basic arithmetic operations and display the results in a graphical interface. What am I?

Short Story: Jessica wanted to make basic calculations easier. She built a simple calculator with a GUI using tkinter that allowed her to add, subtract,
multiply, and divide numbers with ease.

Project 100: Simple Contact Book

Question:
Create a contact book application that allows users to add, view, and search for contacts, and saves the contacts to a file.

Code:

1
2 import json
3
4 def load_contacts(filename):
5 try:
6 with open(filename, 'r') as file:
7 return [Link](file)
8 except FileNotFoundError:
9 return []
10
11 def save_contacts(filename, contacts):
12 with open(filename, 'w') as file:
13 [Link](contacts, file)
14
15 def contact_book():
16 contacts = load_contacts('[Link]')
17 while True:
18 print('1. Add Contact')
19 print('2. View Contacts')
20 print('3. Search Contact')
21 print('4. Exit')
22 choice = input('Enter your choice: ')
23
24 if choice == '1':
25 name = input('Enter contact name: ')
26 phone = input('Enter phone number: ')
27 [Link]({'name': name, 'phone': phone})
28 save_contacts('[Link]', contacts)
29 elif choice == '2':
30 if contacts:
31 for contact in contacts:
32 print(f'{contact["name"]}: {contact["phone"]}')
33 else:
34 print('No contacts to display.')
35 elif choice == '3':
36 search_name = input('Enter name to search: ')
37 found = False
38 for contact in contacts:
39 if contact['name'].lower() == search_name.lower():
40 print(f'{contact["name"]}: {contact["phone"]}')
41 found = True
42 break
43 if not found:
44 print('Contact not found.')
45 elif choice == '4':
46 break
47 else:
48 print('Invalid choice.')
49
50 contact_book()
51

Hint: Store contacts in a JSON file to persist data, and provide options to add, view, and search for contacts.

Riddle: I keep track of names and phone numbers, allowing you to add, view, and search for contacts. What am I?

Short Story: Olivia wanted an easy way to manage her contacts. She developed a simple contact book application that saved contact details to a file and
allowed her to search for contacts quickly.

A Note to My Readers
Hello and welcome! I'm so glad you're here, exploring the world of technology, learning, and growth. Whether you're just starting out or looking to expand
your knowledge, this platform is here to help guide you through every step of the way. My mission is to make learning engaging, practical, and accessible for
everyone. I hope you find the resources here useful and inspiring as you embark on your own learning journey.

Thank you for being part of this community. Let's continue to learn, create, and grow together!

Best regards,
Anshu Goyal

You might also like