Python Mastery for Educators Guide
Python Mastery for Educators Guide
By Anshu Goyal
TABLE OF CONTENT
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.
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.
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.
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:
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.
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.
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.
Game developer
Web designer
Python developer
Full-stack developer
Data engineer
DevOps engineer
Software engineer
Many more other roles
Characteristics of Python
Following are important characteristics of Python Programming −
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 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 −
To obtain the complete Zen of Python document, type import this in the Python Shell −
1 >>>import this
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
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 .
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
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.
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.
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.
Easy to Learn
Dynamically Typed
Interpreter Based
Interactive
Multi-paradigm
Standard Library
GUI Applications
Database Connectivity
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.
NumPy
Pandas
Matplotlib
Tkinter
Math
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.
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 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 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.
Web development
Data analysis and machine learning
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 −
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 −
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 −
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.
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.
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.
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.
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.
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".
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
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
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
For Windows OS, open the command prompt terminal (CMD) and run the program as shown below −
C:\>python [Link]
$ python3 [Link]
1 Hello World
Open Compiler
#!/usr/bin/python3
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]
1 Hello World
FAQs
print() method
[Link]() method by importing the sys module
Using python-f string
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
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.
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.
Many software products like Maya embed Python API for writing automation scripts (something similar to Excel micros).
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:
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.
Save the following lines as [Link] , with the use of any text editor such as vim on Linux or Notepad on Windows.
Open Compiler
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.
Open Compiler
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.
Open Compiler
#! /usr/bin/python3.11
$ chmod +x [Link]
You can now execute the script directly, without using it as a command-line argument.
$ ./[Link]
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 −
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?.
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
Directory of F:\Python311
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 is available on a wide variety of platforms including Linux and Mac OS X. Let's understand how to set up our Python environment.
Python has also been ported to the Java and .NET virtual machines
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.
$ 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.
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.
To install the latest Python 3.11 version, enter the following command in the terminal −
>>>
This installs Python at standard location /usr/local/bin and its libraries at /usr/local/lib/pythonXX where XX is the version of Python.
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.
([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.
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.
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 −
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.
1 $python # Unix/Linux
2 or
3 python% # Unix/Linux
4 or
5 C:> python # Windows/DOS
3 -SDo not run import site to look for Python paths on startup.
5 -Xdisable class-based built-in exceptions (just use strings); obsolete starting with version 1.6.
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
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]
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.
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.
$ 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 −
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
We assume that you have Python interpreter path set in PATH variable. Now, let's try to run this program as follows −
$ python3 [Link]
1 Hello, World!
Let us try another way to execute a Python script. Here is the modified [Link] file −
Open Compiler
#!/usr/bin/python3
We assume that you have Python interpreter available in /usr/bin directory. Now, try to run this program as follows −
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.
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.
and as assert
global if import
in is lambda
and as assert
or pass raise
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")
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 −
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)
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
1 Hello, World!
You can type a comment on the same line after a statement or expression −
# 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.
#!/usr/bin/python
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.
Open Compiler
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
$ 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 −
Open Compiler
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
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)
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
x = "Zara"
y = 10
z = 10.10
print(type(x))
print(type(y))
print(type(z))
1 <class 'str'>
2 <class 'int'>
3 <class 'float'>
Example
This example demonstrates case sensitivity of variables.
Open Compiler
Open Compiler
age = 20
Age = 30
1 age = 20
2 Age = 30
>>> a=10
>>> b=10
>>> c=10
>>> a=b=c=10
>>> print (a,b,c)
10 10 10
>>> 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.
Open Compiler
a = b = c = 100
print (a)
print (b)
print (c)
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
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.
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)
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)
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
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))
1 15
Example
Following is an example of global variables −
Open Compiler
x = 5
y = 10
def sum():
sum = x + y
return sum
print(sum())
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).
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)
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.
Python numeric data types store numeric values. Number objects are created when you assign a value to them. For example −
Python supports four different numerical types and each of them have built-in classes in Python library, called int, bool, float and complex respectively −
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'>
10 0.0 3.14j
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))
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.
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.
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.
Python sequences are bounded and iterable - Whenever we say an iterable in Python, it means a sequence data type (for example, a list).
A list in Python is an object of list class. We can check it with type() function.
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.
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.
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.
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.
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.
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
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 −
Open Compiler
for i in range(5):
print(i)
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
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
1 1
2 3
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
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
1 b'ABCDE'
In here, we are using the "b" prefix before a string to automatically create a bytes object −
Open Compiler
1 b'Hello'
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.
Open Compiler
1 bytearray(b'Hello')
Open Compiler
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.
Open Compiler
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)
1 <memory at 0x0000017963CD3580>
Open Compiler
1 <memory at 0x00000200D9AA3580>
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.
In Python, dictionary is an object of the built-in dict class. We can check it with the type() function.
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"
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.
Comma separated items in a set are put inside curly brackets or braces {}. Items in the set collection can be of different data types.
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.
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 .
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)
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.
Open Compiler
a = True
# display the value of a
print(a)
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 0
a = 0.0
print(bool(a))
# Returns false as a is 10
a = 10
print(bool(a))
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.
Open Compiler
# Declaring a variable
# And, assigning a Null value (None)
x = None
1 x = None
2 type of x = <class 'NoneType'>
Example
In the following example, we are getting the type of the values and variables −
Open Compiler
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
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
1 x = 10
2 type of x = <class 'int'>
3 x = Hello World!
4 type of x = <class 'str'>
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.
Example
Following is an example which converts different values to integer, floating point and string values respectively −
Open Compiler
print (a)
print (b)
print (c)
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)
2 Python long() functionConverts x to a long integer. base specifies the base if x is a string. This function has been deprecated.
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.
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.
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);
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.
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 −
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'>
<<< 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.
<<< a = int("110011", 2)
<<< a
51
<<< a = int("20", 8)
<<< a
16
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)
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'
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
print (a)
print (b)
print (c)
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)
1 1
2 2.2
3 3.3
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.
### list() separates each character in the string and builds the list
<<< obj=list(c)
<<< obj
['H', 'e', 'l', 'l', 'o']
### tuple() separates each character from string and builds a tuple of characters
<<< obj=tuple(c)
<<< obj
('H', 'e', 'l', 'l', 'o')
### 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.
2 Python long() functionConverts x to a long integer. base specifies the base if x is a string.
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)
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)
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.
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.
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.
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
When you run this code, it will produce the following output −
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.
Open Compiler
(√ −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.
String literals are written by enclosing a sequence of characters in single quotes ('hello'), double quotes ("hello") or triple quotes ('''hello''' or """hello""").
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))
Open Compiler
Literal representation of a list object is done with one or more items which are separated by comma and enclosed in square brackets [].
L1=[1,"Ravi",75.50, True]
print (L1, type(L1))
Literal representation of a tuple object is done with one or more items which are separated by comma and enclosed in parentheses ().
T1=(1,"Ravi",75.50, True)
print (T1, type(T1))
Open Compiler
T1=1,"Ravi",75.50, True
print (T1, type(T1))
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,
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.
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.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
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)
−
+ 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
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
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) −
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")
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
The following table contains all assignment operators with their symbols, names, and examples −
= 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
^= a ^= 5 a=a^5
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
The following table contains all bitwise operators with their symbols, names, and examples −
Operator Name Example
OR
^ XOR a^b
~ NOT ~a
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
The following table contains all logical operators with their symbols, names, and examples −
or OR a or b
var = 5
Output
1 True
2 True
3 False
not in returns True if it does not finds a variable in the specified sequence and false otherwise. a not in b
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
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
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
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
The following table lists all operators from highest precedence to lowest.
2 ~ + -Complement, unary plus and minus (method names for the last two are +@ and -@)
6 &Bitwise 'AND'
7 **^
11 is is notIdentity operators
+ Addition a + b = 30
- Subtraction a – b = -10
* Multiplication a * b = 200
/ Division b/a=2
% Modulus b%a=0
** Exponent ab =1020
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.
Open Compiler
a=10
b=20
print ("Addition of two integers")
print ("a =",a,"b =",b,"addition =",a+b)
Open Compiler
a=10
b=20.5
print ("Addition of integer and float")
print ("a =",a,"b =",b,"addition =",a+b)
Open Compiler
a=10+5j
b=20.5
print ("Addition of complex and float")
print ("a=",a,"b=",b,"addition=",a+b)
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.
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 −
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)
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)
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
a=10
b=20
print ("Multiplication of two integers")
print ("a =",a,"b =",b,"a*b =",a*b)
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)
Open Compiler
a=10+5j
b=20.5
print ("Multiplication of complex and float")
print ("a =",a,"b =",b,"a*b =",a*b)
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.
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)
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)
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)
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)
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.
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)
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)
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.
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
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).
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)
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
%, *, /, // 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.
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)
For example,
a=6+4j
b=3+2j
c=a*b
c=(18-8)+(12+12)j
c=10+24j
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)
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
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.
== Is 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)
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
[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**
Example
Open Compiler
Example
Open Compiler
**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**
**Example**
**Open Compiler**
**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**
**In the following example, two tuple objects are compared −**
**Example**
**Open Compiler**
**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**
**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".**
**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.**
**Open Compiler**
**Open Compiler**
**Open Compiler**
**Open Compiler**
**Open Compiler**
**Open Compiler**
**Open Compiler**
**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.**
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
a not (a)
F T
T F
**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.**
**In the following example, numeric operands are used for logical operators. The variables "x", "y" evaluate to True, "z" is False**
**Open Compiler**
**Open Compiler**
**Open Compiler**
**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.**
**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.**
**Open Compiler**
**To understand how Python performs the operation, obtain the binary equivalent of each variable.**
**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**
**To perform the "|" operation manually, use the 8-bit format.**
**Convert the binary number back to integer to tally the result −**
**Open Compiler**
**Open Compiler**
**Open Compiler**
**How does this take place? Let us use the binary equivalent of 60, and perform the left shift by 2.**
**Open Compiler**
**Use int() function to covert the above binary number to integer. It is 15.**
**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.##
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**
**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**
**Open Compiler**
**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.##
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 1**
**Open Compiler**
**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**
**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.**
**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.**
**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).**
4 **Exponentiation
9 &Bitwise AND
10 ^Bitwise XOR
11 **
12 in, not in, is, is not, <, <=, >, >=, !=, ==Comparisons, including membership tests and identity tests
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**
**Single-line comments**
**Multi-line comments**
**Docstring Comments**
**In this example, the standalone single-line comment is placed above the "greet" function "−**
**Open Compiler**
**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 −**
**Example**
**In this example, multiple lines of comments are used to explain the purpose and logic of the factorial function −**
**Open Compiler**
**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**
**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.**
**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.**
**Open Compiler**
**Open Compiler**
**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 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.**
**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.**
**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**
**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.**
**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 −**
**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 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**
**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**
**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.**
**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 −**
**Open Compiler**
**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.**
**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**
**There is also a bin() function in Python. It returns a binary string equivalent of an integer.**
**Open Compiler**
**Open Compiler**
**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**
**In the following code, two int objects are obtained from octal notations and their addition is performed.**
**Open Compiler**
**To obtain the octal string for an integer, use oct() function.**
**Open Compiler**
**For the literal representation of an integer in Hexadecimal notation, prefix it by "0x" or "0X" .**
**Open Compiler**
**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**
**However, if the string contains any symbol apart from the Hexadecimal symbol chart an error will be generated.**
**Open Compiler**
**Python's standard library has hex() function, with which you can obtain a hexadecimal equivalent of an integer.**
**Open Compiler**
**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**
**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**
**Even if the integer is expressed in binary, octal or hexadecimal, the float() function returns a float with fractional part as 0.**
**Open Compiler**
**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**
**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**
**One more such entity is Nan (stands for Not a Number). It represents any value that is undefined or not representable.**
**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**
**In the above example, we have used x and y as float parameters. They can even be of complex data type.**
**Open Compiler**
**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**
**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**
**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.**
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.
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).
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
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.
4 math.expm1(x)This function returns e raised to the power x, minus 1. Here e is the base of natural logarithms.
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).
**Trigonometric Functions**
**Python includes following functions that perform trigonometric calculations in the math module −**
**Mathematical Constants**
**The Python math module defines the following mathematical constants −**
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Π
.
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 −**
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.
4 [Link](x)This function is used to calculate the hyperbolic cosine of the given value.
**Special Functions**
**Following are the special functions provided by the Python math module −**
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.**
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.
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.
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)
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.
**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**
**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.**
**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**
**Example**
**Following is a simple example which makes use of match statement.**
**Open Compiler**
**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.**
**Example**
**Following is an example which makes use of For Loop to iterate through an array in Python:**
**Open Compiler**
**Example**
**Following is an example which makes use of While Loop to print first 5 numbers in Python:**
**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.##
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.**
**Example**
**The following example demonstrates the use of break statement −**
**Open Compiler**
**Open Compiler**
**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.**
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).
**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.**
**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**
**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 −**
**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.**
**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.**
**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.**
**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.**
**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 −**
**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.**
**Open Compiler**
**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.**
**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**
**Open Compiler**
**When you run the above code, it will display the following result −**
**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))
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.
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"))
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
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]))
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 −
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 supports the following control statements. Click the following links to check their detail.
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.
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.
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='')
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)
1 Total = 539
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
Where,
Example
In this example, we will see the use of range with for loop.
Open Compiler
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
Example
Running a simple for loop over the dictionary object traverses the keys used in it.
Open Compiler
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
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
1 (10, 'Ten')
2 (20, 'Twenty')
3 (30, 'Thirty')
4 (40, 'Forty')
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
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.
Open Compiler
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
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")
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")
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
1 Positive number
2 Positive number
3 Positive number
4 Loop-else Executed
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.
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))
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")
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!")
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.
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")
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
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.
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
Example
In this example, we will see the working of break statement in for loop.
Open Compiler
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
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')
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
Example
Let's see an example to understand how the continue statement works in for loop.
Open Compiler
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.
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
Assign different value (say 75) to num in the above program and test the result for its prime factors.
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.
pass
Open Compiler
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!
Example
If you want to code an infinite loop that does nothing each time through, do it as shown below −
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
...
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.
Open Compiler
for x in months:
for y in days:
print(x, y)
print("Good bye!")
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!
while expression:
while expression:
statement(s)
statement(s)
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!")
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.
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.
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.
def greetings():
"This is docstring of greetings function"
print ("Hello World")
return
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.
Open Compiler
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.
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)
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)
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")
Example
In the code below, we call the function printme() without any parameters which will give error.
Open Compiler
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
1 My string
Example 2
The following example gives more clear picture. Note that the order of parameters does not matter.
Open Compiler
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
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
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
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
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.
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.
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))
1 a = 10 b = 20 a+b = 30
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 −
Example
Following is the example to show how lambda form of function works −
Open Compiler
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
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
Default arguments in Python are the function arguments that will be used if no arguments are passed to the function call.
Open Compiler
# Function definition
def showinfo( name, city = "Hyderabad" ):
"This prints a passed info into this function"
print ("Name:", name)
print ("City:", city)
return
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)
1 percentage: 65.0
2 percentage: 86.0
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
# function calls
fcn(66)
fcn(68)
fcn(70)
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.
Open Compiler
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
division(10,5)
division(5,10)
Since the values are assigned as per the position, the output is as follows −
Example
Instead of passing the values with positional arguments, let us call the function with keyword arguments −
Open Compiler
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 −
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
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.
Open Compiler
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
1 Hello World -
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
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
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.
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)
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)
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)
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)
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 −
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.
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
On executing, this code will show the following error message −<>
Example 1
In this example, we make both the arguments of intr() function as positional-only by putting "/" at the end.
Open Compiler
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
print(intr(amt=1000, rate=10))
Open Compiler
1 10 20 30
2 10 20 30
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.
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
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.
1 45.0
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))
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
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.
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()
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()
1 variable a: 10
2 variable b: 20
3 30
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.
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 −
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).
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.
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.
Example
In the following example, we define a local and a global variable.
Open Compiler
myfunction()
print (marks) # prints global value
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
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
myfunction()
print ("var1:",var1, "var2:",var2) #shows global variables with changed values
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
myfunction(var1, var2)
print (total) # This gives NameError
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
print (myfunction(10,20))
print (myfunction("Hello ", "Python"))
1 30
2 Hello Python
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
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
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.
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.
Example 2
The annotations attribute itself is a dictionary in which arguments are keys and anotations their values.
Open Compiler
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__)
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__)
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.
import math
print ("Square root of 100:", [Link](100))
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.
6 datetimeThis module provides functions to deal with dates and the time within a day. It wraps the C runtime library.
10 FunctoolsThis module has Higher-order functions and operations on callable objects. Useful in functional programming
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.
def SayHello(name):
print ("Hi {}! How are you?".format(name))
return
You can also import one module in another Python script. Save the following code as [Link]
import mymodule
[Link]("Harish")
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))
1 sum:30
2 average:15.0
3 power:100
Out of three functions in mymodule , only two are imported in following executable script [Link]
1 sum: 30
2 average: 15.0
Note that function need not be called by prefixing name of its module to it.
This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.
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 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.
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.
Example
Assuming that the following code is saved as [Link]
def power(x,y):
return x**y
import mymodule
The nameAttribute
The name attribute of a Python module has great significance. Let us explore it in more detail.
>>> __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.
#[Link]
print ("__name__ attribute within a script:", __name__)
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.
Open Compiler
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
import mymodule
print ("sum:",[Link](10,20))
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
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 list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example −
Open Compiler
content = dir(math)
print (content)
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 −
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.
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]
To make all of your functions available when you've imported Phone, you need to put explicit import statements in [Link] as follows −
After you add these lines to [Link], you have all of these classes available when you import the Phone package.
[Link]()
[Link]()
Phone.G3()
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.
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
3 Python anext() functionReturns the next item from the given asynchronous iterator.
8 Python breakpoint() functionThis function drops you into the debugger at the call site and calls [Link]().
66 Python unichr() functionConverts a Unicode code point to its corresponding Unicode character.
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.
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.
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.
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.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −
Open Compiler
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
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.
\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
\s 0x20 Space
\t 0x09 Tab
\x Character x
* 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
Open Compiler
Here is the list of complete set of symbols which can be used along with % −
1 %ccharacter
[Link]. Format Symbol & Conversion
6 %ooctal integer
Other supported symbols and functionality are listed in the following table −
2 -left justification
5 #add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.
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.
Example
Open Compiler
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
Example
Open Compiler
var = '''
Welcome To
Python Tutorial
from TutorialsPoint
'''
print ("var:", var)
1 var:
2 Welcome To
3 Python Tutorial
4 from TutorialsPoint
Open Compiler
print ("Hello"-"World")
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
1 <class 'str'>
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.
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.
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.
22 isspace()Returns true if string contains only whitespace characters 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.
30 partition()Splits the string in three string tuple at the first occurrence of separator.
33 replace(old, new [, max])Replaces all occurrences of old in string with new or at most max occurrences if max given.
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.
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.
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.
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).
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 −
Example
In the below example, we accessing the characters of a string through index.
Open Compiler
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
Open Compiler
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)
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])
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])
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])
Open Compiler
var="HELLO PYTHON"
print ("var:",var)
print ("var[6:12]:", var[6:12])
print ("var[6:]:", var[6:])
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[:])
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])
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])
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.
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)
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")
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]()
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
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)
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)
1 String 1: Hello
2 String 2: World
3 String 3: Hello World
Open Compiler
newString = "Hello" * 3
print(newString)
1 HelloHelloHello
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!
Example
In the below example, we are using format() method to insert values into a string dynamically.
Open Compiler
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)
1 Total: 2800
Example
The following example shows how to use Template class to format strings.
Open Compiler
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)
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)
1 Hello
2 World
3 Hello\nWorld
Escape Characters in Python
The following table shows the different escape characters used in Python -
2 \Backslash ()
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)
# 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)
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 −
2 casefold()Converts all uppercase letters in string to lowercase. Similar to lower(), but works on UNICODE characters alos
5 title()Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.
Alignment Methods
Following methods in the str class control the alignment of characters within the string object.
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 −
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.
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.
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
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.
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 −
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
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)))
1 binary:10101 integer: 21
Example 3
Python program to drop all digits from a string.
Open Compiler
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.”
Any unused piece of code or comments should be deleted. The best place to find them is in the version control systems.
Positive conditionals
All the set standard architecture, coding, and design guidelines should be adhered to. Tools should also be used to ensure that this is accurate.
Try to call variables, methods, classes to be understandable from the caller perspective. And it should be consistent.
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.
Make things small. Class size and method size both matter
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.
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.
1
2 variable = 3.14
3 print(type(variable))
4
Hint: This function will reveal the type of the variable you pass to it.
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.
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.
1
2 string1 = "Hello"
3 string2 = "World"
4 concatenated_string = string1 + " " + string2
5 print(concatenated_string)
6
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.
1
2 number = 5
3 result = number * 2
4 print(result)
5
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.
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.
1
2 text = "Python"
3 number = 3
4 result = text * number
5 print(result)
6
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.
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.
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.
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
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.
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.
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.
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.
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.
1
2 float_value = 7.89
3 integer_part = int(float_value)
4 print(integer_part)
5
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.
1
2 x = "10"
3 y = 5
4 result = int(x) + y
5 print(result)
6
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.
1
2 empty_list = []
3 print(empty_list)
4
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.
1
2 value = "Hello"
3 print(value * 3)
4
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.
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.
1
2 my_list = [1, 2, 3, 4]
3 first_element = my_list[0]
4 print(first_element)
5
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.
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.
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
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.
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.
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.
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.
1
2 x = "Hello"
3 y = "World"
4 print(x + " " + y)
5
1
2 variable = "Sample"
3 is_string = isinstance(variable, str)
4 print(is_string)
5
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.
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.
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.
1
2 x = 10
3 y = 2.5
4 result = x / y
5 print(result)
6
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.
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.
1
2 integer_value = 123
3 string_value = str(integer_value)
4 print(string_value)
5
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.
1
2 x = 1
3 y = 2
4 z = x + y
5 print(z * 2)
6
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
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
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.
1
2 variable = 3.14
3 is_float = isinstance(variable, float)
4 print(is_float)
5
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.
1
2 x = "Hello"
3 y = x * 3
4 print(y)
5
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.
1
2 numbers = [1, 2, 3]
3 strings = list(map(str, numbers))
4 print(strings)
5
1
2 x = [1, 2, [3, 4]]
3 y = x[2]
4 [Link](5)
5 print(x)
6
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.
1
2 string_value = "123"
3 integer_value = int(string_value)
4 print(integer_value)
5
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.
1
2 x = 5
3 y = 10
4 z = x * y / 2
5 print(z)
6
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.
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.
1
2 x = 3.14
3 y = round(x)
4 print(y)
5
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.
1
2 str1 = "Hello"
3 str2 = "World"
4 result = str1 + " " + str2
5 print(result)
6
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.
1
2 a = 10
3 b = 3
4 result = a % b
5 print(result)
6
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.
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.
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.
1
2 x = [1, 2, 3]
3 [Link](4)
4 print(x)
5
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.
1
2 single_element_tuple = (1,)
3 print(single_element_tuple)
4
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.
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.
1
2 value = True
3 is_boolean = isinstance(value, bool)
4 print(is_boolean)
5
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.
1
2 x = "Hello"
3 y = "World"
4 result = f"{x} {y}"
5 print(result)
6
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.
1
2 my_set = {1, 2, 3}
3 print(my_set)
4
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
1
2 squares = [x**2 for x in range(1, 6)]
3 print(squares)
4
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.
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
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.
1
2 x = 10
3 y = 20
4 x, y = y, x
5 print(x, y)
6
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.
1
2 empty_set = set()
3 print(empty_set)
4
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
Short Story: Alex was verifying data types to ensure correct operations. By using `isinstance`, he confirmed that a variable was indeed an integer.
1
2 str1 = "Hello"
3 str2 = "World"
4 result = str1 + " " + str2
5 print(result)
6
Short Story: Lisa needed to create a complete greeting message. By concatenating two strings with the `+` operator, she formed a cohesive message.
1
2 x = [1, 2, 3]
3 [Link](4)
4 print(x)
5
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.
1
2 single_element_tuple = (42,)
3 print(single_element_tuple)
4
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
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.
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.
1
2 numbers = list(range(1, 11))
3 print(numbers)
4
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.
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
1
2 char_list = ['H', 'e', 'l', 'l', 'o']
3 string = ''.join(char_list)
4 print(string)
5
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.
1
2 x = "5"
3 y = "10"
4 result = int(x) + int(y)
5 print(result)
6
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.
1
2 variable = 3.14
3 print(type(variable))
4
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.
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.
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.
1
2 text = "Hello World"
3 length = len(text)
4 print(length)
5
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.
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.
1
2 numbers = [4, 2, 9, 1, 5]
3 [Link]()
4 print(numbers)
5
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.
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.
1
2 sentence = "Python is fun"
3 words = [Link]()
4 print(words)
5
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.
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.
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.
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.
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.
1
2 my_dict = {'name': 'Alice', 'age': 25}
3 print(my_dict)
4
Short Story: Lisa needed to organize information with keys and values. By creating a dictionary, she structured the data for efficient access and
manipulation.
1
2 my_dict = {'name': 'Alice', 'age': 25}
3 keys = my_dict.keys()
4 print(keys)
5
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.
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.
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.
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.
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.
1
2 dict1 = {'name': 'Alice', 'age': 25}
3 dict2 = {'city': 'Wonderland'}
4 merged_dict = {**dict1, **dict2}
5 print(merged_dict)
6
Short Story: Lisa needed to combine two dictionaries for her project. By using the `**` operator, she merged the dictionaries into a single comprehensive
dictionary.
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.
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.
1
2 my_set = {1, 2, 3, 4, 5}
3 print(my_set)
4
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.
1
2 my_set = {1, 2, 3}
3 my_set.add(4)
4 print(my_set)
5
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.
1
2 my_set = {1, 2, 3}
3 my_set.remove(2)
4 print(my_set)
5
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
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.
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.
Short Story: Sarah needed to empty a set for a fresh start. By using the `clear` method, she removed all elements from the set.
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.
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.
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.
Short Story: Michael needed to find common items between two sets. By using the `intersection` method, he quickly determined the shared elements.
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.
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.
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.
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
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.
1
2 my_list = [1, 2, 3, 4]
3 my_list.remove(3)
4 print(my_list)
5
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.
1
2 my_list = [1, 2, 4, 5]
3 my_list.insert(2, 3)
4 print(my_list)
5
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.
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.
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
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.
1
2 my_tuple = (1, 2, 3, 4)
3 print(my_tuple)
4
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.
1
2 my_tuple = (1, 2, 3, 4)
3 element = my_tuple[2]
4 print(element)
5
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.
1
2 tuple1 = (1, 2, 3)
3 tuple2 = (4, 5, 6)
4 concatenated_tuple = tuple1 + tuple2
5 print(concatenated_tuple)
6
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
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.
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.
1
2 my_dict = {'key1': 'value1'}
3 my_dict['key2'] = 'value2'
4 print(my_dict)
5
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.
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.
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.
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.
1
2 empty_dict = {}
3 print(empty_dict)
4
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.
1
2 my_set = {1, 2, 3, 4}
3 print(my_set)
4
Short Story: Emma wanted to create a collection of unique items. By using curly braces, she created a set with distinct elements.
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.
1
2 my_set = {1, 2, 3, 4}
3 my_set.remove(3)
4 print(my_set)
5
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.
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.
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.
Short Story: Emma needed to remove all elements from her set. By using the `clear` method, she emptied the collection completely.
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.
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.
1
2 my_list = [1, 2, 2, 3, 4]
3 my_set = set(my_list)
4 print(my_set)
5
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.
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.
1
2 number_str = "42"
3 number_int = int(number_str)
4 print(number_int)
5
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.
1
2 result = 5 // 2.0
3 print(result)
4
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.
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.
1
2 remainder = 10 % 3
3 print(remainder)
4
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.
1
2 power = 2 ** 3
3 print(power)
4
Short Story: Michael needed to compute powers for a calculation. By using the `**` operator, he obtained the desired result.
1
2 str1 = "Hello"
3 str2 = "World"
4 result = str1 + " " + str2
5 print(result)
6
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.
Short Story: Emma needed to determine how many items were in her list. By using the `len()` function, she got the count.
Control Structures
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.
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.
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.
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.
Short Story: Michael wanted to print numbers from 1 to 5. By using a `while` loop, he achieved this task with ease.
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
1
2 def greet(name):
3 return f"Hello, {name}!"
4
5 print(greet("Alice"))
6
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.
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
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.
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.
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.
1
2 import math
3
4 print([Link](16))
5
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.
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
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.
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.
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.
Hint: Use the `open` function with the `'w'` mode to write to a file.
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.
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
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.
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.
1
2 SELECT * FROM users WHERE name = 'Alice';
3
Hint: Use the `WHERE` clause to specify conditions for filtering records.
Short Story: Michael needed to find records where the name was 'Alice'. He used the `WHERE` clause to filter the results.
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
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.
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.
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.
Short Story: Sarah was learning about Python's data types. She found that integers, floats, strings, and booleans were essential for her programs.
1
2 string_number = "123"
3 integer_number = int(string_number)
4 print(integer_number)
5
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
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
Short Story: Michael needed to know how many elements were in his list. By using `len()`, he quickly found the number of items.
1
2 my_string = "Python"
3 first_char = my_string[0]
4 print(first_char)
5
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.
1
2 even_numbers = [i for i in range(0, 20, 2)]
3 print(even_numbers)
4
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
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.
1
2 y = 20
3 if y % 2 == 0:
4 print("y is even")
5 else:
6 print("y is odd")
7
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
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.
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.
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
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
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.
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.
1
2 import math
3
4 print([Link](16))
5
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
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.
1
2 class Car:
3 def __init__(self, model):
4 [Link] = model
5
6 my_car = Car("Toyota")
7 print(my_car.model)
8
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
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.
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
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
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.
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
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
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.
1
2 for i in range(5):
3 print(i)
4
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.
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.
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.
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
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
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]`.
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
1
2 import sqlite3
3
4 connection = [Link]('[Link]')
5 cursor = [Link]()
6
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.
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.
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
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.
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.
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.
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.
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.
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
1
2 import requests
3
4 data = {'key': 'value'}
5 response = [Link]('[Link] json=data)
6 print(response.status_code)
7 print([Link]())
8
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.
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.
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
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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
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.
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.
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:
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
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
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.
Hint: Familiarize yourself with basic SQL commands to interact with databases.
Short Story: Michael was learning to interact with databases and found that understanding SQL basics was crucial for querying and managing his data
effectively.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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
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.
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.
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
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.
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
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Short Story: Sarah wanted a simple tool for performing quick calculations. She built a basic calculator to help with her everyday math problems.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Short Story: Sarah needed a tool for basic arithmetic operations. She built a simple calculator to perform addition, subtraction, multiplication, and division.
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.
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.
Short Story: Lisa wanted to convert temperatures for her weather report. She built a temperature converter to switch between Celsius and Fahrenheit easily.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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