Data Type Conversion in Python

Datatype Conversion:

Below is a table that demonstrates the conversion of various Python data types into other data types. Each entry in the table includes the original data type, the target data type, a code snippet to perform the conversion, and an example output.

Integer(int) : Convert int Data Type to all other Data Type.

Data TypeTarget Data TypeCodeOutput


int

floatnum_int = 10  

num_float = float(num_int)
10.0


int

strnum_int = 42

num_str = str(num_int)
’42’


int

complexnum_int = 5  

num_complex = complex(num_int)
(5+0j)


int

listnum_int = 123  

num_list = list(num_int)
TypeError: ‘int’ object is not iterable  
Conversion is not possible


int

dictnum_int = 1  

num_dict = dict(num_int)
TypeError: ‘int’ object is not iterable
Conversion is not possible


int

tuplenum_int = 7  

num_tuple = tuple(num_int)
TypeError: ‘int’ object is not iterable
Conversion is not possible
intboolnum_int = 0
num_bool = bool(num_int)
print(num_bool)  

num_int1 = 123
num_bool1 = bool(num_int1)
print(num_bool1)
False


True


Float: Convert Float Data Type to all other Data Type.

Data Type Target Data Type Code Output
floatintnum_float = 10.5  

num_int = int(num_float)
10
float

str

num_float = 3.14  

num_str = str(num_float)
‘3.14’
float

complex

num_float = 3.0  
num_complex = complex(num_float,4.5)
(3+4.5j)
float
list

num_float = 3.14  
num_list = list(num_float)
TypeError: ‘int’ object is not iterable   Conversion is not possible
float
dict

num_float = 2.5  
num_dict = dict(num_float)
TypeError: ‘int’ object is not iterable   Conversion is not possible
floattuple
num_float = 1.5  
num_tuple = float(num_float)
TypeError: ‘int’ object is not iterable   Conversion is not possible
floatboolnum_int = 0
num_bool = bool(num_int)
print(num_bool)  

num_int1 = 12.3
num_bool1 = bool(num_int1)
print(num_bool1)
False


True

Complex : Convert complex data type to all other data type.

Data Type Target Data TypeCodeOutput
complexintnum_complex = complex(3, 4)
 
num_int = int(num_complex)

TypeError: int() argument must be a string, a bytes-like object or a real number, not ‘complex’   Conversion is not possible.
complexfloat
i).
num_complex = complex(3, 4)
num_float = float(num_complex)


ii).
num_complex = complex(3, 4)
num_float = float(num_complex.real)
i).TypeError: float() argument must be a string or a real number, not ‘complex’   Conversion is not possible.



ii).  3
complexstr

num_complex = complex(1, 2)<br>num_str = str(num_complex)

‘(1+2j)’
complexlist
num_complex = complex(2, 3)

num_list = [num_complex.real, num_complex.imag]
[2.0, 3.0]
complexdict
num_complex = complex(2, 1)  

num_dict = {‘real’: num_complex.real, ‘imag’: num_complex.imag}
{‘real’: 2.0, ‘imag’: 1.0}
complextuple
num_complex = complex(4, 5)

num_tuple = (num_complex.real, num_complex.imag)
(4.0, 5.0)
complexbool
num_complex = complex(0, 0)  

num_bool = bool(num_complex)
False

String(str) : Convert str data type to all other data type.

Data TypeTarget Data TypeCodeOutput

str
int
num_str = ‘987’  

num_int = int(num_str)
987

str
float
num_str = ‘2.71’  

num_float = float(num_str)
2.71

str
complex
num_str = ‘1+2j’  

num_complex = complex(num_str)
(1+2j)

str
list
str_val = ‘hello’  

list_val = list(str_val)
[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

str
dict
str_val = ‘hello’  

dict_val = {str_val: len(str_val)}
{‘hello’: 5}

str
tuple
str_val = ‘abc’  

tuple_val = tuple(str_val)
(‘a’, ‘b’, ‘c’)

str
bool
str_val = ‘True’  

bool_val = bool(str_val)
True

List(list) : Convert list data type to all other data type.

Data TypeTarget Data Type CodeOutput
listint
num_list = [1, 2, 3]  

num_int = int(”.join(map(str, num_list)))
123
listfloat
num_list = [3, 1, 4]  

num_float = float(”.join(map(str, num_list)))
314.0
liststr
num_list = [10, 20, 30]  

num_str = ‘, ‘.join(map(str, num_list))
’10, 20, 30′
listcomplex
num_list = [2, 3]  

num_complex = complex(num_list[0], num_list[1])
(2+3j)
listdict
num_list = [1, 2]  

num_dict = dict(zip(num_list, [‘one’, ‘two’]))
{1: ‘one’, 2: ‘two’}
listtuple
num_list = [7, 8, 9]  

num_tuple = tuple(num_list)
(7, 8, 9)
listbool
num_list = [0, 1, 0]  

num_bool = any(num_list)
True

Tuple(tuple) : Convert tuple data type to all other data type.

Data Type Target Data Type Code Output
tupleint
num_tuple = (4, 5, 6)  

num_int = int(”.join(map(str, num_tuple)))
456
tuplefloat
num_tuple = (1, 2)  

num_float = float(‘.’.join(map(str, num_tuple)))
1.2
tuplestr
num_tuple = (7, 8, 9)  

num_str = ‘, ‘.join(map(str, num_tuple))
‘7, 8, 9’
tuplecomplex
num_tuple = (3, 4)  

num_complex = complex(num_tuple[0], num_tuple[1])
(3+4j)
tuplelist
num_tuple = (10, 20)  

num_list = list(num_tuple)
[10, 20]
tupledict
num_tuple = (‘x’, 1)  

num_dict = dict([num_tuple])
{‘x’: 1}
tuplebool
num_tuple = (0, 0)  

num_bool = any(num_tuple)
False

Dictionary(dict) : Convert dict data type to all other data type.

Data Type Target Data Type Code Output
ictint
num_dict = {‘a’: 1}  

num_int = int(list(num_dict.keys())[0])
97
dictfloat
num_dict = {‘pi’: 3.14}  

num_float = float(list(num_dict.values())[0])
3.14
dictstr
num_dict = {1: ‘one’}  

num_str = str(list(num_dict.keys())[0])
‘1’
dictcomplex
num_dict = {3: 5}
 
num_complex = complex(list(num_dict.keys())[0], list(num_dict.values())[0])
(3+5j)
dictlist
num_dict = {‘a’: 1, ‘b’: 2}  

num_list = list(num_dict.items())
[(‘a’, 1), (‘b’, 2)]
dicttuple
num_dict = {‘x’: 10, ‘y’: 20}  

num_tuple = tuple(num_dict.items())
((‘x’, 10), (‘y’, 20))
dictbool
num_dict = {‘flag’: True}  

num_bool = bool(list(num_dict.values())[0])
True

Set : Convert set data type to all other data type.

Data Type Target Data Type CodeOutput
setint
num_set = {1, 2, 3}  

num_int = int(”.join(map(str, num_set)))
123
setfloat
num_set = {3, 1, 4}  

num_float = float(”.join(map(str, num_set)))
314.0
setstr
num_set = {10, 20, 30}  

num_str = ‘, ‘.join(map(str, num_set))
’10, 20, 30′
setcomplex
num_set = {2, 3}  

num_complex = complex(list(num_set)[0], list(num_set)[1])
(2+3j)
setlist
num_set = {1, 2, 3}  

num_list = list(num_set)
[1, 2, 3]
setdict
num_set = {1, 2, 3}  

num_dict = dict.fromkeys(num_set, ‘value’)
{1: ‘value’, 2: ‘value’, 3: ‘value’}
settuple
num_set = {7, 8, 9)  

num_tuple = tuple(num_set)
(8, 9, 7)
setbool
num_set = set()  

num_bool = bool(num_set)
False

Boolean(bool) : Convert bool data type to all other data type.

Data TypeTarget Data Type CodeOutput
boolint
num_bool = False  

num_int = int(num_bool)
0
boolfloat
num_bool = True  

num_float = float(num_bool)
1.0
boolstr
num_bool = True  

num_str = str(num_bool)
‘True‘
boolcomplex
num_bool = True  

num_complex = complex(int(num_bool), 0)
(1+0j)
boollist
num_bool = False  

num_list = [int(num_bool)]
[0]
booldict
num_bool = True  

num_dict = {str(num_bool): ‘boolean’}
{‘True’: ‘boolean’}
booltuple
num_bool = False  

num_tuple = (int(num_bool),)
(0,)

PyCharm Configuration for Windows OS

For installing PyCharm in your System go through the following steps:

  • Open a web browser (e.g., Google Chrome, Firefox, or Edge).1 2
  • Click on first link as shown in web browser ,go to the official JetBrains PyCharm website,or click Here .2 2
  • Visit the official PyCharm website at JETBRAINS and this web page will appear3 2
  • Once the page loads, you’ll see options for different editions of PyCharm.
    • Professional Edition: Paid version with advanced features.
    • Community Edition: Free version, ideal for Python programming.4 2
  • Click the Download button under the Community Edition section.5 2
  • You’ll be redirected to the download page.The website should automatically detect your operating system (Windows) and provide the correct installer.
    • If not, ensure Windows is selected in the operating system dropdown or button.
    • Click the Download button to start downloading the PyCharm Community Edition .exe installer.6 2
  • The installer file will begin downloading. Its name will look something like pycharm-community-<version>.exe.Wait for the download to finish. The file size is usually around 300–400 MB.
    • Locate the downloaded .exe file (usually in your Downloads folder).
    • Double-click the file to start the installation process.7 2
  • A setup wizard will appear. Follow these steps:
    • Welcome Screen: Click Next.
    • Choose Installation Path: Select or confirm the default location where PyCharm will be installed (e.g., C:\Program Files\JetBrains\PyCharm Community Edition). Then, click Next.8 2
  • Installation Options:
    • Check Create Desktop Shortcut (optional).
    • Check Update PATH variable (optional but recommended for easy access to PyCharm from the command line).
    • Check Add Open Folder as Project (optional).
    • Click Next.9 2
  • Choose Start Menu Folder: Leave the default or choose a custom folder for shortcuts. Click Install.
    • 10 2The installation will begin. This might take a few minutes.
    • 11 2
  • Once the installation is complete, check Run PyCharm Community Edition if you want to open it immediately.12 2
  • Open desktop and click on PyCharm Logo.13 2
  • This Dialogue Box will appear, when you click on desktop Shortcut .14 2
  • After PyCharm opens, create a new project:
    • Click New Project.
    • Choose a location and name for the project.15 1
  • If everything works as expected, your PyCharm setup is complete.16 1
  • Right Click on your project name and select new.17
  • In New select for New file Python file.18
  • Name your Python file , here “Trial”.19
  • Write a Trial program of printing a “Hello World” ,and to run that script right click on screen & select Run and Debug.22
  • This Will be the output of the “Trial”. # printing “Hello World “23

Python installation in Windows OS:

  • Open Google Chrome or any other web browser and search for Python. 1 1 e1737919354722
  • Visit the official Python website at python.org.2 1 e1737960267614
  • Navigate to the Downloads section and select the latest stable release for Windows.Choose the appropriate installer based on your system architecture:
  • For 64-bit systems: “Windows installer (64-bit)”
  • For 32-bit systems: “Windows installer (32-bit)”3 1 e1737960433455
  • Locate the downloaded installer file (e.g., python-3.x.x-amd64.exe) and double-click to run it.4 1
  • Check the box labeled “Add Python to PATH” to ensure you can run Python from the command line.Click on “Install Now” to proceed with the default installation.5 1
  • In the “Optional Features” section, you can select additional components like:
    • Documentation
    • pip (Python package installer)
    • tcl/tk and IDLE (Python’s Integrated Development and Learning Environment)
    • Python test suite
    • py launcher6 1
  • Click “Next” and in the “Advanced Options” section, you can:
    • Choose the installation location
    • Add Python to environment variables
    • Install for all users7 1
  • After selecting the desired options, click “Install” to begin the installation.8 19 1 e1737960510964
  • Verify the Installation:
    • Open the Command Prompt:
    • Press Win + R, type cmd, and press Enter.
  • pip --version run in command prompt and python --version.14 1 e1737961172208

Python Installation for MacOS:

  • Check System Requirements: Ensure your macOS version is 10.9 or later.
  • Go To google chrome and search python

seach on google

  • Visit Python’s Official Website: Open https://www.python.org and navigate to the “Downloads” section. The website will auto-detect the appropriate version for macOS.irst page for python
  • Wait until the installation take place & navigate in download bar. 4 e1737897166784
  • Open the .pkg file.5 e1737900198771
  • Click to continue.6 e1737900590266
  • Again click on continue.7 e1737900689287
  • Now click on Agree.8
  • Now complete the processing and click on Install Button.10 e1737901071202And move the python installer package to bin12 e1737902387634
  • Now close all the tabs and open IDLE python.11 e1737902149333
  • Open IDLE shell and try a hello world Program.14 e1737902564954
  • Simple “Hello World” program.16You can also check version in Terminal by giving the following command to check the version of python.
    python3 –versionScreenshot 2025 01 26 at 11.38.27 PM

    PyCharm & VS Code Setup

    Python Tutorial › Getting Started › PyCharm & VS Code Setup

    PyCharm & VS Code Setup

    BeginnerLesson 4 of 479 min read1 runnable examples

    An IDE (integrated development environment) gives you autocomplete, error highlighting, a run button and a debugger. This lesson sets up the two most popular free choices, PyCharm and Visual Studio Code.

    In this lesson
    • Create a Python project in PyCharm
    • Set up VS Code with the Python extension
    • Select the right interpreter
    • Run and debug a script with breakpoints

    Which editor should you choose?

    PyCharm (Community or Pro)VS Code + Python extension
    Made forPython onlyMany languages
    SetupWorks out of the boxInstall the Python extension
    StrengthsRefactoring, inspections, test runnerLightweight, huge extension library
    Best forPython-focused learners and teamsPeople who also write JavaScript, YAML, etc.

    Both are free for learning. Pick one and stick with it while you learn; the Python you write is the same.

    Set up PyCharm

    1. Download PyCharm from jetbrains.com and install it.
    2. Click New Project. Give it a name such as python-practice.
    3. Under Interpreter type choose Project venv. PyCharm creates a virtual environment (a private copy of Python for this project) in a .venv folder.
    4. Click Create. Right-click the project folder, choose New > Python File, and name it first.py.
    5. Paste the program below and click the green Run arrow next to the first line.

    Set up VS Code

    1. Install Visual Studio Code from code.visualstudio.com.
    2. Open the Extensions view (Ctrl+Shift+X), search for Python and install the extension published by Microsoft. It also installs Pylance for autocomplete.
    3. Use File > Open Folder to open an empty folder for your practice files.
    4. Press Ctrl+Shift+P, run Python: Create Environment, choose Venv and your installed Python.
    5. Create first.py, paste the program below and press the Run Python File triangle in the top right.

    Your first program in the IDE

    first.py
    total = 0for price in [120, 80, 45]:    total = total + price    print("Running total:", total) print("Final total:", total)
    Output
    Running total: 120
    Running total: 200
    Running total: 245
    Final total: 245
    Tip

    The Run window shows the same output as the terminal. If you see a ModuleNotFoundError for a package you installed, the IDE is using a different interpreter. Check the interpreter name in the bottom-right status bar.

    Debug with a breakpoint

    A breakpoint pauses the program on a line so you can inspect variables.

    1. Click in the gutter left of the line total = total + price. A red dot appears.
    2. Start the program with Debug (the bug icon) instead of Run.
    3. The program stops at the red dot. The Variables panel shows price and total.
    4. Press Step Over (F8 in PyCharm, F10 in VS Code) to run one line at a time and watch total grow.
    Note

    Debugging is the fastest way to understand someone else’s code, including the practice program solutions on this site. Step through a solution and watch each variable change.

    Useful shortcuts

    ActionPyCharmVS Code
    Run current fileShift+F10Ctrl+F5
    DebugShift+F9F5
    Comment / uncomment lineCtrl+/Ctrl+/
    Reformat codeCtrl+Alt+LShift+Alt+F
    Find anythingShift ShiftCtrl+P

    Check your understanding

    Quick quiz

    1. What does a virtual environment give your project?

    2. Where do you set a breakpoint?

    3. A package works in the terminal but the IDE says ModuleNotFoundError. What is the likely cause?

    Program Practice

    Create a basic-programs folder in your project and solve each program in its own file.

    IDE setup FAQ

    Is PyCharm Community Edition free?

    Yes. PyCharm has a free tier for Python development, and VS Code with the Python extension is free as well.

    Can I use IDLE instead?

    Yes. IDLE comes with Python and is fine for small scripts. Move to PyCharm or VS Code when you want a debugger, a test runner and Git support.

    What is a Python interpreter in PyCharm?

    It is the Python executable PyCharm uses to run your code, usually the one inside the project’s .venv folder. You can change it in Settings > Project > Python Interpreter.

    Install Python

    Python Tutorial › Getting Started › Install Python

    Install Python

    BeginnerLesson 3 of 478 min read1 runnable examples

    To write your own Python programs you need the Python interpreter on your computer. This lesson installs it on Windows, macOS or Linux, checks that it works, and runs your first script.

    In this lesson
    • Install Python 3 on your OS
    • Check the installed version
    • Use the interactive shell
    • Run a .py file from the terminal

    Check whether Python is already installed

    Open a terminal (Command Prompt or PowerShell on Windows, Terminal on macOS and Linux) and run:

    Terminal
    $ python --versionPython 3.15.1

    If you see a version number that starts with 3, Python is ready and you can skip to the interactive shell.

    Note

    On macOS and Linux the command may be python3 instead of python. On Windows, the py launcher (py --version) is installed alongside Python and picks the newest version for you.

    Install Python on Windows

    1. Go to python.org, open Downloads and download the latest Python 3 installer for Windows.
    2. Run the installer. On the first screen tick Add python.exe to PATH. This lets you type python in any terminal.
    3. Click Install Now and wait for it to finish.
    4. Close and reopen your terminal, then run python --version again.
    Watch out

    If python opens the Microsoft Store instead of printing a version, PATH was not set. Re-run the installer, choose Modify, and tick Add Python to environment variables, or turn off the “App execution aliases” for python.exe in Windows Settings.

    Install Python on macOS

    1. Download the macOS installer from python.org and run the .pkg file, or install with Homebrew: brew install python.
    2. Open Terminal and run python3 --version.

    Install Python on Linux

    Most Linux distributions already include Python 3. If yours does not, install it with the package manager:

    • Ubuntu or Debian: sudo apt install python3 python3-pip python3-venv
    • Fedora: sudo dnf install python3

    The interactive shell (REPL)

    Type python on its own to start the interactive shell. It shows a >>> prompt, runs each line as soon as you press Enter and prints the result:

    Python shell
    >>> 2 + 35>>> "py" * 3'pypypy'>>> exit()

    The shell is perfect for trying one line. For anything longer, write a file.

    Run your first Python file

    Create a file called hello.py in any folder with this content:

    hello.py
    print("Hello from a Python file!")print("2 to the power 10 is", 2 ** 10)
    Output
    Hello from a Python file!
    2 to the power 10 is 1024

    Then run it from a terminal opened in that folder:

    Terminal
    $ python hello.pyHello from a Python file!2 to the power 10 is 1024
    Tip

    Python files always end in .py. Keep each practice program in its own file with a descriptive name such as list_sum.py, so you can find and re-run it later.

    Install packages with pip

    pip installs extra packages from PyPI, the Python Package Index. It comes with Python. Check that it works:

    Terminal
    $ python -m pip --versionpip 26.2.2 from C:\Python3\Lib\site-packages\pip (python 3.15)

    You install a package with python -m pip install <name>, for example python -m pip install requests. The Modules & pip lesson covers this in detail, including virtual environments.

    Check your understanding

    Quick quiz

    1. Which installer option lets you type python in any Windows terminal?

    2. What does the >>> prompt mean?

    3. Which command installs a package?

    Program Practice

    With Python installed, write each basic program in its own .py file and run it from the terminal.

    Install Python FAQ

    Which Python version should I install?

    Install the newest Python 3 release from python.org. Libraries add support for new versions quickly, and every example in this tutorial works on current Python 3.

    What is the difference between python and python3?

    They are names for the interpreter. On Windows the command is usually python (or py). On macOS and many Linux systems python3 is the Python 3 interpreter and python may not exist.

    Do I need an IDE to write Python?

    No. Any text editor and a terminal are enough. An IDE such as PyCharm or VS Code adds autocomplete, debugging and a run button. See PyCharm & VS Code Setup.

    How do I uninstall Python on Windows?

    Open Settings > Apps > Installed apps, find Python 3.x and click Uninstall. Remove the Python Launcher the same way if you want it gone too.

    Python Datetime

    Python Tutorial › Modules › Datetime

    Python Datetime

    IntermediateLesson 36 of 4712 min read11 runnable examples

    Dates and times appear in almost every real program: log timestamps, expiry dates, report periods, test data. The datetime module handles creating, formatting, parsing and calculating with them.

    In this lesson
    • Create date, time and datetime objects
    • Format dates with strftime
    • Parse text into dates with strptime
    • Add, subtract and compare dates with timedelta

    The main classes

    ClassHoldsExample
    dateyear, month, daydate(2026, 11, 2)
    timehour, minute, second, microsecondtime(9, 30)
    datetimedate and time togetherdatetime(2026, 11, 2, 9, 30)
    timedeltaa durationtimedelta(days=7)
    timezonea fixed UTC offsettimezone.utc
    Python
    from datetime import date, time, datetime d = date(2026, 11, 2)t = time(9, 30, 15)dt = datetime(2026, 11, 2, 9, 30, 15) print(d, t, dt)print(d.year, d.month, d.day, d.weekday())   # Monday is 0print(dt.date(), dt.time())
    Output
    2026-11-02 09:30:15 2026-11-02 09:30:15
    2026 11 2 0
    2026-11-02 09:30:15

    Today and now

    Python
    from datetime import date, datetime today = date.today()now = datetime.now()print(type(today).__name__, type(now).__name__)print(today == now.date())
    Output
    date datetime
    True

    The values depend on when you run the code, so press Try it to see your own date and time.

    Format dates with strftime

    strftime() turns a date into text using format codes:

    CodeMeaningExample
    %dday, 2 digits02
    %mmonth, 2 digits11
    %Yyear, 4 digits2026
    %B / %bmonth name / shortNovember / Nov
    %A / %aweekday / shortMonday / Mon
    %H:%M:%S24-hour time14:05:09
    %I %p12-hour hour, AM/PM02 PM
    Python
    from datetime import datetime dt = datetime(2026, 11, 2, 14, 5, 9)print(dt.strftime("%d-%m-%Y"))print(dt.strftime("%A, %d %B %Y"))print(dt.strftime("%I:%M %p"))print(dt.isoformat())print(f"{dt:%Y/%m/%d %H:%M}")
    Output
    02-11-2026
    Monday, 02 November 2026
    02:05 PM
    2026-11-02T14:05:09
    2026/11/02 14:05

    Parse text with strptime

    strptime() does the reverse: it reads text in a known format and returns a datetime.

    Python
    from datetime import datetime, date dt = datetime.strptime("02/11/2026 18:45", "%d/%m/%Y %H:%M")print(dt, dt.hour) print(date.fromisoformat("2026-12-25"))
    Output
    2026-11-02 18:45:00 18
    2026-12-25

    A mismatch between the text and the format raises ValueError:

    Python
    from datetime import datetimedatetime.strptime("2026-11-02", "%d/%m/%Y")
    Output
    Traceback (most recent call last):
      File "main.py", line 2, in <module>
        datetime.strptime("2026-11-02", "%d/%m/%Y")
        ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "C:\Python3\Lib\_strptime.py", line 844, in _strptime_datetime_datetime
        tt, fraction, gmtoff_fraction = _strptime(data_string, format)
                                        ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
      File "C:\Python3\Lib\_strptime.py", line 574, in _strptime
        raise ValueError("time data %r does not match format %r" %
                         (data_string, format))
    ValueError: time data '2026-11-02' does not match format '%d/%m/%Y'

    Date arithmetic with timedelta

    Python
    from datetime import date, timedelta start = date(2026, 11, 2)print(start + timedelta(days=30))print(start - timedelta(weeks=2)) deadline = date(2026, 12, 31)remaining = deadline - start          # subtracting dates gives a timedeltaprint(remaining, remaining.days)
    Output
    2026-12-02
    2026-10-19
    59 days, 0:00:00 59
    Python
    from datetime import datetime, timedelta login = datetime(2026, 11, 2, 9, 15)logout = datetime(2026, 11, 2, 17, 40)worked = logout - loginprint(worked)print(worked.total_seconds() / 3600, "hours")
    Output
    8:25:00
    8.416666666666666 hours

    Compare and sort dates

    Python
    from datetime import date dates = [date(2026, 3, 1), date(2025, 12, 25), date(2026, 1, 15)]print(sorted(dates))print(max(dates), date(2026, 1, 1) < date(2026, 1, 2))
    Output
    [datetime.date(2025, 12, 25), datetime.date(2026, 1, 15), datetime.date(2026, 3, 1)]
    2026-03-01 True

    Age and days until a birthday

    Python
    from datetime import date def age_on(birth, on_day):    years = on_day.year - birth.year    if (on_day.month, on_day.day) < (birth.month, birth.day):        years -= 1          # birthday not reached yet this year    return years print(age_on(date(1995, 12, 20), date(2026, 11, 2)))print(age_on(date(1995, 6, 1), date(2026, 11, 2)))
    Output
    30
    31

    Time zones

    A datetime without time zone information is “naive”. Attach a zone to make it “aware”. zoneinfo (Python 3.9+) uses the IANA time zone names.

    Python
    from datetime import datetime, timezone, timedelta utc_time = datetime(2026, 11, 2, 12, 0, tzinfo=timezone.utc)ist = timezone(timedelta(hours=5, minutes=30))print(utc_time.astimezone(ist))print(utc_time.astimezone(ist).strftime("%H:%M %z"))
    Output
    2026-11-02 17:30:00+05:30
    17:30 +0530
    Tip

    Store and compare times in UTC, and convert to the user’s local zone only when displaying them.

    Timestamps

    Python
    from datetime import datetime, timezone dt = datetime(2026, 1, 1, tzinfo=timezone.utc)ts = dt.timestamp()print(ts)print(datetime.fromtimestamp(ts, tz=timezone.utc))
    Output
    1767225600.0
    2026-01-01 00:00:00+00:00

    Check your understanding

    Predict the output

    from datetime import date, timedeltad = date(2024, 2, 28) + timedelta(days=2)print(d, d.strftime("%a"))

    Quick quiz

    1. Which method turns a datetime into formatted text?

    2. What is the type of date(2026, 12, 31) - date(2026, 11, 2)?

    3. What does %B produce?

    Exercise: days until a deadline

    Given today’s date and a deadline, print how many days are left and the deadline’s weekday name. Use fixed dates so the output is repeatable.

    Input
    today = 2026-11-02, deadline = 2027-01-15
    Expected output
    74 days left
    Deadline is on a Friday
    Hint 1

    Subtract the dates and use .days.

    Program Practice

    Python datetime FAQ

    How do I get the current date and time in Python?

    from datetime import datetime then datetime.now(). Use date.today() for the date only.

    How do I convert a string to a date in Python?

    Use datetime.strptime(text, format), for example datetime.strptime("02/11/2026", "%d/%m/%Y"), or date.fromisoformat("2026-11-02") for ISO text.

    How do I add days to a date in Python?

    Add a timedelta: date + timedelta(days=10).

    What is the difference between strftime and strptime?

    strftime formats a date as text; strptime parses text into a date.

    Python sys Module

    Python Tutorial › Modules › sys Module

    Python sys Module

    IntermediateLesson 39 of 479 min read6 runnable examples

    The sys module gives your program access to the Python interpreter itself: the command-line arguments it was started with, the version and platform, where it looks for modules, and the standard input and output streams.

    In this lesson
    • Read command-line arguments with sys.argv
    • Stop a program with sys.exit and an exit code
    • Inspect the Python version and module search path
    • Write to stdout and stderr

    Command-line arguments: sys.argv

    sys.argv is a list of the words typed after python. Item 0 is the script name, and the rest are the arguments, always as strings.

    greet.py
    import sys print("script:", sys.argv[0])print("arguments:", sys.argv[1:]) if len(sys.argv) > 1:    name = sys.argv[1]    times = int(sys.argv[2]) if len(sys.argv) > 2 else 1    for _ in range(times):        print("Hello,", name)
    Terminal
    $ python greet.py Asha 2script: greet.pyarguments: ['Asha', '2']Hello, AshaHello, Asha$ python greet.pyscript: greet.pyarguments: []
    Tip

    For real command-line tools, use the argparse module. It builds --help output, converts types and reports missing arguments for you.

    Exit with a status code: sys.exit

    sys.exit() stops the program. By convention, exit code 0 means success and anything else means failure; CI systems and shell scripts check this code.

    check.py
    import sys def main(values):    if not values:        print("no values given", file=sys.stderr)        sys.exit(2)    print("total:", sum(map(int, values))) main(sys.argv[1:])
    Terminal
    $ python check.py 4 5 6total: 15$ python check.pyno values given$ python -c "import subprocess, sys; print('exit code:', subprocess.run([sys.executable, 'check.py']).returncode)"no values givenexit code: 2

    Version and platform

    Python
    import sys print(sys.version_info.major, sys.version_info.minor)print(sys.version_info >= (3, 10))print(sys.platform)print(sys.maxsize == 2 ** 63 - 1)
    Output
    3 15
    True
    win32
    True

    Use a version check to fail early with a clear message:

    Python
    import sys if sys.version_info < (3, 10):    sys.exit("This script needs Python 3.10 or newer")print("version OK")
    Output
    version OK

    Where Python looks for modules: sys.path

    import searches the folders in sys.path, in order: the script’s folder first, then the standard library, then installed packages.

    Python
    import sys print(type(sys.path).__name__, len(sys.path) > 2)print(any(p.endswith("site-packages") for p in sys.path))
    Output
    list True
    True
    Note

    A ModuleNotFoundError means none of these folders contains the module. Usually the package was installed into a different Python or virtual environment; see Modules & pip.

    stdin, stdout and stderr

    print() writes to sys.stdout. Error messages belong on sys.stderr, so they stay visible even when normal output is redirected to a file.

    Python
    import sys sys.stdout.write("normal output\n")print("also normal output", file=sys.stdout)print("number of bytes written:", sys.stdout.write("abc\n"))
    Output
    normal output
    also normal output
    abc
    number of bytes written: 4

    Reading all input lines from sys.stdin is the fastest way to read large input, which is common in coding challenges:

    Python
    import sys numbers = [int(line) for line in sys.stdin if line.strip()]print("sum:", sum(numbers))
    Outputtyped input: 5, 10, 15
    sum: 30

    Other useful sys features

    Python
    import sys print(sys.getrecursionlimit())print(sys.getsizeof([]) < sys.getsizeof([1, 2, 3]))print(sys.executable.endswith(("python.exe", "python", "python3")))
    Output
    1000
    True
    True

    Check your understanding

    Quick quiz

    1. What is sys.argv[0]?

    2. What type are the values in sys.argv?

    3. Which exit code means success?

    Exercise: sum the arguments

    Write add.py that prints the sum of all numbers passed on the command line, or exits with code 1 and a message if any argument is not a number.

    Input
    python add.py 3 4.5 10
    Expected output
    sum = 17.5
    Hint 1

    Wrap the conversion in try/except ValueError and call sys.exit(1) on failure.

    Program Practice

    Python sys module FAQ

    How do I read command-line arguments in Python?

    Use sys.argv, a list of strings where sys.argv[1:] are the arguments. For anything beyond a couple of arguments, use argparse.

    What is the difference between sys.exit() and exit()?

    exit() is a convenience for the interactive shell. Use sys.exit() in scripts; it raises SystemExit, which can carry an exit code or message.

    How do I check the Python version in code?

    Compare sys.version_info with a tuple: if sys.version_info >= (3, 10):.

    Python Collections Module

    Python Tutorial › Modules › Collections

    Python Collections Module

    IntermediateLesson 37 of 4711 min read9 runnable examples

    The collections module adds specialised containers that solve common problems in one line: counting items, grouping values, building fast queues and giving names to tuple fields. Interview questions love them.

    In this lesson
    • Count anything with Counter
    • Group values with defaultdict
    • Build queues with deque
    • Name tuple fields with namedtuple

    Counter: count items

    Counter takes any iterable and counts how many times each item appears.

    Python
    from collections import Counter words = "the cat and the hat and the bat".split()counts = Counter(words)print(counts)print(counts["the"], counts["dog"])     # missing items count as 0print(counts.most_common(2))
    Output
    Counter({'the': 3, 'and': 2, 'cat': 1, 'hat': 1, 'bat': 1})
    3 0
    [('the', 3), ('and', 2)]

    Counting characters, and doing arithmetic with counters:

    Python
    from collections import Counter print(Counter("mississippi").most_common(3)) week1 = Counter(passed=40, failed=5)week2 = Counter(passed=42, failed=2, skipped=1)print(week1 + week2)print(sorted((week1 + week2).elements())[:3])
    Output
    [('i', 4), ('s', 4), ('p', 2)]
    Counter({'passed': 82, 'failed': 7, 'skipped': 1})
    ['failed', 'failed', 'failed']

    Two words are anagrams if their letter counts are equal:

    Python
    from collections import Counterprint(Counter("listen") == Counter("silent"), Counter("apple") == Counter("paple"))
    Output
    True True

    defaultdict: no more KeyError

    A defaultdict creates a default value the first time a missing key is used. Pass the type of the default: list, int, set…

    Python
    from collections import defaultdict employees = [("qa", "Asha"), ("dev", "Ravi"), ("qa", "Meena"), ("ops", "John")] teams = defaultdict(list)for team, name in employees:    teams[team].append(name)       # no need to check if the key exists print(dict(teams)) letters = defaultdict(int)for ch in "banana":    letters[ch] += 1print(dict(letters))
    Output
    {'qa': ['Asha', 'Meena'], 'dev': ['Ravi'], 'ops': ['John']}
    {'b': 1, 'a': 3, 'n': 2}

    deque: a fast queue

    A deque (“deck”) adds and removes items quickly at both ends. Removing from the front of a list is slow for big lists; a deque does it instantly.

    Python
    from collections import deque queue = deque(["task1", "task2"])queue.append("task3")          # join at the backqueue.appendleft("urgent")     # jump the queueprint(queue) print(queue.popleft())         # serve from the frontprint(queue.pop())             # remove from the backprint(queue)
    Output
    deque(['urgent', 'task1', 'task2', 'task3'])
    urgent
    task3
    deque(['task1', 'task2'])

    maxlen keeps only the last N items, perfect for “recent history”:

    Python
    from collections import deque recent = deque(maxlen=3)for page in ["home", "search", "product", "cart", "checkout"]:    recent.append(page)print(list(recent)) d = deque([1, 2, 3, 4, 5])d.rotate(2)print(d)
    Output
    ['product', 'cart', 'checkout']
    deque([4, 5, 1, 2, 3])

    namedtuple: tuples with field names

    Python
    from collections import namedtuple Employee = namedtuple("Employee", ["name", "dept", "salary"])e = Employee("Asha", "QA", 52000) print(e)print(e.name, e.salary)print(e._asdict())print(e._replace(salary=56000))
    Output
    Employee(name='Asha', dept='QA', salary=52000)
    Asha 52000
    {'name': 'Asha', 'dept': 'QA', 'salary': 52000}
    Employee(name='Asha', dept='QA', salary=56000)

    OrderedDict

    Normal dicts keep insertion order since Python 3.7. OrderedDict still adds move_to_end() and an order-sensitive ==, which is handy for simple caches:

    Python
    from collections import OrderedDict cache = OrderedDict(a=1, b=2, c=3)cache.move_to_end("a")print(list(cache))cache.popitem(last=False)      # remove the oldestprint(list(cache))
    Output
    ['b', 'c', 'a']
    ['c', 'a']

    ChainMap

    ChainMap looks up keys in several dicts in order, without copying them. It is a neat way to layer settings:

    Python
    from collections import ChainMap defaults = {"browser": "chromium", "headless": True, "timeout": 30}env = {"headless": False}cli = {"timeout": 60} settings = ChainMap(cli, env, defaults)print(settings["browser"], settings["headless"], settings["timeout"])
    Output
    chromium False 60

    Which one to use

    NeedUse
    Count occurrencesCounter
    Group items into lists or setsdefaultdict(list) / defaultdict(set)
    Queue or stack with fast endsdeque
    Lightweight record with namesnamedtuple (or dataclass)
    Layered configurationChainMap

    Check your understanding

    Predict the output

    from collections import Counter, defaultdictc = Counter("hello")d = defaultdict(int)d["x"] += 5print(c["l"], c["z"], dict(d))

    Quick quiz

    1. Which container counts items automatically?

    2. What does defaultdict(list) give for a missing key?

    3. Which is fastest for removing items from the front?

    Exercise: most frequent words

    Print the three most common words in the text, ignoring case and punctuation.

    Input
    "Test early. Test often! Automate the test, then test again."
    Expected output
    test 4
    early 1
    often 1
    Hint 1

    Lower-case the text, replace punctuation with spaces, then use Counter(words).most_common(3).

    Program Practice

    Python collections FAQ

    What is Counter in Python?

    collections.Counter is a dict subclass that counts hashable items. Counter("banana") gives {'a': 3, 'n': 2, 'b': 1}.

    What is the difference between dict and defaultdict?

    A normal dict raises KeyError for a missing key. A defaultdict creates the key with a default value from the factory you supplied.

    When should I use deque instead of list?

    When you add or remove items at the front, as in a queue. A deque does this in constant time; a list has to shift every item.

    Python Exception Handling

    Python Tutorial › Errors › Exception Handling

    Python Exception Handling

    IntermediateLesson 34 of 4713 min read10 runnable examples

    An exception is Python’s way of saying “something went wrong here”: a file is missing, a number cannot be parsed, a key does not exist. Handling exceptions lets your program recover, retry or report the problem clearly instead of crashing.

    In this lesson
    • Read a traceback
    • Catch specific exceptions with try/except
    • Use else and finally correctly
    • Raise your own and define custom exceptions

    What an exception looks like

    When an error is not handled, Python stops and prints a traceback. Read it from the bottom: the last line names the exception and the message, and the lines above show where it happened.

    Python
    def average(values):    return sum(values) / len(values) print(average([10, 20]))print(average([]))
    Output
    15.0
    Traceback (most recent call last):
      File "main.py", line 5, in <module>
        print(average([]))
              ~~~~~~~^^^^
      File "main.py", line 2, in average
        return sum(values) / len(values)
               ~~~~~~~~~~~~^~~~~~~~~~~~~
    ZeroDivisionError: division by zero

    Common built-in exceptions

    ExceptionTypical cause
    ValueErrorRight type, wrong value: int("abc")
    TypeErrorWrong type: "2" + 2
    KeyErrorMissing dict key
    IndexErrorList index out of range
    ZeroDivisionErrorDivision by zero
    FileNotFoundErrorOpening a file that does not exist
    AttributeErrorObject has no such attribute or method
    NameErrorUsing a name that was never defined

    try and except

    Put the risky code in try. If an exception happens, Python jumps to the matching except block and continues after it.

    Python
    text = "12a"try:    number = int(text)    print("Parsed", number)except ValueError:    print(f"{text!r} is not a number")print("program continues")
    Output
    '12a' is not a number
    program continues

    Catch specific exceptions

    Catch only the errors you expect and know how to handle. Use several except blocks, or a tuple, for different errors. as e gives you the exception object.

    Python
    def safe_divide(a, b):    try:        return a / b    except ZeroDivisionError:        return "cannot divide by zero"    except TypeError as e:        return f"bad input: {e}" print(safe_divide(10, 4))print(safe_divide(10, 0))print(safe_divide(10, "2"))
    Output
    2.5
    cannot divide by zero
    bad input: unsupported operand type(s) for /: 'int' and 'str'
    Python
    data = {"items": [1, 2]}for key, index in [("items", 5), ("users", 0)]:    try:        print(data[key][index])    except (KeyError, IndexError) as e:        print(type(e).__name__, e)
    Output
    IndexError list index out of range
    KeyError 'users'
    Watch out

    Avoid a bare except: or except Exception: that swallows every error silently. It hides real bugs, including typos. If you must catch broadly, log the error.

    else and finally

    • else runs only if the try block raised no exception.
    • finally runs always, error or not. Use it for clean-up such as closing a connection.
    Python
    def read_number(text):    try:        n = int(text)    except ValueError:        print("  invalid:", text)    else:        print("  valid:", n)    finally:        print("  done with", repr(text)) read_number("42")read_number("x")
    Output
      valid: 42
      done with '42'
      invalid: x
      done with 'x'
    Tip

    For files and connections, a with statement does the clean-up for you, so you rarely need finally for that. See File Handling.

    Raise an exception

    Use raise to signal that something is wrong in your own code. Choose the built-in exception that fits best and write a helpful message.

    Python
    def set_age(age):    if not isinstance(age, int):        raise TypeError(f"age must be an int, got {type(age).__name__}")    if age < 0:        raise ValueError("age cannot be negative")    return age for value in [30, -1, "30"]:    try:        print("ok", set_age(value))    except (TypeError, ValueError) as e:        print("rejected:", e)
    Output
    ok 30
    rejected: age cannot be negative
    rejected: age must be an int, got str

    A bare raise inside except re-raises the same exception after you have logged it:

    Python
    try:    {}["missing"]except KeyError:    print("logging the error, then passing it on")    raise
    Output
    logging the error, then passing it on
    Traceback (most recent call last):
      File "main.py", line 2, in <module>
        {}["missing"]
        ~~^^^^^^^^^^^
    KeyError: 'missing'

    Custom exceptions

    Create your own exception classes by inheriting from Exception. They make errors easy to recognise and catch.

    Python
    class InsufficientFundsError(Exception):    def __init__(self, balance, amount):        super().__init__(f"need {amount}, only {balance} available")        self.balance = balance        self.amount = amount def withdraw(balance, amount):    if amount > balance:        raise InsufficientFundsError(balance, amount)    return balance - amount try:    withdraw(500, 800)except InsufficientFundsError as e:    print("Declined:", e)    print("Short by", e.amount - e.balance)
    Output
    Declined: need 800, only 500 available
    Short by 300

    Exception chaining

    raise ... from ... keeps the original error attached, so the traceback shows both:

    Python
    def load_port(config):    try:        return int(config["port"])    except (KeyError, ValueError) as e:        raise RuntimeError("invalid config: port") from e load_port({"port": "eighty"})
    Output
    Traceback (most recent call last):
      File "main.py", line 3, in load_port
        return int(config["port"])
    ValueError: invalid literal for int() with base 10: 'eighty'
    
    The above exception was the direct cause of the following exception:
    
    Traceback (most recent call last):
      File "main.py", line 7, in <module>
        load_port({"port": "eighty"})
        ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
      File "main.py", line 5, in load_port
        raise RuntimeError("invalid config: port") from e
    RuntimeError: invalid config: port

    Retry pattern

    Python
    attempts = iter(["timeout", "timeout", "ok"]) def call_api():    result = next(attempts)    if result == "timeout":        raise TimeoutError("server did not answer")    return "200 OK" for attempt in range(1, 4):    try:        print(call_api(), "on attempt", attempt)        break    except TimeoutError as e:        print(f"attempt {attempt}: {e}")
    Output
    attempt 1: server did not answer
    attempt 2: server did not answer
    200 OK on attempt 3

    Check your understanding

    Predict the output

    def f():    try:        return "try"    finally:        print("finally runs first") print(f())

    Quick quiz

    1. When does the else block of a try statement run?

    2. Which exception does int("abc") raise?

    3. How do you create a custom exception?

    4. Why is a bare except: discouraged?

    Exercise: safe average

    Write safe_average(items) that converts every item to float, skips items that cannot be converted (printing a warning), and returns 0 for an empty result.

    Input
    ["10", "abc", "20.5", None, "30"]
    Expected output
    skipping 'abc'
    skipping None
    20.166666666666668
    0
    Hint 1

    Catch both ValueError (bad text) and TypeError (None).

    Program Practice

    Python exception handling FAQ

    What is the difference between an error and an exception in Python?

    In everyday use they mean the same thing. Technically, syntax errors stop the file from running at all, while exceptions happen while the program runs and can be caught.

    Can I catch multiple exceptions in one except?

    Yes. Use a tuple: except (ValueError, TypeError) as e:.

    What is the purpose of finally in Python?

    finally holds clean-up code that must run whether or not an exception happened, such as closing a connection.

    How do I print the full traceback of a caught exception?

    Use the traceback module: traceback.print_exc() inside the except block, or logging.exception("message").