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

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 Lists

Python Tutorial › Data Structures › Lists

Python Lists

BeginnerLesson 18 of 4712 min read11 runnable examples

A list stores many values in one variable, in order. You will use lists in almost every Python program you write, from a shopping cart to a set of test results.

In this lesson
  • Create lists of any type
  • Read items with indexing and slicing
  • Add, change and remove items
  • Loop through a list
  • Sort a list two ways
  • Avoid the shared-list copy bug

What is a list in Python?

A list is written with square brackets, with items separated by commas. One list can hold numbers, strings, booleans, None and even other lists.

Python
fruits = ["apple", "banana", "cherry"]mixed = [1, "two", 3.0, True, None]empty = [] print(fruits)print(type(fruits))print(len(mixed), len(empty))
Output
['apple', 'banana', 'cherry']
<class 'list'>
5 0
Note

Lists are ordered (items keep their position), mutable (you can change them after creating them) and they allow duplicates.

You can also build a list from any iterable with list(), for example from a string or a range.

Python
print(list("abc"))print(list(range(1, 6)))
Output
['a', 'b', 'c']
[1, 2, 3, 4, 5]

Indexing and slicing

Every item has a position, called its index. Counting starts at 0 from the left and at -1 from the right.

Python
nums = [10, 20, 30, 40, 50] print(nums[0])      # first itemprint(nums[-1])     # last itemprint(nums[1:4])    # items at index 1, 2, 3print(nums[::-1])   # reversed copy
Output
10
50
[20, 30, 40]
[50, 40, 30, 20, 10]
Tip

A slice nums[start:stop] includes start but stops before stop. That is why nums[1:4] returns three items. Leave out start or stop to go from the beginning or to the end.

Reading an index that does not exist raises an IndexError. A slice never does: it just returns fewer items.

Python
nums = [10, 20, 30]print(nums[1:10])print(nums[5])
Output
[20, 30]
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(nums[5])
          ~~~~^^^
IndexError: list index out of range

Add, change and remove items

For every built-in method with examples, see the full guide to Python list methods and functions.

Python
cart = ["pen", "book"] cart.append("bag")        # add to the endcart.insert(1, "ink")     # add at index 1cart[0] = "pencil"        # replace an itemprint(cart) last = cart.pop()         # remove and return the last itemprint(last, cart) cart.remove("ink")        # remove by valueprint(cart)
Output
['pencil', 'ink', 'book', 'bag']
bag ['pencil', 'ink', 'book']
['pencil', 'book']

Python list methods you will use most

MethodWhat it doesReturns
append(x)Adds x to the endNone
insert(i, x)Adds x before index iNone
extend(items)Adds every item from another iterableNone
remove(x)Removes the first x; raises ValueError if it is missingNone
pop(i=-1)Removes the item at index ithe removed item
index(x)Finds the position of the first xint
count(x)Counts how often x appearsint
sort() / reverse()Reorders the list in placeNone
clear()Removes every itemNone
copy()Makes a shallow copya new list

append() adds its argument as one item, while extend() adds each item separately:

Python
a = [1, 2]a.append([3, 4])print(a) b = [1, 2]b.extend([3, 4])print(b)
Output
[1, 2, [3, 4]]
[1, 2, 3, 4]

Loop through a list

A for loop visits each item in order. enumerate() gives you the position and the item together, so you do not need a counter variable.

Python
tasks = ["write tests", "run tests", "fix bugs"] for number, task in enumerate(tasks, start=1):    print(f"{number}. {task}")
Output
1. write tests
2. run tests
3. fix bugs

Use in to check whether a value is in a list:

Python
browsers = ["chromium", "firefox", "webkit"]print("firefox" in browsers)print("edge" in browsers)
Output
True
False

Sort a list

Python
scores = [72, 95, 58, 88] print(sorted(scores))          # new sorted listprint(scores)                  # original is unchanged scores.sort(reverse=True)      # sorts in placeprint(scores)
Output
[58, 72, 88, 95]
[72, 95, 58, 88]
[95, 88, 72, 58]
Watch out

scores.sort() changes the list and returns None. Writing scores = scores.sort() throws your list away. Use sorted(scores) when you need a new list.

Pass key= to sort by something other than the value itself, such as the length of each word:

Python
words = ["banana", "fig", "apple"]print(sorted(words, key=len))
Output
['fig', 'apple', 'banana']

Copy a list without surprises

Assigning a list to a new name does not copy it. Both names point at the same list, so a change through one name shows up in the other.

Python
a = [1, 2]b = a            # b is the SAME list, not a copyb.append(3)print(a) c = a.copy()     # c is a new listc.append(4)print(a, c)
Output
[1, 2, 3]
[1, 2, 3] [1, 2, 3, 4]

Check your understanding

Predict the output

x = [1, 2, 3]y = x * 2print(y, len(y))

Quick quiz

1. What does [10, 20, 30][-1] return?

2. Which call removes and returns the last item?

3. After b = a and b.append(3), what is in a?

4. What does [3, 1, 2].sort() evaluate to?

Exercise: remove duplicate emails

You have a list of signup emails with repeats. Build a list that keeps each email once, in the order it first appeared.

Input
["a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com"]
Expected output
['a@x.com', 'b@x.com', 'c@x.com']
Hint 1

A set removes duplicates but does not keep the order.

Hint 2

Dictionary keys are unique and keep insertion order.

Program Practice: Python list programs

Practise what you just learned. Start with the easy programs and work up.

Python lists FAQ

What is the difference between a list and a tuple in Python?

A list is mutable, so you can add, change and remove items. A tuple is immutable: once created, its items cannot change. Use a tuple for fixed data such as coordinates. See List vs Tuple.

How do I check if an item is in a list?

Use the in operator: "apple" in fruits returns True or False.

What is the difference between append() and extend()?

append(x) adds x as one item, even if x is a list. extend(items) adds each item of items separately.

How do I remove duplicates from a list and keep the order?

Use list(dict.fromkeys(items)). list(set(items)) also removes duplicates but does not keep the original order.

Can a Python list hold different data types?

Yes. A list can mix integers, strings, floats, booleans, None and other lists, although lists of one type are easier to work with.

Python Strings & Methods

Python Tutorial › Strings › Strings & Methods

Python Strings & Methods

BeginnerLesson 16 of 4714 min read11 runnable examples

A string is a piece of text: a name, a URL, a log line, a whole file. Python strings come with dozens of built-in methods, and knowing the common ones will save you from writing loops for everyday text work.

In this lesson
  • Create strings with any quote style
  • Index and slice text
  • Use the most common string methods
  • Split text into parts and join it back

Create a string

Use single or double quotes; they mean the same thing. Pick the one that avoids escaping quotes inside the text. Triple quotes allow several lines.

Python
a = 'single quotes'b = "double quotes, with an 'apostrophe' inside"c = """Line oneLine two"""print(a)print(b)print(c)print(len(c))
Output
single quotes
double quotes, with an 'apostrophe' inside
Line one
Line two
17

A raw string, written r"...", ignores backslash escapes. It is handy for Windows paths and regular expressions:

Python
print("C:\new\table")      # \n and \t become a newline and a tabprint(r"C:\new\table")     # printed exactly as written
Output
C:
ew	able
C:\new\table

Index and slice

Strings are sequences of characters, so they support the same indexing and slicing as lists.

Python
text = "PYTHON"print(text[0], text[-1])print(text[0:2], text[2:], text[:-2])print(text[::2])       # every second characterprint(text[::-1])      # reversed
Output
P N
PY THON PYTH
PTO
NOHTYP

Strings are immutable

You cannot change a character in place. Methods return a new string and leave the original alone.

Python
word = "python"upper_word = word.upper()print(word, upper_word)word[0] = "P"
Output
python PYTHON
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    word[0] = "P"
    ~~~~^^^
TypeError: 'str' object does not support item assignment

To “change” a string, build a new one and assign it: word = "P" + word[1:].

Change case

Python
title = "pYthon tUTORIAL"print(title.upper())print(title.lower())print(title.title())print(title.capitalize())print(title.swapcase())
Output
PYTHON TUTORIAL
python tutorial
Python Tutorial
Python tutorial
PyTHON Tutorial
Python
log = "ERROR 2026-11-02 login failed for user asha"print("failed" in log)print(log.startswith("ERROR"), log.endswith(".py"))print(log.find("login"))        # index of the first matchprint(log.find("logout"))       # -1 when not foundprint(log.count("a"))
Output
True
True False
17
-1
3
Tip

find() returns -1 when the text is missing, while index() raises ValueError. Use in when you only need yes or no.

Clean up text

Python
raw = "   Pune, Maharashtra \n"print(repr(raw.strip()))print(repr(raw.lstrip()), repr(raw.rstrip()))print("--report--".strip("-"))print("2026-11-02".replace("-", "/"))print("aaa".replace("a", "b", 2))     # only the first 2
Output
'Pune, Maharashtra'
'Pune, Maharashtra \n' '   Pune, Maharashtra'
report
2026/11/02
bba

Split and join

split() breaks a string into a list. join() does the opposite: it glues a list of strings together with the string you call it on.

Python
csv_line = "asha,tester,pune"fields = csv_line.split(",")print(fields) sentence = "  learn   python   step by step "words = sentence.split()        # no argument: split on any run of whitespaceprint(words) print(" ".join(words))print("-".join(["2026", "11", "02"]))print(list("abc"))
Output
['asha', 'tester', 'pune']
['learn', 'python', 'step', 'by', 'step']
learn python step by step
2026-11-02
['a', 'b', 'c']

Check what a string contains

Python
for s in ["2026", "python", "Py3", "  ", "3.5"]:    print(repr(s).ljust(9), s.isdigit(), s.isalpha(), s.isalnum(), s.isspace())
Output
'2026'    True False True False
'python'  False True True False
'Py3'     False False True False
'  '      False False False True
'3.5'     False False False False

The columns are isdigit(), isalpha(), isalnum() and isspace(). Note that "3.5".isdigit() is False because . is not a digit.

Alignment and padding

Python
for name, score in [("Asha", 91), ("Ravi", 7), ("Meenakshi", 100)]:    print(name.ljust(10), str(score).rjust(4), str(score).zfill(5))print("menu".center(20, "*"))
Output
Asha         91 00091
Ravi          7 00007
Meenakshi   100 00100
********menu********

Common string methods

MethodReturns
upper(), lower(), title()Text in a different case
strip(), lstrip(), rstrip()Text without surrounding whitespace (or given characters)
replace(old, new)Text with every old replaced
split(sep)A list of parts
sep.join(items)One string from a list of strings
find(sub) / index(sub)Position of sub (-1 / error if missing)
count(sub)How often sub appears
startswith(x) / endswith(x)True or False
isdigit(), isalpha(), isalnum()True or False
ljust(), rjust(), center(), zfill()Padded text

Loop over a string

Python
word = "level"vowels = 0for ch in word:    if ch in "aeiou":        vowels += 1print("vowels:", vowels)print("palindrome:", word == word[::-1])
Output
vowels: 2
palindrome: True

Check your understanding

Predict the output

s = "Hello, World"print(s[7:], s.lower().count("l"), s.split(", "))

Quick quiz

1. What does "python"[1:4] return?

2. What does "a-b-c".split("-") return?

3. Why does name[0] = "J" fail?

4. Which returns -1 when the text is not found?

Exercise: initials and username

From a full name, print the initials in upper case and a username made of the lower-case first name and the length of the full name.

Input
"  meena  ravi  kumar "
Expected output
MRK
meena16
Hint 1

split() without arguments handles the extra spaces.

Hint 2

"".join(...) can build the initials from a list.

Program Practice

Python strings FAQ

How do I reverse a string in Python?

Use slicing with a step of -1: text[::-1]. "".join(reversed(text)) also works.

How do I check if a string contains a substring?

Use in: "py" in "python" is True. Use find() when you also need the position.

Are Python strings mutable?

No. Every method returns a new string. To change a variable, assign the new string to it: name = name.strip().

What is the difference between split() and split(” “)?

split() splits on any run of whitespace and ignores leading and trailing spaces. split(" ") splits on every single space, so repeated spaces give empty strings.

Python Loops: for & while

Python Tutorial › Control Flow › Loops: for & while

Python Loops: for & while

BeginnerLesson 15 of 4714 min read12 runnable examples

A loop repeats a block of code. Use a for loop to go through every item in a collection, and a while loop to repeat until a condition changes. Loops are behind almost every practice program on this site.

In this lesson
  • Loop over lists, strings and dicts with for
  • Count with range()
  • Repeat until a condition with while
  • Control loops with break, continue and else

The for loop

A for loop takes each item from a collection in turn and runs the block once per item.

Python
browsers = ["chromium", "firefox", "webkit"] for browser in browsers:    print("Testing on", browser)print("All browsers done")
Output
Testing on chromium
Testing on firefox
Testing on webkit
All browsers done

It works with anything you can iterate over, including strings, tuples, sets, dicts and files:

Python
for ch in "SQA":    print(ch)
Output
S
Q
A

Count with range()

range() produces a sequence of numbers on demand. It stops before the end value.

CallNumbers
range(5)0, 1, 2, 3, 4
range(2, 6)2, 3, 4, 5
range(0, 10, 3)0, 3, 6, 9
range(5, 0, -1)5, 4, 3, 2, 1
Python
for i in range(1, 6):    print(i, "squared is", i * i) print(list(range(10, 0, -2)))
Output
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
[10, 8, 6, 4, 2]

Index and value: enumerate()

Python
steps = ["open page", "log in", "add to cart"] for number, step in enumerate(steps, start=1):    print(f"Step {number}: {step}")
Output
Step 1: open page
Step 2: log in
Step 3: add to cart

Two lists side by side: zip()

Python
names = ["Asha", "Ravi", "Meena"]scores = [91, 78, 85] for name, score in zip(names, scores):    print(f"{name:6} {score}")
Output
Asha   91
Ravi   78
Meena  85

Loop over a dictionary

Python
stock = {"pen": 40, "notebook": 0, "bag": 7} for item, qty in stock.items():    status = "out of stock" if qty == 0 else f"{qty} left"    print(item, "-", status)
Output
pen - 40 left
notebook - out of stock
bag - 7 left

The while loop

while repeats as long as its condition is true. Make sure something in the loop changes the condition, or it never stops.

Python
balance = 1000year = 0 while balance < 2000:    balance *= 1.08          # 8% growth per year    year += 1 print(f"Doubled after {year} years: {balance:.2f}")
Output
Doubled after 10 years: 2158.92
Watch out

while True: loops forever unless a break stops it. If a program seems stuck, press Ctrl+C in the terminal to stop it.

break and continue

  • break leaves the loop immediately.
  • continue skips the rest of this pass and goes to the next item.
Python
numbers = [4, 7, -1, 12, 0, 9] for n in numbers:    if n < 0:        print("skip negative", n)        continue    if n == 0:        print("zero found, stopping")        break    print("processing", n)
Output
processing 4
processing 7
skip negative -1
processing 12
zero found, stopping

else on a loop

A loop’s else block runs only if the loop finished without break. It is perfect for “search, and report if not found”:

Python
users = ["asha", "ravi", "meena"]wanted = "john" for user in users:    if user == wanted:        print("Found", wanted)        breakelse:    print(wanted, "not found")
Output
john not found

Nested loops

A loop inside a loop runs the inner loop completely for every pass of the outer one.

Python
for row in range(1, 4):    for col in range(1, 4):        print(row * col, end="\t")    print()
Output
1	2	3	
2	4	6	
3	6	9	

Patterns are a classic exercise for nested loops:

Python
rows = 4for i in range(1, rows + 1):    print(" " * (rows - i) + "*" * (2 * i - 1))
Output
   *
  ***
 *****
*******

Common loop patterns

Python
prices = [120, 45, 300, 80, 45] total = 0                       # accumulatefor p in prices:    total += p count_cheap = 0                 # count matchesfor p in prices:    if p < 100:        count_cheap += 1 biggest = prices[0]             # track the maximumfor p in prices[1:]:    if p > biggest:        biggest = p print(total, count_cheap, biggest)print(sum(prices), sum(1 for p in prices if p < 100), max(prices))   # built-in shortcuts
Output
590 3 300
590 3 300
Tip

Write the loop yourself while learning, because interviewers and practice programs ask for it. In real code, prefer sum(), max(), min() and any() when they fit.

Check your understanding

Predict the output

total = 0for i in range(1, 10, 2):    if i == 7:        break    total += iprint(total)

Quick quiz

1. What numbers does range(3) produce?

2. When does a loop’s else block run?

3. What does continue do?

4. Which loop fits “keep asking until the user types quit”?

Exercise: digits of a number

Use a while loop to print the sum of the digits of a number and the number reversed.

Input
40721
Expected output
Sum of digits: 14
Reversed: 12704
Hint 1

n % 10 gives the last digit and n // 10 removes it.

Program Practice

Python loops FAQ

What is the difference between a for loop and a while loop?

A for loop goes through the items of a collection or a range, so the number of passes is known. A while loop repeats until its condition becomes false.

How do I loop with an index in Python?

Use enumerate(): for i, item in enumerate(items):. Avoid for i in range(len(items)) unless you really need the number alone.

How do I loop backwards in Python?

Use reversed(items) or range(start, stop, -1), for example for i in range(10, 0, -1):.

Does Python have a do-while loop?

No. Write while True: and break at the end of the body when the condition is met.

Python Data Types

Python Tutorial › Basics › Data Types

Python Data Types

BeginnerLesson 9 of 4711 min read8 runnable examples

Every value in Python has a type, and the type decides what you can do with it: you can add two numbers, make a string upper case, or append to a list. This lesson is a tour of the built-in types you will use every day.

In this lesson
  • The built-in data types at a glance
  • Check a value’s type with type() and isinstance()
  • Mutable vs immutable types
  • Choose the right collection for the job

Built-in data types at a glance

CategoryTypeExampleNotes
Textstr"hello"Immutable sequence of characters
Numbersint42, -7Whole numbers of any size
float3.14, 1e-3Decimal numbers
complex2 + 3jUsed in maths and engineering
BooleanboolTrue, FalseResult of comparisons
NothingNoneTypeNone“No value yet”
Sequenceslist[1, 2, 3]Ordered, changeable
tuple(1, 2, 3)Ordered, unchangeable
rangerange(5)Sequence of numbers, created on demand
Mappingdict{"id": 7}Key-value pairs
Setsset{1, 2, 3}Unique items, no order
Binarybytesb"abc"Raw bytes from files and networks

Check the type of a value

type() returns the exact type of a value:

Python
values = [42, 3.14, 2 + 3j, "py", True, None, [1], (1,), {1}, {"a": 1}, range(3), b"x"]for v in values:    print(repr(v).ljust(10), type(v).__name__)
Output
42         int
3.14       float
(2+3j)     complex
'py'       str
True       bool
None       NoneType
[1]        list
(1,)       tuple
{1}        set
{'a': 1}   dict
range(0, 3) range
b'x'       bytes

Use isinstance() in real code. It also accepts a tuple of types and understands subclasses:

Python
price = 99.5print(isinstance(price, float))print(isinstance(price, (int, float)))print(isinstance(True, int))     # bool is a subclass of int
Output
True
True
True

Numbers

Python
big = 2 ** 100          # ints never overflowprint(big)print(7 / 2, 7 // 2)    # / always gives a float, // rounds downprint(0.1 + 0.2)        # floats are approximate
Output
1267650600228229401496703205376
3.5 3
0.30000000000000004
Note

0.1 + 0.2 is not exactly 0.3 because floats are stored in binary. Use round() for display, or the decimal module for money. The Numbers & Math lesson goes deeper.

Strings

A string is text in single, double or triple quotes. Strings support indexing, slicing and many methods.

Python
course = "Python Tutorial"print(course.upper())print(course[0], course[-1])print(len(course))print("Tut" in course)
Output
PYTHON TUTORIAL
P l
15
True

Booleans and None

True and False come from comparisons and are used by if and while. None means “no value”.

Python
is_logged_in = 5 > 3print(is_logged_in, type(is_logged_in)) result = Noneprint(result is None)
Output
True <class 'bool'>
True

Every value is either “truthy” or “falsy”. Empty values and zero are falsy:

Python
for v in [0, 1, "", "a", [], [0], None]:    print(repr(v).ljust(5), bool(v))
Output
0     False
1     True
''    False
'a'   True
[]    False
[0]   True
None  False

Collections: list, tuple, set, dict

Python
skills = ["python", "sql", "python"]          # list: ordered, duplicates allowedpoint = (12.5, 77.3)                          # tuple: fixed recordunique_skills = set(skills)                   # set: duplicates removeduser = {"name": "Asha", "role": "tester"}     # dict: look up by key print(skills)print(point[0])print(len(unique_skills))print(user["role"])
Output
['python', 'sql', 'python']
12.5
2
tester
NeedUse
An ordered list of items you will changelist
A fixed group of values, such as coordinatestuple
Unique items, or fast “is it in here?” checksset
Look up a value by a keydict

Mutable vs immutable

A mutable object can change after it is created; an immutable one cannot.

  • Immutable: int, float, bool, str, tuple, frozenset, bytes.
  • Mutable: list, dict, set, bytearray.
Python
name = "python"name.upper()           # returns a NEW stringprint(name)            # the original is unchanged name[0] = "P"          # strings cannot be changed in place
Output
python
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    name[0] = "P"          # strings cannot be changed in place
    ~~~~^^^
TypeError: 'str' object does not support item assignment
Watch out

Because lists and dicts are mutable, passing one to a function lets that function change your data. Strings and numbers are safe from that.

Check your understanding

Predict the output

print(type(7 / 7).__name__, type(7 // 7).__name__, type("7").__name__)

Quick quiz

1. What is the type of (5,)?

2. Which type removes duplicates automatically?

3. Which of these is immutable?

4. What does bool([]) return?

Exercise: describe each value

Loop over the list and print each value with its type name and whether it is truthy.

Input
[0, 2.5, "", "hi", None, [3]]
Expected output
0      int       False
2.5    float     True
''     str       False
'hi'   str       True
None   NoneType  False
[3]    list      True
Hint 1

type(v).__name__ gives the type name as a string.

Program Practice

Python data types FAQ

How many data types are there in Python?

Python has about a dozen commonly used built-in types: int, float, complex, bool, str, list, tuple, range, dict, set, frozenset, bytes and NoneType. You can also create your own with classes.

How do I check the data type of a variable?

Use type(x) to see the type, or isinstance(x, int) to test it.

What is the difference between mutable and immutable types?

Mutable objects such as lists and dicts can be changed in place. Immutable objects such as strings, numbers and tuples cannot; operations on them return new objects.

Is a string a sequence in Python?

Yes. A string is an immutable sequence of characters, so it supports indexing, slicing, len() and in.

Python String Programs with Solutions

Python Practice › String Programs

Python String Programs with Solutions

106 programs101 easy5 medium0 hard

106 string programs that cover slicing, searching, counting, replacing, splitting and joining text. They are among the most common Python interview questions, and each one has an explained solution with real output.

Before you start

Read the Strings & Methods and String Formatting & f-strings lesson first if the topic is new to you.

All programs

Python Tuple Programs with Solutions

Python Practice › Tuple Programs

Python Tuple Programs with Solutions

70 programs65 easy5 medium0 hard

70 tuple programs: creating, indexing, unpacking, sorting lists of tuples, converting between tuples, lists, strings and dicts, and filtering tuples by their contents. Each solution is explained and shows its real output.

Before you start

Read the Tuples and List vs Tuple lesson first if the topic is new to you.

All programs

Python If-Else Programs with Solutions

Python Practice › If-Else Programs

Python If-Else Programs with Solutions

64 programs59 easy5 medium0 hard

64 if-else programs that practise decisions in Python: comparisons, elif chains, nested conditions and combining tests with and / or. Each solution tests several inputs so you can see every branch run.

Before you start

Read the If…Else and Match Case lesson first if the topic is new to you.

All programs