0% found this document useful (0 votes)
21 views258 pages

Python Programming Language Overview

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

Python Programming Language Overview

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

Python Introduction

What is Python?
Python is a popular programming language. It was created by
Guido van Rossum, and released in 1991.

It is used for:

• web development (server-side),


• software development,
• mathematics,
• system scripting.

What can Python do?


• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read
and modify files.
• Python can be used to handle big data and perform complex
mathematics.
• Python can be used for rapid prototyping, or for production-
ready software development.

Why Python?
• Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs
with fewer lines than some other programming languages.
• Python runs on an interpreter system, meaning that code
can be executed as soon as it is written. This means that
prototyping can be very quick.
• Python can be treated in a procedural way, an object-
oriented way or a functional way.
Good to know
• The most recent major version of Python is Python 3, which
we shall be using in this tutorial. However, Python 2,
although not being updated with anything other than
security updates, is still quite popular.
• In this tutorial Python will be written in a text editor. It is
possible to write Python in an Integrated Development
Environment, such as Thonny, Pycharm, Netbeans or Eclipse
which are particularly useful when managing larger
collections of Python files.

Python Syntax compared to other


programming languages
• Python was designed for readability, and has some
similarities to the English language with influence from
mathematics.
• Python uses new lines to complete a command, as opposed
to other programming languages which often use semicolons
or parentheses.
• Python relies on indentation, using whitespace, to define
scope; such as the scope of loops, functions and classes.
Other programming languages often use curly-brackets for
this purpose.

Python Getting Started


Python Install
Many PCs and Macs will have python already installed.

To check if you have python installed on a Windows PC, search in


the start bar for Python or run the following on the Command
Line ([Link]):

C:\Users\Your Name>python --version

To check if you have python installed on a Linux or Mac, then on


linux open the command line or on Mac open the Terminal and
type:

python --version

If you find that you do not have Python installed on your


computer, then you can download it for free from the following
website: [Link]

Python Quickstart
Python is an interpreted programming language, this means that
as a developer you write Python (.py) files in a text editor and
then put those files into the python interpreter to be executed.

The way to run a python file is like this on the command line:

C:\Users\Your Name>python [Link]

Where "[Link]" is the name of your python file.

Let's write our first Python file, called [Link], which can be
done in any text editor.

[Link]
print("Hello, World!")

Simple as that. Save your file. Open your command line, navigate
to the directory where you saved your file, and run:
C:\Users\Your Name>python [Link]

The output should read:

Hello, World!

Congratulations, you have written and executed your first Python


program

We have an online Python editor where you can execute your own
Python code and see the result:

Example
Try our online Python editor:

print("Hello, World!")

This editor will be used in the entire tutorial to demonstrate the


different aspects of Python.

Python Version
To check the Python version of the editor, you can find it by
importing the sys module:

Example
Check the Python version of the editor:

import sys

print([Link])

You will learn more about importing modules in our Python


Modules chapter.
The Python Command Line
To test a short amount of code in python sometimes it is quickest
and easiest not to write the code in a file. This is made possible
because Python can be run as a command line itself.

Type the following on the Windows, Mac or Linux command line:

C:\Users\Your Name>python
Or, if the "python" command did not work, you can try "py":
C:\Users\Your Name>py

From there you can write any python, including our hello world
example from earlier in the tutorial:

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC
v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>> print("Hello, World!")

Which will write "Hello, World!" in the command line:

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC
v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>> print("Hello, World!")
Hello, World!

Whenever you are done in the python command line, you can
simply type the following to quit the python command line
interface:

exit()
Python Syntax

Execute Python Syntax


As we learned in the previous page, Python syntax can be
executed by writing directly in the Command Line:

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


Hello, World!

Or by creating a python file on the server, using the .py file


extension, and running it in the Command Line:

C:\Users\Your Name>python [Link]


Python Indentation
Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is


for readability only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Example
if 5 > 2:
print("Five is greater than two!")

Python will give you an error if you skip the indentation:

Example

Syntax Error:

if 5 > 2:
print("Five is greater than two!")

The number of spaces is up to you as a programmer, the most


common use is four, but it has to be at least one.

Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of
code, otherwise Python will give you an error:
Example

Syntax Error:

if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables
In Python, variables are created when you assign a value to it:

Example

Variables in Python:

x=5
y = "Hello, World!"
Python has no command for declaring a variable.

You will learn more about variables in the Python


Variables chapter.

Comments
Python has commenting capability for the purpose of in-code
documentation.

Comments start with a #, and Python will render the rest of the
line as a comment:

Example
Comments in Python:

#This is a comment.
print("Hello, World!")
Python Comments
Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Creating a Comment
Comments starts with a #, and Python will ignore them:

Example
#This is a comment
print("Hello, World!")

Comments can be placed at the end of a line, and Python will


ignore the rest of the line:

Example
print("Hello, World!") #This is a comment

A comment does not have to be text that explains the code, it


can also be used to prevent Python from executing code:

Example
#print("Hello, World!")
print("Cheers, Mate!")
Multiline Comments
Python does not really have a syntax for multiline comments.

To add a multiline comment you could insert a # for each line:

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a
variable, you can add a multiline string (triple quotes) in your
code, and place your comment inside it:

Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

As long as the string is not assigned to a variable, Python will


read the code, but then ignore it, and you have made a multiline
comment.
Python - Variable Names

Variable Names
A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume). Rules for Python
variables:

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


character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are
three different variables)

Example
Legal variable names:

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Remember that variable names are case-sensitive
Multi Words Variable Names
Variable names with more than one word can be difficult to read.

There are several techniques you can use to make them more
readable:

Camel Case
Each word, except the first, starts with a capital letter:

myVariableName = "John"

Pascal Case
Each word starts with a capital letter:

MyVariableName = "John"

Snake Case
Each word is separated by an underscore character:

my_variable_name = "John"
Python Variables - Assign
Multiple Values
Many Values to Multiple
Variables
Python allows you to assign values to multiple variables in one
line:

Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)

Note: Make sure the number of variables matches the number of


values, or else you will get an error.

One Value to Multiple Variables


And you can assign the same value to multiple variables in one
line:

Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows
you to extract the values into variables. This is called unpacking.
Example
Unpack a list:

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)
Python - Output Variables
Output Variables
The Python print() function is often used to output variables.

Example
x = "Python is awesome"
print(x)

In the print() function, you output multiple variables, separated


by a comma:

Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)

You can also use the + operator to output multiple variables:

Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

Notice the space character after "Python " and "is ", without them
the result would be "Pythonisawesome".

For numbers, the + character works as a mathematical operator:

Example
x=5
y = 10
print(x + y)
In the print() function, when you try to combine a string and a
number with the + operator, Python will give you an error:

Example
x=5
y = "John"
print(x + y)

The best way to output multiple variables in the print() function is


to separate them with commas, which even support different data
types:

Example
x=5
y = "John"
print(x, y)
Python Data Types
Built-in Data Types
In programming, data type is an important concept.

Variables can store data of different types, and different types


can do different things.

Python has the following data types built-in by default, in these


categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

None Type: NoneType


Getting the Data Type
You can get the data type of any object by using
the type() function:

Example
Print the data type of the variable x:

x=5
print(type(x))

Setting the Data Type


In Python, the data type is set when you assign a value to a
variable:

Example Data
Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list


x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "John", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", frozenset


"cherry"})

x = True bool

x = b"Hello" bytes

x = None NoneType
Setting the Specific Data Type
If you want to specify the data type, you can use the following
constructor functions:

Example Data Type

x = str("Hello World") str

x = int(20) int

x = float(20.5) float

x = complex(1j) complex

x = list(("apple", "banana", "cherry")) list

x = tuple(("apple", "banana", "cherry")) tuple

x = range(6) range

x = dict(name="John", age=36) dict

x = set(("apple", "banana", "cherry")) set


x = frozenset(("apple", "banana", "cherry")) frozenset

x = bool(5) bool

x = memoryview(bytes(5)) memoryview
Python Numbers
There are three numeric types in Python:

• int
• float
• complex

Variables of numeric types are created when you assign a value


to them:

Example
x = 1 # int
y = 2.8 # float
z = 1j # complex

To verify the type of any object in Python, use


the type() function:

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

Int
Int, or integer, is a whole number, positive or negative, without
decimals, of unlimited length.

Example
Integers:

x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(x))
print(type(x))

Float
Float, or "floating point number" is a number, positive or
negative, containing one or more decimals.

Example
Floats:

x = 1.10
y = 1.0
z = -35.59

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

Float can also be scientific numbers with an "e" to indicate the


power of 10.

Example
Floats:

x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:

Example
Complex:

x = 3+5j
y = 5j
z = -5j

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

Random Number
Python does not have a random() function to make a random
number, but Python has a built-in module called random that can
be used to make random numbers:

Example
Import the random module, and display a random number
between 1 and 9:

import random

print([Link](1, 10))
Python Operators
Python Operators
Operators are used to perform operations on variables and
values.

In the example below, we use the + operator to add together two


values:

Example
print(10 + 5)

Python divides the operators in the following groups:

Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform
common mathematical operations:

Operator Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y
Python Assignment Operators
Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3


|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

:= print(x := 3) x=3
print(x)
Python Comparison Operators
Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Python Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example

and Returns True if both x < 5 and x


statements are true < 10

or Returns True if one of the x < 5 or x < 4


statements is true

not Reverse the result, returns not(x < 5 and


False if the result is true x < 10)

Examples (AND)

x=5
print(x > 3 and x < 10)

Examples (OR)

x=5
print(x > 3 or x < 4)

Examples (Not)

x=5
print(not(x > 3 and x < 10))
Python Identity Operators
Identity operators are used to compare the objects, not if they
are equal, but if they are actually the same object, with the same
memory location:

Operator Description Example

is Returns True if both variables are x is y


the same object

is not Returns True if both variables are x is not y


not the same object

Examples
x = ["apple", "banana"]

y = ["apple", "banana"]

z=x

print(x is z)

print(x is y)

print(x == y)
Python Membership Operators
Membership operators are used to test if a sequence is presented
in an object:

Operator Description Example

in Returns True if a sequence with the x in y


specified value is present in the
object

not in Returns True if a sequence with the x not in y


specified value is not present in the
object

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Operator Name Description Examples

& AND Sets each bit to 1 if both bits are 1 x&


y

| OR Sets each bit to 1 if one of two bits x|


is 1 y
^ XOR Sets each bit to 1 if only one of two x^
bits is 1 y

~ NOT Inverts all the bits ~x

<< Zero fill Shift left by pushing zeros in from x


left shift the right and let the leftmost bits <<
fall off 2

>> Signed Shift right by pushing copies of the x


right shift leftmost bit in from the left, and let >>
the rightmost bits fall off 2

Operator Precedence
Operator precedence describes the order in which operations are
performed.

Example
Parentheses has the highest precedence, meaning that
expressions inside parentheses must be evaluated first:

print((6 + 3) - (6 + 3))

Example
Multiplication * has higher precedence than addition +, and
therefor multiplications are evaluated before additions:
print(100 + 5 * 3)

The precedence order is described in the table below, starting


with the highest precedence at the top:

Operator Description

() Parentheses

** Exponentiation

+x -x ~x Unary plus, unary minus,


and bitwise NOT

* / // % Multiplication, division,
floor division, and modulus

+ - Addition and subtraction

<< >> Bitwise left and right shifts

& Bitwise AND

^ Bitwise XOR
| Bitwise OR

== != > >= < <= is is Comparisons, identity, and


not in not in membership operators

Not Logical NOT

And AND

Or OR

If two operators have the same precedence, the expression is


evaluated from left to right.

Example
Addition + and subtraction - has the same precedence, and
therefor we evaluate the expression from left to right:

print(5 + 4 - 7 + 3)
Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a
variable. This can be done with casting. Python is an object-
orientated language, and as such it uses classes to define data
types, including its primitive types.

Casting in python is therefore done using constructor functions:

• int() - constructs an integer number from an integer literal,


a float literal (by removing all decimals), or a string literal
(providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a
float literal or a string literal (providing the string represents
a float or an integer)
• str() - constructs a string from a wide variety of data types,
including strings, integer literals and float literals

Example
Integers:

x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Example
Floats:

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
Example
Strings:

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Python Strings

Strings
Strings in python are surrounded by either single quotation
marks, or double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example
print("Hello")
print('Hello')

Quotes Inside Quotes


You can use quotes inside a string, as long as they don't match
the quotes surrounding the string:

Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

Assign String to a Variable


Assigning a string to a variable is done with the variable name
followed by an equal sign and the string:

Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three
quotes:

Example
You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Or three single quotes:

Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Note: in the result, the line breaks are inserted at the same
position as in the code.

Strings are Arrays


Like many other popular programming languages, strings in
Python are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single


character is simply a string with a length of 1.

Square brackets can be used to access elements of the string.


Example
Get the character at position 1 (remember that the first character
has the position 0):

a = "Hello, World!"
print(a[1])

String Length
To get the length of a string, use the len() function.

Example
The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

Check String
To check if a certain phrase or character is present in a string, we
can use the keyword in.

Example
Check if "free" is present in the following text:

txt = "The best things in life are free!"


print("free" in txt)

Use it in an if statement:

Check if NOT
To check if a certain phrase or character is NOT present in a
string, we can use the keyword not in.
Example
Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"


print("expensive" not in txt)
Use it in an if statement:

Example
print only if "expensive" is NOT present:

txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")
Python - Slicing String

Slicing
You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon,
to return a part of the string.

Example
Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Note: The first character has index 0.

Slice From the Start


By leaving out the start index, the range will start at the first
character:

Example
Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])
Slice To the End
By leaving out the end index, the range will go to the end:

Example
Get the characters from position 2, and all the way to the end:

b = "Hello, World!"
print(b[2:])

Negative Indexing
Use negative indexes to start the slice from the end of the string:

Example
Get the characters:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])
Python - Format - String
String Format
As we learned in the Python Variables chapter, we cannot
combine strings and numbers like this:

Example
age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using f-strings or


the format() method!

age = 36

txt = "My name is John, I am {}"

print([Link](age))

F-Strings
F-String was introduced in Python 3.6, and is now the preferred
way of formatting strings.

To specify a string as an f-string, simply put an f in front of the


string literal, and add curly brackets {} as placeholders for
variables and other operations.

Example
Create an f-string:

age = 36
txt = f"My name is John, I am {age}"
print(txt)
Placeholders and Modifiers
A placeholder can contain variables, operations, functions, and
modifiers to format the value.

Example
Add a placeholder for the price variable:

price = 59
txt = f"The price is {price} dollars"
print(txt)

A placeholder can include a modifier to format the value.

A modifier is included by adding a colon : followed by a legal


formatting type, like .2f which means fixed point number with 2
decimals:

Example
Display the price with 2 decimals:

price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)

A placeholder can contain Python code, like math operations:

Example

Perform a math operation in the placeholder, and return the


result:

txt = f"The price is {20 * 59} dollars"


print(txt)
Python - String Method

String Methods
Python has a set of built-in methods that you can use on strings.

Note: All string methods return new values. They do not change
the original string.

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a


string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string


find() Searches the string for a specified value and returns the
position of where it was found

format() Formats specified values in a string

index() Searches the string for a specified value and returns the
position of where it was found

isalnum() Returns True if all characters in the string are


alphanumeric

isalpha() Returns True if all characters in the string are in the


alphabet

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric


isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a


specified value

rfind() Searches the string for a specified value and returns the
last position of where it was found
rindex() Searches the string for a specified value and returns the
last position of where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a


list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a


list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice
versa
title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the


beginning
Python If ... Else
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:

• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in


"if statements" and loops.

An "if statement" is written by using the if keyword.

Example
If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as


part of the if statement to test whether b is greater than a.
As a is 33, and b is 200, we know that 200 is greater than 33,
and so we print to screen that "b is greater than a".

Indentation
Python relies on indentation (whitespace at the beginning of a
line) to define scope in the code. Other programming languages
often use curly-brackets for this purpose.
Example
If statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

Elif
The elif keyword is Python's way of saying "if the previous
conditions were not true, then try this condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

In this example a is equal to b, so the first condition is not true,


but the elif condition is true, so we print to screen that "a and b
are equal".

Else
The else keyword catches anything which isn't caught by the
preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

In this example a is greater than b, so the first condition is not


true, also the elif condition is not true, so we go to
the else condition and print to screen that "a is greater than b".

You can also have an else without the elif:

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand If
If you have only one statement to execute, you can put it on the
same line as the if statement.

Example
One line if statement:

if a > b: print("a is greater than b")


Short Hand If ... Else
If you have only one statement to execute, one for if, and one for
else, you can put it all on the same line:

Example
One line if else statement:

a=2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional


Expressions.

You can also have multiple else statements on the same line:

Example
One line if else statement, with 3 conditions:

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

And
The and keyword is a logical operator, and is used to combine
conditional statements:

Example
Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or
The or keyword is a logical operator, and is used to combine
conditional statements:

Example
Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

Not
The not keyword is a logical operator, and is used to reverse the
result of the conditional statement:

Example
Test if a is NOT greater than b:

a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
You can have if statements inside if statements, this is
called nested if statements.

Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

The pass Statement


if statements cannot be empty, but if you for some reason have
an if statement with no content, put in the pass statement to
avoid getting an error.

Example
a = 33
b = 200

if b > a:
pass
Python Loops
Python has two primitive loop commands:

• while loops
• for loops

Python For Loops


A for loop is used for iterating over a sequence (that is either a
list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages,


and works more like an iterator method as found in other object-
orientated programming languages.

With the for loop we can execute a set of statements, once for
each item in a list, tuple, set etc.

Example
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

The for loop does not require an indexing variable to set


beforehand.
Looping Through a String
Even strings are iterable objects, they contain a sequence of
characters:

Example
Loop through the letters in the word "banana":

for x in "banana":
print(x)

The break Statement


With the break statement we can stop the loop before it has
looped through all the items:

Example
Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break

Example
Exit the loop when x is "banana", but this time the break comes
before the print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)
The continue Statement
With the continue statement we can stop the current iteration of
the loop, and continue with the next:

Example
Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

The range() Function


To loop through a set of code a specified number of times, we can
use the range() function,

The range() function returns a sequence of numbers, starting


from 0 by default, and increments by 1 (by default), and ends at
a specified number.

Example
Using the range() function:

for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to


5.

The range() function defaults to 0 as a starting value, however it


is possible to specify the starting value by adding a
parameter: range(2, 6), which means values from 2 to 6 (but not
including 6):

Example
Using the start parameter:
for x in range(2, 6):
print(x)
The range() function defaults to increment the sequence by 1,
however it is possible to specify the increment value by adding a
third parameter: range(2, 30, 3):

Example
Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)

Else in For Loop


The else keyword in a for loop specifies a block of code to be
executed when the loop is finished:

Example
Print all numbers from 0 to 5, and print a message when the loop
has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")

Note: The else block will NOT be executed if the loop is stopped
by a break statement.

Example
Break the loop when x is 3, and see what happens with
the else block:

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")

Nested Loops
A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of
the "outer loop":

Example
Print each adjective for every fruit:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

The pass Statement


for loops cannot be empty, but if you for some reason have
a for loop with no content, put in the pass statement to avoid
getting an error.

Example
for x in [0, 1, 2]:
pass
Python While Loops
The while Loop
With the while loop we can execute a set of statements as long as
a condition is true.

Example
Print i as long as i is less than 6:

i=1
while i < 6:
print(i)
i += 1

Note: remember to increment i, or else the loop will continue


forever.

The while loop requires relevant variables to be ready, in this


example we need to define an indexing variable, i, which we set
to 1.

The break Statement


With the break statement we can stop the loop even if the while
condition is true:

Example
Exit the loop when i is 3:

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1

The continue Statement


With the continue statement we can stop the current iteration,
and continue with the next:

Example
Continue to the next iteration if i is 3:

i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)

The else Statement


With the else statement we can run a block of code once when
the condition no longer is true:

Example
Print a message once the condition is false:

i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Map and Filter
Operations in Python
•••
Map, and Filter Operations in Python. These three operations are
paradigms of functional programming. They allow one to write
simpler, shorter code without needing to bother about intricacies
like loops and branching. In this article, we will see Map and Filter
Operations in Python.
Map and Filter Operations in Python
Below, are examples of Map and Filter Operations in Python:
• map() Function
• Filter() Function

Map Function in Python


The map () function returns a map object(which is an
iterator) of the results after applying the given function to each
item of a given iterable (list, tuple, etc.).
Syntax: map(fun, iter)
Parameters:
• fun: It is a function to which map passes each element of
given iterable.
• iter: iterable object to be mapped.
Example: In this example, Python program showcases the usage
of the map function to double each number in a given list by
applying the double function to each element, and then printing
the result as a list.
Python3
# Function to return double of n
def double(n):
return n * 2

# Using map to double all numbers


numbers = [5, 6, 7, 8]
result = map(double, numbers)
print(list(result))

Output
[10, 12, 14, 16]

Filter Function in Python


The filter() method filters the given sequence with the help of a
function that tests each element in the sequence to be true or
not.
Syntax: filter(function, sequence)
Parameters:
• function: function that tests if each element of a
sequence is true or not.
• sequence: sequence which needs to be filtered, it can
be sets, lists, tuples, or containers of any iterators.

Example : In this example, we defines a function is_even to


check whether a number is even or not. Then, it applies
the filter() function to a list of numbers to extract only the
even numbers, resulting in a list containing only the even
elements. Finally, it prints the list of even numbers.
Python3
# Define a function to check if a number is even
def is_even(n):
return n % 2 == 0

# Define a list of numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use filter to filter out even numbers


even_numbers = filter(is_even, numbers)
print("Even numbers:", list(even_numbers))

Output
Even numbers: [2, 4, 6, 8, 10]
Python Collections (Arrays)
There are four collection data types in the Python programming
language:

• List is a collection which is ordered and changeable. Allows


duplicate members.
• Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
• Set is a collection which is unordered, unchangeable*, and
unindexed. No duplicate members.
• Dictionary is a collection which is ordered** and
changeable. No duplicate members.

Python Lists

mylist = ["apple", "banana", "cherry"]

List
Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store


collections of data, the other 3 are Tuple, Set, and Dictionary, all
with different qualities and usage.

Lists are created using square brackets:

Example
Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)
List Items
List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second
item has index [1] etc.

Ordered
When we say that lists are ordered, it means that the items have
a defined order, and that order will not change.

If you add new items to a list, the new items will be placed at the
end of the list.

Note: There are some list methods that will change the order,
but in general: the order of the items will not change.

Changeable
The list is changeable, meaning that we can change, add, and
remove items in a list after it has been created.

Allow Duplicates
Since lists are indexed, lists can have items with the same value:

Example
Lists allow duplicate values:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)
List Length
To determine how many items a list has, use the len() function:

Example
Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

List Items - Data Types


List items can be of any data type:

Example
String, int and boolean data types:

list1 = ["apple", "banana", "cherry"]


list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:

Example
A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

type()
From Python's perspective, lists are defined as objects with the
data type 'list':

<class 'list'>
Example
What is the data type of a list?

mylist = ["apple", "banana", "cherry"]


print(type(mylist))

The list() Constructor


It is also possible to use the list() constructor when creating a
new list.

Example
Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the


double round-brackets
print(thislist)
Python - Access List
Items

Access Items
List items are indexed and you can access them by referring to
the index number:

Example
Print the second item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])

Note: The first item has index 0.

Negative Indexing
Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Example
Print the last item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start
and where to end the range.

When specifying a range, the return value will be a new list with
the specified items.
Example
Return the third, fourth, and fifth item:

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

Note: The search will start at index 2 (included) and end at index
5 (not included).

Remember that the first item has index 0.

By leaving out the start value, the range will start at the first
item:

Example
This example returns the items from the beginning to, but NOT
including, "kiwi":

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])

By leaving out the end value, the range will go on to the end of
the list:

Example
This example returns the items from "cherry" to the end:

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the
end of the list:
Example
This example returns the items from "orange" (-4) to, but NOT
including "mango" (-1):

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])

Check if Item Exists


To determine if a specified item is present in a list use
the in keyword:

Example

Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Python - Change List
Items

Change Item Value


To change the value of a specific item, refer to the index number:

Example
Change the second item:

thislist = ["apple", "banana", "cherry"]


thislist[1] = "blackcurrant"
print(thislist)

Change a Range of Item Values


To change the value of items within a specific range, define a list
with the new values, and refer to the range of index numbers
where you want to insert the new values:

Example
Change the values "banana" and "cherry" with the values
"blackcurrant" and "watermelon":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]


thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)

If you insert more items than you replace, the new items will be
inserted where you specified, and the remaining items will move
accordingly:
Example
Change the second value by replacing it with two new values:

thislist = ["apple", "banana", "cherry"]


thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)

Note: The length of the list will change when the number of
items inserted does not match the number of items replaced.

If you insert less items than you replace, the new items will be
inserted where you specified, and the remaining items will move
accordingly:

Example
Change the second and third value by replacing it with one value:

thislist = ["apple", "banana", "cherry"]


thislist[1:3] = ["watermelon"]
print(thislist)

Insert Items
To insert a new list item, without replacing any of the existing
values, we can use the insert() method.

The insert() method inserts an item at the specified index:

Example
Insert "watermelon" as the third item:

thislist = ["apple", "banana", "cherry"]


[Link](2, "watermelon")
print(thislist)

Note: As a result of the example above, the list will now contain
4 items.
Python - Add List Items

Append Items
To add an item to the end of the list, use the append() method:

Example
Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


[Link]("orange")
print(thislist)

Insert Items
To insert a list item at a specified index, use the insert() method.

The insert() method inserts an item at the specified index:

Example
Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]


[Link](1, "orange")
print(thislist)

Note: As a result of the examples above, the lists will now


contain 4 items.

Extend List
To append elements from another list to the current list, use
the extend() method.
Example
Add the elements of tropical to thislist:

thislist = ["apple", "banana", "cherry"]


tropical = ["mango", "pineapple", "papaya"]
[Link](tropical)
print(thislist)

The elements will be added to the end of the list.

Add Any Iterable


The extend() method does not have to append lists, you can add
any iterable object (tuples, sets, dictionaries etc.).

Example
Add elements of a tuple to a list:

thislist = ["apple", "banana", "cherry"]


thistuple = ("kiwi", "orange")
[Link](thistuple)
print(thislist)
Python - Remove List
Items

Remove Specified Item


The remove() method removes the specified item.

Example
Remove "banana":

thislist = ["apple", "banana", "cherry"]


[Link]("banana")
print(thislist)

If there are more than one item with the specified value,
the remove() method removes the first occurance:

Example
Remove the first occurance of "banana":

thislist = ["apple", "banana", "cherry", "banana", "kiwi"]


[Link]("banana")
print(thislist)

Remove Specified Index


The pop() method removes the specified index.

Example
Remove the second item:
thislist = ["apple", "banana", "cherry"]
[Link](1)
print(thislist)

If you do not specify the index, the pop() method removes the
last item.

Example
Remove the last item:

thislist = ["apple", "banana", "cherry"]


[Link]()
print(thislist)

The del keyword also removes the specified index:

Example
Remove the first item:

thislist = ["apple", "banana", "cherry"]


del thislist[0]
print(thislist)

The del keyword can also delete the list completely.

Example
Delete the entire list:

thislist = ["apple", "banana", "cherry"]


del thislist

Clear the List


The clear() method empties the list.

The list still remains, but it has no content.


Example
Clear the list content:

thislist = ["apple", "banana", "cherry"]


[Link]()
print(thislist)

Python - Loop Lists

Loop Through a List


You can loop through the list items by using a for loop:

Example
Print all items in the list, one by one:

thislist = ["apple", "banana", "cherry"]


for x in thislist:
print(x)

Learn more about for loops in our Python For Loops Chapter.

Loop Through the Index


Numbers
You can also loop through the list items by referring to their index
number.

Use the range() and len() functions to create a suitable iterable.

Example
Print all items by referring to their index number:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
The iterable created in the example above is [0, 1, 2].

Using a While Loop


You can loop through the list items by using a while loop.

Use the len() function to determine the length of the list, then
start at 0 and loop your way through the list items by referring to
their indexes.

Remember to increase the index by 1 after each iteration.

Example
Print all items, using a while loop to go through all the index
numbers

thislist = ["apple", "banana", "cherry"]


i=0
while i < len(thislist):
print(thislist[i])
i = i + 1.

Looping Using List


Comprehension
List Comprehension offers the shortest syntax for looping through
lists:

Example
A short hand for loop that will print all items in a list:

thislist = ["apple", "banana", "cherry"]


[print(x) for x in thislist]
Python - List
Comprehension

List Comprehension
List comprehension offers a shorter syntax when you want to
create a new list based on the values of an existing list.

Example:

Based on a list of fruits, you want a new list, containing only the
fruits with the letter "a" in the name.

Without list comprehension you will have to write a for statement


with a conditional test inside:

Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []

for x in fruits:
if "a" in x:
[Link](x)

print(newlist)
With list comprehension you can do all that with only one line of
code:

Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)
The Syntax
newlist = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged.

Condition
The condition is like a filter that only accepts the items that
valuate to True.

Example
Only accept items that are not "apple":

newlist = [x for x in fruits if x != "apple"]

The condition if x != "apple" will return True for all elements


other than "apple", making the new list contain all fruits except
"apple".

The condition is optional and can be omitted:

Example
With no if statement:

newlist = [x for x in fruits]

Iterable
The iterable can be any iterable object, like a list, tuple, set etc.

Example
You can use the range() function to create an iterable:

newlist = [x for x in range(10)]


Same example, but with a condition:

Example
Accept only numbers lower than 5:

newlist = [x for x in range(10) if x < 5]

Expression
The expression is the current item in the iteration, but it is also
the outcome, which you can manipulate before it ends up like a
list item in the new list:

Example
Set the values in the new list to upper case:

newlist = [[Link]() for x in fruits]

You can set the outcome to whatever you like:

Example
Set all values in the new list to 'hello':

newlist = ['hello' for x in fruits]

The expression can also contain conditions, not like a filter, but as
a way to manipulate the outcome:

Example
Return "orange" instead of "banana":

newlist = [x if x != "banana" else "orange" for x in fruits]

The expression in the example above says:

"Return the item if it is not banana, if it is banana return orange".


Python - Sort Lists

Sort List Alphanumerically


List objects have a sort() method that will sort the list
alphanumerically, ascending, by default:

Example
Sort the list alphabetically:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


[Link]()
print(thislist)

Example
Sort the list numerically:

thislist = [100, 50, 65, 82, 23]


[Link]()
print(thislist)

Sort Descending
To sort descending, use the keyword argument reverse = True:

Example
Sort the list descending:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


[Link](reverse = True)
print(thislist)
Example
Sort the list descending:

thislist = [100, 50, 65, 82, 23]


[Link](reverse = True)
print(thislist)

Customize Sort Function


You can also customize your own function by using the keyword
argument key = function.

The function will return a number that will be used to sort the list
(the lowest number first):

Example
Sort the list based on how close the number is to 50:

def myfunc(n):
return abs(n - 50)

thislist = [100, 50, 65, 82, 23]


[Link](key = myfunc)
print(thislist)

Case Insensitive Sort


By default the sort() method is case sensitive, resulting in all
capital letters being sorted before lower case letters:

Example
Case sensitive sorting can give an unexpected result:

thislist = ["banana", "Orange", "Kiwi", "cherry"]


[Link]()
print(thislist)
Luckily we can use built-in functions as key functions when
sorting a list.

So if you want a case-insensitive sort function, use [Link] as a


key function:

Example
Perform a case-insensitive sort of the list:

thislist = ["banana", "Orange", "Kiwi", "cherry"]


[Link](key = [Link])
print(thislist)

Reverse Order
What if you want to reverse the order of a list, regardless of the
alphabet?

The reverse() method reverses the current sorting order of the


elements.

Example
Reverse the order of the list items:

thislist = ["banana", "Orange", "Kiwi", "cherry"]


[Link]()
print(thislist)
Python - Copy Lists

Copy a List
You cannot copy a list simply by typing list2 = list1,
because: list2 will only be a reference to list1, and changes made
in list1 will automatically also be made in list2.

There are ways to make a copy, one way is to use the built-in List
method copy().

Example
Make a copy of a list with the copy() method:

thislist = ["apple", "banana", "cherry"]


mylist = [Link]()
print(mylist)

Another way to make a copy is to use the built-in method list().

Example
Make a copy of a list with the list() method:

thislist = ["apple", "banana", "cherry"]


mylist = list(thislist)
print(mylist)
Python - Join Lists

Join Two Lists


There are several ways to join, or concatenate, two or more lists
in Python.

One of the easiest ways are by using the + operator.

Example
Join two list:

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

Another way to join two lists is by appending all the items from
list2 into list1, one by one:

Example
Append list2 into list1:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

for x in list2:
[Link](x)

print(list1)

Or you can use the extend() method, where the purpose is to add
elements from one list to another list:
Example
Use the extend() method to add list2 at the end of list1:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

[Link](list2)
print(list1)

List Methods
Python has a set of built-in methods that you can use on lists.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of

index() Returns the index of the first element with the specified v
insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list


Python Tuples
mytuple = ("apple", "banana", "cherry")

Tuple
Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store


collections of data, the other 3 are List, Set, and Dictionary, all
with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Example
Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate
values.

Tuple items are indexed, the first item has index [0], the second
item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items
have a defined order, and that order will not change.

Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.

Allow Duplicates
Since tuples are indexed, they can have items with the same
value:

Example
Tuples allow duplicate values:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)

Tuple Length
To determine how many items a tuple has, use the len() function:

Example
Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma
after the item, otherwise Python will not recognize it as a tuple.

Example
One item tuple, remember the comma:

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Tuple Items - Data Types


Tuple items can be of any data type:

Example
String, int and boolean data types:

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

A tuple can contain different data types:

Example
A tuple with strings, integers and boolean values:

tuple1 = ("abc", 34, True, 40, "male")


type()
From Python's perspective, tuples are defined as objects with the
data type 'tuple':

<class 'tuple'>

Example
What is the data type of a tuple?

mytuple = ("apple", "banana", "cherry")


print(type(mytuple))

The tuple() Constructor


It is also possible to use the tuple() constructor to make a tuple.

Example
Using the tuple() method to make a tuple:

thistuple = tuple(("apple", "banana", "cherry")) # note the double


round-brackets
print(thistuple)
Python - Access Tuple
Items

Access Tuple Items


You can access tuple items by referring to the index number,
inside square brackets:

Example
Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])

Note: The first item has index 0.

Negative Indexing
Negative indexing means start from the end.

-1 refers to the last item, -2 refers to the second last item etc.

Example
Print the last item of the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start
and where to end the range.

When specifying a range, the return value will be a new tuple


with the specified items.

Example
Return the third, fourth, and fifth item:

thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

Note: The search will start at index 2 (included) and end at index
5 (not included).

Remember that the first item has index 0.

By leaving out the start value, the range will start at the first
item:

Example
This example returns the items from the beginning to, but NOT
included, "kiwi":

thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[:4])

By leaving out the end value, the range will go on to the end of
the tuple:

Example
This example returns the items from "cherry" and to the end:
thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the
end of the tuple:

Example
This example returns the items from index -4 (included) to index
-1 (excluded)

thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])

Check if Item Exists


To determine if a specified item is present in a tuple use
the in keyword:

Example
Check if "apple" is present in the tuple:

thistuple = ("apple", "banana", "cherry")


if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Python - Update Tuples

Tuples are unchangeable, meaning that you cannot change, add,


or remove items once the tuple is created.

But there are some workarounds.

Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.

But there is a workaround. You can convert the tuple into a list,
change the list, and convert the list back into a tuple.

Example
Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

Add Items
Since tuples are immutable, they do not have a built-
in append() method, but there are other ways to add items to a
tuple.

1. Convert into a list: Just like the workaround for changing a


tuple, you can convert it into a list, add your item(s), and convert
it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back
into a tuple:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
[Link]("orange")
thistuple = tuple(y)

2. Add tuple to a tuple. You are allowed to add tuples to tuples,


so if you want to add one item, (or many), create a new tuple
with the item(s), and add it to the existing tuple:

Example
Create a new tuple with the value "orange", and add that tuple:

thistuple = ("apple", "banana", "cherry")


y = ("orange",)
thistuple += y

print(thistuple)

Note: When creating a tuple with only one item, remember to


include a comma after the item, otherwise it will not be identified
as a tuple.

Remove Items
Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it,


but you can use the same workaround as we used for changing
and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back
into a tuple:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
[Link]("apple")
thistuple = tuple(y)

Or you can delete the tuple completely:

Example
The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple) #this will raise an error because the tuple no
longer exists
Python - Unpack Tuples

Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is
called "packing" a tuple:

Example
Packing a tuple:

fruits = ("apple", "banana", "cherry")

But, in Python, we are also allowed to extract the values back


into variables. This is called "unpacking":

Example
Unpacking a tuple:

fruits = ("apple", "banana", "cherry")

(green, yellow, red) = fruits

print(green)
print(yellow)
print(red)

Note: The number of variables must match the number of values


in the tuple, if not, you must use an asterisk to collect the
remaining values as a list.
Using Asterisk*
If the number of variables is less than the number of values, you
can add an * to the variable name and the values will be assigned
to the variable as a list:

Example
Assign the rest of the values as a list called "red":

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)

If the asterisk is added to another variable name than the last,


Python will assign values to the variable until the number of
values left matches the number of variables left.

Example
Add a list of values the "tropic" variable:

fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits

print(green)
print(tropic)
print(red)
Python - Loop Tuples
Loop Through a Tuple
You can loop through the tuple items by using a for loop.

Example
Iterate through the items and print the values:

thistuple = ("apple", "banana", "cherry")


for x in thistuple:
print(x)

Loop Through the Index


Numbers
You can also loop through the tuple items by referring to their
index number.

Use the range() and len() functions to create a suitable iterable.

Example
Print all items by referring to their index number:

thistuple = ("apple", "banana", "cherry")


for i in range(len(thistuple)):
print(thistuple[i])

Using a While Loop


You can loop through the tuple items by using a while loop.

Use the len() function to determine the length of the tuple, then
start at 0 and loop your way through the tuple items by referring
to their indexes.
Remember to increase the index by 1 after each iteration.

Example
Print all items, using a while loop to go through all the index
numbers:

thistuple = ("apple", "banana", "cherry")


i=0
while i < len(thistuple):
print(thistuple[i])
i=i+1
Python - Join Tuples

Join Two Tuples


To join two or more tuples you can use the + operator:

Example
Join two tuples:

tuple1 = ("a", "b" , "c")


tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)

Multiply Tuples
If you want to multiply the content of a tuple a given number of
times, you can use the * operator:

Example
Multiply the fruits tuple by 2:

fruits = ("apple", "banana", "cherry")


mytuple = fruits * 2

print(mytuple)
Python - Tuple Methods
Tuple Methods
Python has two built-in methods that you can use on tuples.

Method Description

count() Returns the number of times a specified value occurs in

index() Searches the tuple for a specified value and returns the
Python Sets
myset = {"apple", "banana", "cherry"}

Set
Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store


collections of data, the other 3 are List, Tuple, and Dictionary, all
with different qualities and usage.

A set is a collection which is unordered, unchangeable*,


and unindexed.

* Note: Set items are unchangeable, but you can remove items
and add new items.

Sets are written with curly brackets.

Example
Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)

Note: Sets are unordered, so you cannot be sure in which order


the items will appear.

Set Items
Set items are unordered, unchangeable, and do not allow
duplicate values.
Unordered
Unordered means that the items in a set do not have a defined
order.

Set items can appear in a different order every time you use
them, and cannot be referred to by index or key.

Unchangeable
Set items are unchangeable, meaning that we cannot change the
items after the set has been created.

Once a set is created, you cannot change its items, but you can
remove items and add new items.

Duplicates Not Allowed


Sets cannot have two items with the same value.

Example
Duplicate values will be ignored:

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)

Note: The values True and 1 are considered the same value in
sets, and are treated as duplicates:

Example
True and 1 is considered the same value:

thisset = {"apple", "banana", "cherry", True, 1, 2}

print(thisset)

Note: The values False and 0 are considered the same value in
sets, and are treated as duplicates:
Example
False and 0 is considered the same value:

thisset = {"apple", "banana", "cherry", False, True, 0}

print(thisset)

Get the Length of a Set


To determine how many items a set has, use the len() function.

Example
Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

print(len(thisset))

Set Items - Data Types


Set items can be of any data type:

Example
String, int and boolean data types:

set1 = {"apple", "banana", "cherry"}


set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

A set can contain different data types:

Example
A set with strings, integers and boolean values:

set1 = {"abc", 34, True, 40, "male"}


type()
From Python's perspective, sets are defined as objects with the
data type 'set':

<class 'set'>

Example
What is the data type of a set?

myset = {"apple", "banana", "cherry"}


print(type(myset))

The set() Constructor


It is also possible to use the set() constructor to make a set.

Example
Using the set() constructor to make a set:

thisset = set(("apple", "banana", "cherry")) # note the double


round-brackets
print(thisset)
Python - Access Set
Items
Access Items
You cannot access items in a set by referring to an index or a
key.

But you can loop through the set items using a for loop, or ask if
a specified value is present in a set, by using the in keyword.

Example
Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)

Example
Check if "banana" is present in the set:

thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

Example
Check if "banana" is NOT present in the set:

thisset = {"apple", "banana", "cherry"}

print("banana" not in thisset)


Change Items
Once a set is created, you cannot change its items, but you can
add new items.

Python - Add Set Items

Add Items
Once a set is created, you cannot change its items, but you can
add new items.

To add one item to a set use the add() method.

Example
Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}

[Link]("orange")

print(thisset)

Add Sets
To add items from another set into the current set, use
the update() method.

Example
Add elements from tropical into thisset:

thisset = {"apple", "banana", "cherry"}


tropical = {"pineapple", "mango", "papaya"}

[Link](tropical)
print(thisset)

Add Any Iterable


The object in the update() method does not have to be a set, it
can be any iterable object (tuples, lists, dictionaries etc.).

Example
Add elements of a list to at set:

thisset = {"apple", "banana", "cherry"}


mylist = ["kiwi", "orange"]

[Link](mylist)

print(thisset)
Python - Remove Set
Items

Remove Item
To remove an item in a set, use the remove(), or
the discard() method.

Example
Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}

[Link]("banana")

print(thisset)

Note: If the item to remove does not exist, remove() will raise an
error.

Example
Remove "banana" by using the discard() method:

thisset = {"apple", "banana", "cherry"}

[Link]("banana")

print(thisset)

Note: If the item to remove does not


exist, discard() will NOT raise an error.

You can also use the pop() method to remove an item, but this
method will remove a random item, so you cannot be sure what
item that gets removed.
The return value of the pop() method is the removed item.

Example
Remove a random item by using the pop() method:

thisset = {"apple", "banana", "cherry"}

x = [Link]()

print(x)

print(thisset)

Note: Sets are unordered, so when using the pop() method, you
do not know which item that gets removed.

Example
The clear() method empties the set:

thisset = {"apple", "banana", "cherry"}

[Link]()

print(thisset)

Example
The del keyword will delete the set completely:

thisset = {"apple", "banana", "cherry"}

del thisset

print(thisset)
Python - Loop Sets

Loop Items
You can loop through the set items by using a for loop:

Example
Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)
Python - Join Sets
Join Sets
There are several ways to join two or more sets in Python.

The union() and update() methods joins all items from both sets.

The intersection() method keeps ONLY the duplicates.

The difference() method keeps the items from the first set that
are not in the other set(s).

The symmetric_difference() method keeps all items EXCEPT the


duplicates.

Union
The union() method returns a new set with all items from both
sets.

Example
Join set1 and set2 into a new set:

set1 = {"a", "b", "c"}


set2 = {1, 2, 3}

set3 = [Link](set2)
print(set3)

You can use the | operator instead of the union() method, and
you will get the same result.

Example
Use | to join two sets:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}

set3 = set1 | set2


print(set3)

Join Multiple Sets


All the joining methods and operators can be used to join multiple
sets.

When using a method, just add more sets in the parentheses,


separated by commas:

Example
Join multiple sets with the union() method:

set1 = {"a", "b", "c"}


set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}

myset = [Link](set2, set3, set4)


print(myset)

When using the | operator, separate the sets with


more | operators:

Example
Use | to join two sets:

set1 = {"a", "b", "c"}


set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}

myset = set1 | set2 | set3 |set4


print(myset)

Join a Set and a Tuple


The union() method allows you to join a set with other data
types, like lists or tuples.

The result will be a set.

Example
Join a set with a tuple:

x = {"a", "b", "c"}


y = (1, 2, 3)

z = [Link](y)
print(z)

Note: The | operator only allows you to join sets with sets, and
not with other data types like you can with the union() method.

Update
The update() method inserts all items from one set into another.

The update() changes the original set, and does not return a new
set.

Example
The update() method inserts the items in set2 into set1:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}

[Link](set2)
print(set1)
Note: Both union() and update() will exclude any duplicate items.

Intersection
Keep ONLY the duplicates

The intersection() method will return a new set, that only


contains the items that are present in both sets.

Example
Join set1 and set2, but keep only the duplicates:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = [Link](set2)
print(set3)

You can use the & operator instead of the intersection() method,
and you will get the same result.

Example
Use & to join two sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = set1 & set2


print(set3)

Note: The & operator only allows you to join sets with sets, and
not with other data types like you can with
the intersection() method.

The intersection_update() method will also keep ONLY the


duplicates, but it will change the original set instead of returning
a new set.
Example
Keep the items that exist in both set1, and set2:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set1.intersection_update(set2)

print(set1)

The values True and 1 are considered the same value. The same
goes for False and 0.

Example
Join sets that contains the values True, False, 1, and 0, and see
what is considered as duplicates:

set1 = {"apple", 1, "banana", 0, "cherry"}


set2 = {False, "google", 1, "apple", 2, True}

set3 = [Link](set2)

print(set3)

Difference
The difference() method will return a new set that will contain
only the items from the first set that are not present in the other
set.

Example
Keep all items from set1 that are not in set2:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = [Link](set2)
print(set3)

You can use the - operator instead of the difference() method,


and you will get the same result.

Example
Use - to join two sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = set1 - set2


print(set3)

Note: The - operator only allows you to join sets with sets, and
not with other data types like you can with
the difference() method.

The difference_update() method will also keep the items from the
first set that are not in the other set, but it will change the
original set instead of returning a new set.

Example
Use the difference_update() method to keep the items that are
not present in both sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set1.difference_update(set2)

print(set1)

Symmetric Differences
The symmetric_difference() method will keep only the elements
that are NOT present in both sets.
Example
Keep the items that are not present in both sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = set1.symmetric_difference(set2)

print(set3)

You can use the ^ operator instead of


the symmetric_difference() method, and you will get the same
result.

Example
Use ^ to join two sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}

set3 = set1 ^ set2


print(set3)

Note: The ^ operator only allows you to join sets with sets, and
not with other data types like you can with
the symmetric_difference() method.

The symmetric_difference_update() method will also keep all but


the duplicates, but it will change the original set instead of
returning a new set.

Example
Use the symmetric_difference_update() method to keep the
items that are not present in both sets:

set1 = {"apple", "banana", "cherry"}


set2 = {"google", "microsoft", "apple"}
set1.symmetric_difference_update(set2)
print(set1)
Python - Set Methods
Set Methods
Python has a set of built-in methods that you can use on sets.

Method Shortcut Description

add() Adds an element to


the set

clear() Removes all the


elements from the
set

copy() Returns a copy of


the set

difference() - Returns a set


containing the
difference between
two or more sets

difference_update() -= Removes the items


in this set that are
also included in
another, specified set
discard() Remove the
specified item

intersection() & Returns a set, that is


the intersection of
two other sets

intersection_update() &= Removes the items


in this set that are
not present in other,
specified set(s)

isdisjoint() Returns whether two


sets have a
intersection or not

issubset() <= Returns whether


another set contains
this set or not

< Returns whether all


items in this set is
present in other,
specified set(s)

issuperset() >= Returns whether this


set contains another
set or not
> Returns whether all
items in other,
specified set(s) is
present in this set

pop() Removes an element


from the set

remove() Removes the


specified element

symmetric_difference() ^ Returns a set with


the symmetric
differences of two
sets

symmetric_difference_update() ^= Inserts the


symmetric
differences from this
set and another

union() | Return a set


containing the union
of sets

update() |= Update the set with


the union of this set
and others
Python Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do


not allow duplicates.

As of Python version 3.7, dictionaries are ordered. In Python 3.6


and earlier, dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and
values:

Example
Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Dictionary Items
Dictionary items are ordered, changeable, and do not allow
duplicates.
Dictionary items are presented in key:value pairs, and can be
referred to by using the key name.

Example
Print the "brand" value of the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])

Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6
and earlier, dictionaries are unordered.

When we say that dictionaries are ordered, it means that the


items have a defined order, and that order will not change.

Unordered means that the items do not have a defined order, you
cannot refer to an item by using an index.

Changeable
Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key:

Example
Duplicate values will overwrite existing values:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)

Dictionary Length
To determine how many items a dictionary has, use
the len() function:

Example
Print the number of items in the dictionary:

print(len(thisdict))

Dictionary Items - Data Types


The values in dictionary items can be of any data type:

Example
String, int, boolean, and list data types:

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

type()
From Python's perspective, dictionaries are defined as objects
with the data type 'dict':

<class 'dict'>
Example
Print the data type of a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))

The dict() Constructor


It is also possible to use the dict() constructor to make a
dictionary.

Example
Using the dict() method to make a dictionary:

thisdict = dict(name = "John", age = 36, country = "Norway")


print(thisdict)
Python - Access
Dictionary Items

Accessing Items
You can access the items of a dictionary by referring to its key
name, inside square brackets:

Example
Get the value of the "model" key:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]

There is also a method called get() that will give you the same
result:

Example
Get the value of the "model" key:

x = [Link]("model")

Get Keys
The keys() method will return a list of all the keys in the
dictionary.
Example
Get a list of the keys:

x = [Link]()

The list of the keys is a view of the dictionary, meaning that any
changes done to the dictionary will be reflected in the keys list.

Example
Add a new item to the original dictionary, and see that the keys
list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]()

print(x) #before the change

car["color"] = "white"

print(x) #after the change

Get Values
The values() method will return a list of all the values in the
dictionary.

Example
Get a list of the values:

x = [Link]()
The list of the values is a view of the dictionary, meaning that any
changes done to the dictionary will be reflected in the values list.

Example
Make a change in the original dictionary, and see that the values
list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

Example
Add a new item to the original dictionary, and see that the values
list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]()

print(x) #before the change

car["color"] = "red"

print(x) #after the change


Get Items
The items() method will return each item in a dictionary, as
tuples in a list.

Example
Get a list of the key:value pairs

x = [Link]()

The returned list is a view of the items of the dictionary, meaning


that any changes done to the dictionary will be reflected in the
items list.

Example
Make a change in the original dictionary, and see that the items
list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]()

print(x) #before the change

car["year"] = 2020

print(x) #after the change

Example
Add a new item to the original dictionary, and see that the items
list gets updated as well:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]()

print(x) #before the change

car["color"] = "red"

print(x) #after the change

Check if Key Exists


To determine if a specified key is present in a dictionary use
the in keyword:

Example
Check if "model" is present in the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Python - Change
Dictionary Items
Change Values
You can change the value of a specific item by referring to its key
name:

Example
Change the "year" to 2018:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Update Dictionary
The update() method will update the dictionary with the items
from the given argument.

The argument must be a dictionary, or an iterable object with


key:value pairs.

Example
Update the "year" of the car by using the update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})

Python - Add Dictionary


Items
Adding Items
Adding an item to the dictionary is done by using a new index key
and assigning a value to it:

Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Update Dictionary
The update() method will update the dictionary with the items
from a given argument. If the item does not exist, the item will
be added.

The argument must be a dictionary, or an iterable object with


key:value pairs.

Example
Add a color item to the dictionary by using the update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"color": "red"})

Python - Remove
Dictionary Items

Removing Items
There are several methods to remove items from a dictionary:

Example
The pop() method removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)

Example
The popitem() method removes the last inserted item (in versions
before 3.7, a random item is removed instead):

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
Example
The del keyword removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

Example
The del keyword can also delete the dictionary completely:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no
longer exists.

Example
The clear() method empties the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]()
print(thisdict)
Python - Loop
Dictionaries

Loop Through a Dictionary


You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are


the keys of the dictionary, but there are methods to return
the values as well.

Example
Print all key names in the dictionary, one by one:

for x in thisdict:
print(x)

Example
Print all values in the dictionary, one by one:

for x in thisdict:
print(thisdict[x])

Example
You can also use the values() method to return values of a
dictionary:

for x in [Link]():
print(x)

Example
You can use the keys() method to return the keys of a dictionary:

for x in [Link]():
print(x)
Example
Loop through both keys and values, by using the items() method:

for x, y in [Link]():
print(x, y)
Python - Copy
Dictionaries
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1,
because: dict2 will only be a reference to dict1, and changes
made in dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in
Dictionary method copy().

Example
Make a copy of a dictionary with the copy() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = [Link]()
print(mydict)

Another way to make a copy is to use the built-in function dict().

Example
Make a copy of a dictionary with the dict() function:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Python - Nested
Dictionaries

Nested Dictionaries
A dictionary can contain dictionaries, this is called nested
dictionaries.

Example
Create a dictionary that contain three dictionaries:

myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}

Or, if you want to add three dictionaries into a new dictionary:

Example
Create three dictionaries, then create one dictionary that will
contain the other three dictionaries:

child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily ={
"child1" : child1,
"child2" : child2,
"child3" : child3
}

Access Items in Nested


Dictionaries
To access items from a nested dictionary, you use the name of
the dictionaries, starting with the outer dictionary:

Example
Print the name of child 2:

print(myfamily["child2"]["name"])

Loop Through Nested Dictionaries


You can loop through a dictionary by using the items() method
like this:

Example
Loop through the keys and values of all nested dictionaries:
for x, obj in [Link]():
print(x)

for y in obj:
print(y + ':', obj[y])
Python Dictionary
Methods
Dictionary Methods
Python has a set of built-in methods that you can use on
dictionaries.

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and


value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value


pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key


popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key


does not exist: insert the key, with the specified
value

update() Updates the dictionary with the specified key-value


pairs

values() Returns a list of all the values in the dictionary

Python
Dictionary setdefault() M
ethod
Get the value of the "model" item:

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = [Link]("model", "Bronco")

print(x)
Python
Dictionary fromkeys()
Method
Example
Create a dictionary with 3 keys, all with the value 0:

x = ('key1', 'key2', 'key3')


y=0

thisdict = [Link](x, y)

print(thisdict)

Definition and Usage


The fromkeys() method returns a dictionary with the specified
keys and the specified value.
Syntax
[Link](keys, value)

Parameter Values

Parameter Description

keys Required. An iterable specifying the keys of the new


dictionary

value Optional. The value for all keys. Default value is None

More Examples
Example
Same example as above, but without specifying the value:

x = ('key1', 'key2', 'key3')

thisdict = [Link](x)

print(thisdict)
Definition and Usage
The setdefault() method returns the value of the item with the
specified [Link] the key does not exist, insert the key, with the
specified value, see example below

Syntax
[Link](keyname, value)

Parameter Values

Parameter Description

keyname Required. The keyname of the item you want to return the
value from

value Optional.
If the key exist, this parameter has no effect.
If the key does not exist, this value becomes the key's value
Default value None

More Examples
Example
Get the value of the "color" item, if the "color" item does not exist,
insert "color" with the value "white":

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]("color", "white")
print(x)
Note
Before learning Tkinter, you must have the basic knowledge of Python.

Python Tkinter

Tkinter tutorial provides basic and advanced concepts of Python


Tkinter. Our Tkinter tutorial is designed for beginners and
professionals.

Python provides the standard library Tkinter for creating the


graphical user interface for desktop based applications.

Developing desktop based applications with python Tkinter is not


a complex task. An empty Tkinter top-level window can be created
by using the following steps.

1. import the Tkinter module.


2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the
window.
4. Call the main event loop so that the actions can take place on
the user's computer screen.

Example
1. # !/usr/bin/python3
2. from tkinter import *
3. #creating the application main window.
4. top = Tk()
5. #Entering the event main loop
6. [Link]()

Output:

Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that
are used to build the python GUI applications.

SN Widget Description

1 Button The Button is used to add various kinds of buttons to the


python application.

2 Canvas The canvas widget is used to draw the canvas on the window.

3 Checkbutton The Checkbutton is used to display the CheckButton on the


window.

4 Entry The entry widget is used to display the single-line text field to
the user. It is commonly used to accept user values.
5 Frame It can be defined as a container to which, another widget can
be added and organized.

6 Label A label is a text used to display some message or information


about the other widgets.

7 ListBox The ListBox widget is used to display a list of options to the


user.

8 Menubutton The Menubutton is used to display the menu items to the user.

9 Menu It is used to add menu items to the user.

10 Message The Message widget is used to display the message-box to the


user.

11 Radiobutton The Radiobutton is different from a checkbutton. Here, the


user is provided with various options and the user can select
only one option among them.

12 Scale It is used to provide the slider to the user.

13 Scrollbar It provides the scrollbar to the user so that the user can scroll
the window up and down.

14 Text It is different from Entry because it provides a multi-line text


field to the user so that the user can write the text and edit
the text inside it.

14 Toplevel It is used to create a separate window container.

15 Spinbox It is an entry widget used to select from options of values.

16 PanedWindow It is like a container widget that contains horizontal or vertical


panes.
17 LabelFrame A LabelFrame is a container widget that acts as the container

18 MessageBox This module is used to display the message-box in the desktop


based applications.

Python Tkinter Geometry


The Tkinter geometry specifies the method by using which, the
widgets are represented on display. The python Tkinter provides
the following geometry methods.

1. The pack() method


2. The grid() method
3. The place() method

Let's discuss each one of them in detail.

Python Tkinter pack() method


The pack() widget is used to organize widget in the block. The
positions widgets added to the python application using the pack()
method can be controlled by using the various options specified in
the method call.

However, the controls are less and widgets are generally added in
the less organized manner.

The syntax to use the pack() is given below.

syntax
1. [Link](options)

A list of possible options that can be passed in pack() is given


below.

o expand: If the expand is set to true, the widget expands to


fill any space.
o Fill: By default, the fill is set to NONE. However, we can set it
to X or Y to determine whether the widget contains any extra
space.
o size: it represents the side of the parent to which the widget
is to be placed on the window.

Example
1. # !/usr/bin/python3
2. from tkinter import *
3. parent = Tk()
4. redbutton = Button(parent, text = "Red", fg = "red")
5. [Link]( side = LEFT)
6. greenbutton = Button(parent, text = "Black", fg = "black")
7. [Link]( side = RIGHT )
8. bluebutton = Button(parent, text = "Blue", fg = "blue")
9. [Link]( side = TOP )
10. blackbutton = Button(parent, text = "Green", fg = "red
")
11. [Link]( side = BOTTOM)
[Link]()

Output:

Python Tkinter grid() method


The grid() geometry manager organizes the widgets in the tabular
form. We can specify the rows and columns as the options in the
method call. We can also specify the column span (width) or
rowspan(height) of a widget.

This is a more organized way to place the widgets to the python


application. The syntax to use the grid() is given below.
Syntax
1. [Link](options)

A list of possible options that can be passed inside the grid()


method is given below.

• Column
The column number in which the widget is to be placed. The
leftmost column is represented by 0.
• Columnspan
The width of the widget. It represents the number of
columns up to which, the column is expanded.
• ipadx, ipady
It represents the number of pixels to pad the widget inside
the widget's border.
• padx, pady
It represents the number of pixels to pad the widget outside
the widget's border.
• row
The row number in which the widget is to be placed. The
topmost row is represented by 0.
• rowspan
The height of the widget, i.e. the number of the row up to
which the widget is expanded.
• Sticky
If the cell is larger than a widget, then sticky is used to
specify the position of the widget inside the cell. It may be
the concatenation of the sticky letters representing the
position of the widget. It may be N, E, W, S, NE, NW, NS,
EW, ES.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. parent = Tk()
4. name = Label(parent,text = "Name").grid(row = 0, column
= 0)
5. e1 = Entry(parent).grid(row = 0, column = 1)
6. password = Label(parent,text = "Password").grid(row = 1, c
olumn = 0)
7. e2 = Entry(parent).grid(row = 1, column = 1)
8. submit = Button(parent, text = "Submit").grid(row = 4, colu
mn = 0)
9. [Link]()

Output:

Python Tkinter place() method


The place() geometry manager organizes the widgets to the
specific x and y coordinates.

Syntax
1. [Link](options)

A list of possible options is given below.

o Anchor: It represents the exact position of the widget within


the container. The default value (direction) is NW (the upper
left corner)
o bordermode: The default value of the border type is INSIDE
that refers to ignore the parent's inside the border. The other
option is OUTSIDE.
o height, width: It refers to the height and width in pixels.
o relheight, relwidth: It is represented as the float between
0.0 and 1.0 indicating the fraction of the parent's height and
width.
o relx, rely: It is represented as the float between 0.0 and 1.0
that is the offset in the horizontal and vertical direction.
o x, y: It refers to the horizontal and vertical offset in the pixels.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. top = Tk()
4. [Link]("400x250")
5. name = Label(top, text = "Name").place(x = 30,y = 50)
6. email = Label(top, text = "Email").place(x = 30, y = 90)
7. password = Label(top, text = "Password").place(x = 30, y =
130)
8. e1 = Entry(top).place(x = 80, y = 50)
9. e2 = Entry(top).place(x = 80, y = 90)
10. e3 = Entry(top).place(x = 95, y = 130)
11. [Link]()

Output:
SN Option Description

1 activebackground It represents the background of the button when the mouse hover the button.

2 activeforeground It represents the font color of the button when the mouse hover the button.

3 Bd It represents the border width in pixels.

4 Bg It represents the background color of the button.

5 Command It is set to the function call which is scheduled when the function is called.

6 Fg Foreground color of the button.

7 Font The font of the button text.

8 Height The height of the button. The height is represented in the number of text lines
for the textual lines or the number of pixels for the images.

10 Highlightcolor The color of the highlight when the button has the focus.

11 Image It is set to the image displayed on the button.

12 justify It illustrates the way by which the multiple text lines are represented. It is set
to LEFT for left justification, RIGHT for the right justification, and CENTER for
the center.

13 Padx Additional padding to the button in the horizontal direction.

14 pady Additional padding to the button in the vertical direction.

15 Relief It represents the type of the border. It can be SUNKEN, RAISED, GROOVE, and
RIDGE.
17 State This option is set to DISABLED to make the button unresponsive. The ACTIVE
represents the active state of the button.

18 Underline Set this option to make the button text underlined.

19 Width The width of the button. It exists as a number of letters for textual buttons or
pixels for image buttons.

20 Wraplength If the value is set to a positive number, the text lines will be wrapped to fit
within this length.

Python Tkinter Button


The button widget is used to add various types of buttons to the python
application. Python allows us to configure the look of the button according
to our requirements. Various options can be set or reset depending upon
the requirements.

We can also associate a method or function with a button which is called


when the button is pressed.

The syntax to use the button widget is given below.

Syntax
1. W = Button(parent, options)

A list of possible options is given below.

Example
1. #python application to create a simple button
2.
3. from tkinter import *
4.
5.
6. top = Tk()
7.
8. [Link]("200x100")
9.
10.b = Button(top,text = "Simple")
11.
[Link]()
13.
[Link]()

Output:

Example
1. from tkinter import *
2.
3. top = Tk()
4.
5. [Link]("200x100")
6.
7. def fun():
8. [Link]("Hello", "Red Button clicked")
9.
10.
11. b1 = Button(top,text = "Red",command = fun,activeforegroun
d = "red",activebackground = "pink",pady=10)
12.
13. b2 = Button(top, text = "Blue",activeforeground = "blue",acti
vebackground = "pink",pady=10)
14.
15. b3 = Button(top, text = "Green",activeforeground = "green",a
ctivebackground = "pink",pady = 10)
16.
17. b4 = Button(top, text = "Yellow",activeforeground = "yellow",
activebackground = "pink",pady = 10)
18.
19. [Link](side = LEFT)
20.
21. [Link](side = RIGHT)
22.
23. [Link](side = TOP)
24.
25. [Link](side = BOTTOM)
26.
27. [Link]()

Output:

SN Option Description

1 bd The represents the border width. The default width is 2.

2 bg It represents the background color of the canvas.

3 confine It is set to make the canvas unscrollable outside the scroll region.

4 cursor The cursor is used as the arrow, circle, dot, etc. on the canvas.

5 height It represents the size of the canvas in the vertical direction.

6 highlightcolor It represents the highlight color when the widget is focused.

7 relief It represents the type of the border. The possible values are SUNKEN, RAISED

8 scrollregion It represents the coordinates specified as the tuple containing the area of the

9 width It represents the width of the canvas.


10 xscrollincrement If it is set to a positive value. The canvas is placed only to the multiple of this

11 xscrollcommand If the canvas is scrollable, this attribute should be the .set() method of the ho

12 yscrollincrement Works like xscrollincrement, but governs vertical movement.

13 yscrollcommand If the canvas is scrollable, this attribute should be the .set() method of the ve

Python Tkinter Canvas


The canvas widget is used to add the structured graphics to the python
application. It is used to draw the graph and plots to the python application.
The syntax to use the canvas is given below.

Syntax
1. w = canvas(parent, options)

A list of possible options is given below.

Example
1. from tkinter import *
2.
3. top = Tk()
4.
5. [Link]("200x200")
6.
7. #creating a simple canvas
8. c = Canvas(top,bg = "pink",height = "200")
9.
10.
11. [Link]()
12.
13. [Link]()

Output:

Example: Creating an arc


1. from tkinter import *
2.
3. top = Tk()
4.
5. [Link]("200x200")
6.
7. #creating a simple canvas
8. c = Canvas(top,bg = "pink",height = "200",width = 200)
9.
[Link] = c.create_arc((5,10,150,200),start = 0,extent = 150, fill= "white")
11.
[Link]()
13.
[Link]()
Output:

Python Tkinter Checkbutton


The Checkbutton is used to track the user's choices provided to the
application. In other words, we can say that Checkbutton is used to
implement the on/off selections.

The Checkbutton can contain the text or images. The Checkbutton is mostly
used to provide many choices to the user among which, the user needs to
choose the one. It generally implements many of many selections.

The syntax to use the checkbutton is given below.

Syntax
1. w = checkbutton(master, options)

A list of possible options is given below.


SN Option Description

1 activebackground It represents the background color when the checkbutton is under the cursor.

2 activeforeground It represents the foreground color of the checkbutton when the checkbutton is
under the cursor.

3 bg The background color of the button.

4 bitmap It displays an image (monochrome) on the button.

5 bd The size of the border around the corner.

6 command It is associated with a function to be called when the state of the checkbutton
is changed.

7 cursor The mouse pointer will be changed to the cursor name when it is over the
checkbutton.

8 disableforeground It is the color which is used to represent the text of a disabled checkbutton.

9 font It represents the font of the checkbutton.

10 fg The foreground color (text color) of the checkbutton.

11 height It represents the height of the checkbutton (number of lines). The default
height is 1.

12 highlightcolor The color of the focus highlight when the checkbutton is under focus.

13 image The image used to represent the checkbutton.

14 justify This specifies the justification of the text if the text contains multiple lines.

15 offvalue The associated control variable is set to 0 by default if the button is unchecked.
We can change the state of an unchecked variable to some other one.

16 onvalue The associated control variable is set to 1 by default if the button is checked.
We can change the state of the checked variable to some other one.

17 padx The horizontal padding of the checkbutton


18 pady The vertical padding of the checkbutton.

19 relief The type of the border of the checkbutton. By default, it is set to FLAT.

20 selectcolor The color of the checkbutton when it is set. By default, it is red.

21 selectimage The image is shown on the checkbutton when it is set.

22 state It represents the state of the checkbutton. By default, it is set to normal. We


can change it to DISABLED to make the checkbutton unresponsive. The state
of the checkbutton is ACTIVE when it is under focus.

24 underline It represents the index of the character in the text which is to be underlined.
The indexing starts with zero in the text.

25 variable It represents the associated variable that tracks the state of the checkbutton.

26 width It represents the width of the checkbutton. It is represented in the number of


characters that are represented in the form of texts.

27 wraplength If this option is set to an integer number, the text will be broken into the
number of pieces.

Methods
The methods that can be called with the Checkbuttons are described in the
following table.

SN Method Description

1 deselect() It is called to turn off the checkbutton.

2 flash() The checkbutton is flashed between the active and normal colors.
3 invoke() This will invoke the method associated with the checkbutton.

4 select() It is called to turn on the checkbutton.

5 toggle() It is used to toggle between the different Checkbuttons.

Example
1. from tkinter import *
2.
3. top = Tk()
4.
5. [Link]("200x200")
6.
7. checkvar1 = IntVar()
8.
9. checkvar2 = IntVar()
10.
11. checkvar3 = IntVar()
12.
13. chkbtn1 = Checkbutton(top, text = "C", variable = checkvar1,
onvalue = 1, offvalue = 0, height = 2, width = 10)
14.
15. chkbtn2 = Checkbutton(top, text = "C++", variable = checkv
ar2, onvalue = 1, offvalue = 0, height = 2, width = 10)
16.
17. chkbtn3 = Checkbutton(top, text = "Java", variable = checkv
ar3, onvalue = 1, offvalue = 0, height = 2, width = 10)
18.
19. [Link]()
20.
21. [Link]()
22.
23. [Link]()
24.
25. [Link]()

Output:
Python Tkinter Entry
The Entry widget is used to provde the single line text-box to the user to
accept a value from the user. We can use the Entry widget to accept the
text strings from the user. It can only be used for one line of text from the
user. For multiple lines of text, we must use the text widget.

The syntax to use the Entry widget is given below.

Syntax
1. w = Entry (parent, options)

A list of possible options is given below.


SN Option Description

1 bg The background color of the widget.

2 bd The border width of the widget in pixels.

3 cursor The mouse pointer will be changed to the cursor type set to the arrow, dot,
etc.

4 exportselection The text written inside the entry box will be automatically copied to the
clipboard by default. We can set the exportselection to 0 to not copy this.

5 fg It represents the color of the text.

6 font It represents the font type of the text.

7 highlightbackground It represents the color to display in the traversal highlight region when the
widget does not have the input focus.

8 highlightcolor It represents the color to use for the traversal highlight rectangle that is
drawn around the widget when it has the input focus.

9 highlightthickness It represents a non-negative value indicating the width of the highlight


rectangle to draw around the outside of the widget when it has the input
focus.

10 insertbackground It represents the color to use as background in the area covered by the
insertion cursor. This color will normally override either the normal
background for the widget.

11 insertborderwidth It represents a non-negative value indicating the width of the 3-D border to
draw around the insertion cursor. The value may have any of the forms
acceptable to Tk_GetPixels.

12 insertofftime It represents a non-negative integer value indicating the number of


milliseconds the insertion cursor should remain "off" in each blink cycle. If
this option is zero, then the cursor doesn't blink: it is on all the time.

13 insertontime Specifies a non-negative integer value indicating the number of milliseconds


the insertion cursor should remain "on" in each blink cycle.

14 insertwidth It represents the value indicating the total width of the insertion cursor. The
value may have any of the forms acceptable to Tk_GetPixels.
15 justify It specifies how the text is organized if the text contains multiple lines.

16 relief It specifies the type of the border. Its default value is FLAT.

17 selectbackground The background color of the selected text.

18 selectborderwidth The width of the border to display around the selected task.

19 selectforeground The font color of the selected task.

20 show It is used to show the entry text of some other type instead of the string.
For example, the password is typed using stars (*).

21 textvariable It is set to the instance of the StringVar to retrieve the text from the entry.

22 width The width of the displayed text or image.

23 xscrollcommand The entry widget can be linked to the horizontal scrollbar if we want the
user to enter more text then the actual width of the widget.

Example
1. # !/usr/bin/python3
2.
3. from tkinter import *
4.
5. top = Tk()
6.
7. [Link]("400x250")
8.
9. name = Label(top, text = "Name").place(x = 30,y = 50)
10.
11. email = Label(top, text = "Email").place(x = 30, y = 90)
12.
13. password = Label(top, text = "Password").place(x = 30, y = 1
30)
14.
15. sbmitbtn = Button(top, text = "Submit",activebackground = "
pink", activeforeground = "blue").place(x = 30, y = 170)
16.
17. e1 = Entry(top).place(x = 80, y = 50)
18.
19.
20.e2 = Entry(top).place(x = 80, y = 90)
21.
22.
23. e3 = Entry(top).place(x = 95, y = 130)
24.
25. [Link]()

Output:
Entry widget methods
Python provides various methods to configure the data written inside the
widget. There are the following methods provided by the Entry widget.

SN Method Description

1 delete(first, last = none) It is used to delete the specified characters inside the widget.

2 get() It is used to get the text written inside the widget.

3 icursor(index) It is used to change the insertion cursor position. We can specify the
index of the character before which, the cursor to be placed.

4 index(index) It is used to place the cursor to the left of the character written at
the specified index.

5 insert(index,s) It is used to insert the specified string before the character placed at
the specified index.

6 select_adjust(index) It includes the selection of the character present at the specified


index.

7 select_clear() It clears the selection if some selection has been done.

8 select_form(index) It sets the anchor index position to the character specified by the
index.

9 select_present() It returns true if some text in the Entry is selected otherwise returns
false.

10 select_range(start,end) It selects the characters to exist between the specified range.

11 select_to(index) It selects all the characters from the beginning to the specified index.

12 xview(index) It is used to link the entry widget to a horizontal scrollbar.


13 xview_scroll(number,what) It is used to make the entry scrollable horizontally.

Example: A simple calculator


1. import tkinter as tk
2. from functools import partial
3.
4.
5. def call_result(label_result, n1, n2):
6. num1 = ([Link]())
7. num2 = ([Link]())
8. result = int(num1)+int(num2)
9. label_result.config(text="Result = %d" % result)
10. return
11.
[Link] = [Link]()
13. [Link]('400x200+100+200')
14.
15. [Link]('Calculator')
16.
17. number1 = [Link]()
18.number2 = [Link]()
19.
20.labelNum1 = [Link](root, text="A").grid(row=1, column=0)
21.
22.labelNum2 = [Link](root, text="B").grid(row=2, column=0)
23.
[Link] = [Link](root)
25.
[Link](row=7, column=2)
27.
28.entryNum1 = [Link](root, textvariable=number1).grid(row=1, column=
2)
29.
30.entryNum2 = [Link](root, textvariable=number2).grid(row=2, column=
2)
31.
32.call_result = partial(call_result, labelResult, number1, number2)
33.
[Link] = [Link](root, text="Calculate", command=call_result).grid(
row=3, column=0)
35.
[Link]()

Output:

Python Tkinter Frame


Python Tkinter Frame widget is used to organize the group of widgets. It
acts like a container which can be used to hold the other widgets. The
rectangular areas of the screen are used to organize the widgets to the
python application.

The syntax to use the Frame widget is given below.

Syntax
1. w = Frame(parent, options)
A list of possible options is given below.

SN Option Description

1 bd It represents the border width.

2 bg The background color of the widget.

3 cursor The mouse pointer is changed to the cursor type set to different values like
an arrow, dot, etc.

4 height The height of the frame.

5 highlightbackground The color of the background color when it is under focus.

6 highlightcolor The text color when the widget is under focus.

7 highlightthickness It specifies the thickness around the border when the widget is under the
focus.

8 relief It specifies the type of the border. The default value if FLAT.

9 width It represents the width of the widget.

Example
1. from tkinter import *
2.
3. top = Tk()
4. [Link]("140x100")
5. frame = Frame(top)
6. [Link]()
7.
8. leftframe = Frame(top)
9. [Link](side = LEFT)
10.
11. rightframe = Frame(top)
[Link](side = RIGHT)
13.
14.btn1 = Button(frame, text="Submit", fg="red",activebackground = "red")

15. [Link](side = LEFT)


16.
17. btn2 = Button(frame, text="Remove", fg="brown", activeback
ground = "brown")
[Link](side = RIGHT)
19.
20.btn3 = Button(rightframe, text="Add", fg="blue", activebackground = "bl
ue")
21. [Link](side = LEFT)
22.
23. btn4 = Button(leftframe, text="Modify", fg="black", activebac
kground = "white")
[Link](side = RIGHT)
25.
[Link]()

Output:

Python Tkinter Label


The Label is used to specify the container box where we can place the text
or images. This widget is used to provide the message to the user about
other widgets used in the python application.

There are the various options which can be specified to configure the text
or the part of the text shown in the Label.

The syntax to use the Label is given below.


Syntax
1. w = Label (master, options)

A list of possible options is given below.

SN Option Description

1 anchor It specifies the exact position of the text within the size provided to the widget. The
default value is CENTER, which is used to center the text within the specified space.

2 bg The background color displayed behind the widget.

3 bitmap It is used to set the bitmap to the graphical object specified so that, the label can
represent the graphics instead of text.

4 bd It represents the width of the border. The default is 2 pixels.

5 cursor The mouse pointer will be changed to the type of the cursor specified, i.e., arrow,
dot, etc.

6 font The font type of the text written inside the widget.

7 fg The foreground color of the text written inside the widget.

8 height The height of the widget.

9 image The image that is to be shown as the label.

10 justify It is used to represent the orientation of the text if the text contains multiple lines.
It can be set to LEFT for left justification, RIGHT for right justification, and CENTER
for center justification.

11 padx The horizontal padding of the text. The default value is 1.

12 pady The vertical padding of the text. The default value is 1.

13 relief The type of the border. The default value is FLAT.


14 text This is set to the string variable which may contain one or more line of text.

15 textvariable The text written inside the widget is set to the control variable StringVar so that it
can be accessed and changed accordingly.

16 underline We can display a line under the specified letter of the text. Set this option to the
number of the letter under which the line will be displayed.

17 width The width of the widget. It is specified as the number of characters.

18 wraplength Instead of having only one line as the label text, we can break it to the number of
lines where each line has the number of characters specified to this option.

Example 1
1. # !/usr/bin/python3
2.
3. from tkinter import *
4.
5. top = Tk()
6.
7. [Link]("400x250")
8.
9. #creating label
[Link] = Label(top, text = "Username").place(x = 30,y = 50)
11.
12.#creating label
13. password = Label(top, text = "Password").place(x = 30, y = 9
0)
14.
15.
[Link] = Button(top, text = "Submit",activebackground = "pink", active
foreground = "blue").place(x = 30, y = 120)
17.
18.e1 = Entry(top,width = 20).place(x = 100, y = 50)
19.
20.
21. e2 = Entry(top, width = 20).place(x = 100, y = 90)
22.
23.
[Link]()

Output:

Python Tkinter Listbox


The Listbox widget is used to display the list items to the user. We can
place only text items in the Listbox and all text items contain the same font
and color.

The user can choose one or more items from the list depending upon the
configuration.

The syntax to use the Listbox is given below.

1. w = Listbox(parent, options)
A list of possible options is given below.

SN Option Description

1 bg The background color of the widget.

2 bd It represents the size of the border. Default value is 2 pixel.

3 cursor The mouse pointer will look like the cursor type like dot, arrow, etc.

4 font The font type of the Listbox items.

5 fg The color of the text.

6 height It represents the count of the lines shown in the Listbox. The default value is
10.

7 highlightcolor The color of the Listbox items when the widget is under focus.

8 highlightthickness The thickness of the highlight.

9 relief The type of the border. The default is SUNKEN.

10 selectbackground The background color that is used to display the selected text.

11 selectmode It is used to determine the number of items that can be selected from the list.
It can set to BROWSE, SINGLE, MULTIPLE, EXTENDED.

12 width It represents the width of the widget in characters.

13 xscrollcommand It is used to let the user scroll the Listbox horizontally.

14 yscrollcommand It is used to let the user scroll the Listbox vertically.


Methods
There are the following methods associated with the Listbox.

SN Method Description

1 activate(index) It is used to select the lines at the specified index.

2 curselection() It returns a tuple containing the line numbers of the selected element
or elements, counting from 0. If nothing is selected, returns an empty
tuple.

3 delete(first, last = None) It is used to delete the lines which exist in the given range.

4 get(first, last = None) It is used to get the list items that exist in the given range.

5 index(i) It is used to place the line with the specified index at the top of the
widget.

6 insert(index, *elements) It is used to insert the new lines with the specified number of elements
before the specified index.

7 nearest(y) It returns the index of the nearest line to the y coordinate of the
Listbox widget.

8 see(index) It is used to adjust the position of the listbox to make the lines
specified by the index visible.

9 size() It returns the number of lines that are present in the Listbox widget.

10 xview() This is used to make the widget horizontally scrollable.

11 xview_moveto(fraction) It is used to make the listbox horizontally scrollable by the fraction of


width of the longest line present in the listbox.

12 xview_scroll(number, It is used to make the listbox horizontally scrollable by the number of


what) characters specified.

13 yview() It allows the Listbox to be vertically scrollable.


14 yview_moveto(fraction) It is used to make the listbox vertically scrollable by the fraction of
width of the longest line present in the listbox.

15 yview_scroll (number, It is used to make the listbox vertically scrollable by the number of
what) characters specified.

Example 1
1. # !/usr/bin/python3
2.
3. from tkinter import *
4.
5. top = Tk()
6.
7. [Link]("200x250")
8.
9. lbl = Label(top,text = "A list of favourite countries...")
10.
11. listbox = Listbox(top)
12.
13. [Link](1,"India")
14.
15. [Link](2, "USA")
16.
17. [Link](3, "Japan")
18.
19. [Link](4, "Austrelia")
20.
21. [Link]()
[Link]()
23.
[Link]()
Output:

Example 2: Deleting the active items from the list


1. # !/usr/bin/python3
2.
3. from tkinter import *
4.
5. top = Tk()
6.
7. [Link]("200x250")
8.
9. lbl = Label(top,text = "A list of favourite countries...")
10.
11. listbox = Listbox(top)
12.
13. [Link](1,"India")
14.
15. [Link](2, "USA")
16.
17. [Link](3, "Japan")
18.
19. [Link](4, "Austrelia")
20.
21. #this button will delete the selected item from the list
22.
23. btn = Button(top, text = "delete", command = lambda listbo
x=listbox: [Link](ANCHOR))
24.
25. [Link]()
26.
27.
[Link]()
29.
[Link]()
31. [Link]()

Output:

After pressing the delete button.


Python Tkinter Menubutton
The Menubutton widget can be defined as the drop-down menu that is
shown to the user all the time. It is used to provide the user a option to
select the appropriate choice exist within the application.

The Menubutton is used to implement various types of menus in the python


application. A Menu is associated with the Menubutton that can display the
choices of the Menubutton when clicked by the user.

The syntax to use the python tkinter Menubutton is given below.

Syntax
1. w = Menubutton(Top, options)

A list of various options is given below.


SN Option Description

1 activebackground The background color of the widget when the widget is under focus.

2 activeforeground The font color of the widget text when the widget is under focus.

3 anchor It specifies the exact position of the widget content when the widget is
assigned more space than needed.

4 bg It specifies the background color of the widget.

5 bitmap It is set to the graphical content which is to be displayed to the widget.

6 bd It represents the size of the border. The default value is 2 pixels.

7 cursor The mouse pointer will be changed to the cursor type specified when the
widget is under the focus. The possible value of the cursor type is arrow, or
dot etc.

8 direction It direction can be specified so that menu can be displayed to the specified
direction of the button. Use LEFT, RIGHT, or ABOVE to place the widget
accordingly.

9 disabledforeground The text color of the widget when the widget is disabled.

10 fg The normal foreground color of the widget.

11 height The vertical dimension of the Menubutton. It is specified as the number of


lines.

12 highlightcolor The highlight color shown to the widget under focus.

13 image The image displayed on the widget.

14 justify This specified the exact position of the text under the widget when the text
is unable to fill the width of the widget. We can use the LEFT for the left
justification, RIGHT for the right justification, CENTER for the centre
justification.

15 menu It represents the menu specified with the Menubutton.

16 padx The horizontal padding of the widget.


17 pady The vertical padding of the widget.

18 relief This option specifies the type of the border. The default value is RAISED.

19 state The normal state of the Mousebutton is enabled. We can set it to DISABLED
to make it unresponsive.

20 text The text shown with the widget.

21 textvariable We can set the control variable of string type to the text variable so that we
can control the text of the widget at runtime.

22 underline The text of the widget is not underlined by default but we can set this option
to make the text of the widget underlined.

23 width It represents the width of the widget in characters. The default value is 20.

24 wraplength We can break the text of the widget in the number of lines so that the text
contains the number of lines not greater than the specified value.

Example
1. # !/usr/bin/python3
2.
3. from tkinter import *
4.
5. top = Tk()
6.
7. [Link]("200x250")
8.
9. menubutton = Menubutton(top, text = "Language", relief = FLAT)
10.
11. [Link]()
12.
13. [Link] = Menu(menubutton)
14.
15. menubutton["menu"]=[Link]
16.
17. [Link].add_checkbutton(label = "Hindi", variable
=IntVar())
18.
19. [Link].add_checkbutton(label = "English", variabl
e = IntVar())
20.
21. [Link]()
22.
23. [Link]()

Output:

Python Tkinter Menu


The Menu widget is used to create various types of menus (top level, pull
down, and pop up) in the python application.

The top-level menus are the one which is displayed just under the title bar
of the parent window. We need to create a new instance of the Menu widget
and add various commands to it by using the add() method.

The syntax to use the Menu widget is given below.

Syntax
1. w = Menu(top, options)

A list of possible options is given below.


SN Option Description

1 activebackground The background color of the widget when the widget is under the focus.

2 activeborderwidth The width of the border of the widget when it is under the mouse. The default
is 1 pixel.

3 activeforeground The font color of the widget when the widget has the focus.

4 bg The background color of the widget.

5 bd The border width of the widget.

6 cursor The mouse pointer is changed to the cursor type when it hovers the widget.
The cursor type can be set to arrow or dot.

7 disabledforeground The font color of the widget when it is disabled.

8 font The font type of the text of the widget.

9 fg The foreground color of the widget.

10 postcommand The postcommand can be set to any of the function which is called when the
mourse hovers the menu.

11 relief The type of the border of the widget. The default type is RAISED.

12 image It is used to display an image on the menu.

13 selectcolor The color used to display the checkbutton or radiobutton when they are
selected.

14 tearoff By default, the choices in the menu start taking place from position 1. If we
set the tearoff = 1, then it will start taking place from 0th position.

15 title Set this option to the title of the window if you want to change the title of the
window.
Methods
The Menu widget contains the following methods.

SN Option Description

1 add_command(options) It is used to add the Menu items to the menu.

2 add_radiobutton(options) This method adds the radiobutton to the menu.

3 add_checkbutton(options) This method is used to add the checkbuttons to the menu.

4 add_cascade(options) It is used to create a hierarchical menu to the parent menu by


associating the given menu to the parent menu.

5 add_seperator() It is used to add the seperator line to the menu.

6 add(type, options) It is used to add the specific menu item to the menu.

7 delete(startindex, It is used to delete the menu items exist in the specified range.
endindex)

8 entryconfig(index, options) It is used to configure a menu item identified by the given index.

9 index(item) It is used to get the index of the specified menu item.

10 insert_seperator(index) It is used to insert a seperator at the specified index.

11 invoke(index) It is used to invoke the associated with the choice given at the
specified index.

12 type(index) It is used to get the type of the choice specified by the index.
Creating a top level menu
A top-level menu can be created by instantiating the Menu widget and
adding the menu items to the menu.

Example 1
1. # !/usr/bin/python3
2.
3. from tkinter import *
4.
5. top = Tk()
6.
7. def hello():
8. print("hello!")
9.
10.# create a toplevel menu
11. menubar = Menu(root)
[Link].add_command(label="Hello!", command=hello)
13. menubar.add_command(label="Quit!", command=[Link])
14.
15. # display the menu
[Link](menu=menubar)
17.
[Link]()

Output:
Clicking the hello Menubutton will print the hello on the console while
clicking the Quit Menubutton will make an exit from the python application.

Example 2
1. from tkinter import Toplevel, Button, Tk, Menu
2.
3. top = Tk()
4. menubar = Menu(top)
5. file = Menu(menubar, tearoff=0)
6. file.add_command(label="New")
7. file.add_command(label="Open")
8. file.add_command(label="Save")
9. file.add_command(label="Save as...")
[Link].add_command(label="Close")
11.
[Link].add_separator()
13.
[Link].add_command(label="Exit", command=[Link])
15.
[Link].add_cascade(label="File", menu=file)
17. edit = Menu(menubar, tearoff=0)
[Link].add_command(label="Undo")
19.
[Link].add_separator()
21.
[Link].add_command(label="Cut")
23. edit.add_command(label="Copy")
[Link].add_command(label="Paste")
25. edit.add_command(label="Delete")
[Link].add_command(label="Select All")
27.
[Link].add_cascade(label="Edit", menu=edit)
29. help = Menu(menubar, tearoff=0)
[Link].add_command(label="About")
31. menubar.add_cascade(label="Help", menu=help)
32.
33. [Link](menu=menubar)
[Link]()

Output:

Python Tkinter Message


The Message widget is used to show the message to the user regarding the
behaviour of the python application. The message widget shows the text
messages to the user which can not be edited.

The message text contains more than one line. However, the message can
only be shown in the single font.

The syntax to use the Message widget is given below.

Syntax
1. w = Message(parent, options)

A list of possible options is given below.


SN Option Description

1 anchor It is used to decide the exact position of the text within the space provided to the
widget if the widget contains more space than the need of the text. The default is
CENTER.

2 bg The background color of the widget.

3 bitmap It is used to display the graphics on the widget. It can be set to any graphical or
image object.

4 bd It represents the size of the border in the pixel. The default size is 2 pixel.

5 cursor The mouse pointer is changed to the specified cursor type. The cursor type can be
an arrow, dot, etc.

6 font The font type of the widget text.

7 fg The font color of the widget text.

8 height The vertical dimension of the message.

9 image We can set this option to a static image to show that onto the widget.

10 justify This option is used to specify the alignment of multiple line of code with respect to
each other. The possible values can be LEFT (left alignment), CENTER (default), and
RIGHT (right alignment).

11 padx The horizontal padding of the widget.

12 pady The vertical padding of the widget.

13 relief It represents the type of the border. The default type is FLAT.

14 text We can set this option to the string so that the widget can represent the specified
text.

15 textvariable This is used to control the text represented by the widget. The textvariable can be
set to the text that is shown in the widget.
16 underline The default value of this option is -1 that represents no underline. We can set this
option to an existing number to specify that nth letter of the string will be underlined.

17 width It specifies the horizontal dimension of the widget in the number of characters (not
pixel).

18 wraplength We can wrap the text to the number of lines by setting this option to the desired
number so that each line contains only that number of characters.

Example
1. from tkinter import *
2.
3. top = Tk()
4. [Link]("100x100")
5. var = StringVar()
6. msg = Message( top, text = "Welcome to Javatpoint")
7.
8. [Link]()
9. [Link]()

Output:
Python Tkinter Radiobutton
The Radiobutton widget is used to implement one-of-many selection in the
python application. It shows multiple choices to the user out of which, the
user can select only one out of them. We can associate different methods
with each of the radiobutton.

We can display the multiple line text or images on the radiobuttons. To


keep track the user's selection the radiobutton, it is associated with a single
variable. Each button displays a single value for that particular variable.

The syntax to use the Radiobutton is given below.

Syntax
1. w = Radiobutton(top, options)
SN Option Description

1 activebackground The background color of the widget when it has the focus.

2 activeforeground The font color of the widget text when it has the focus.

3 anchor It represents the exact position of the text within the widget if the widget
contains more space than the requirement of the text. The default value is
CENTER.

4 bg The background color of the widget.

5 bitmap It is used to display the graphics on the widget. It can be set to any
graphical or image object.

6 borderwidth It represents the size of the border.

7 command This option is set to the procedure which must be called every-time when
the state of the radiobutton is changed.

8 cursor The mouse pointer is changed to the specified cursor type. It can be set to
the arrow, dot, etc.

9 font It represents the font type of the widget text.

10 fg The normal foreground color of the widget text.

11 height The vertical dimension of the widget. It is specified as the number of lines
(not pixel).

12 highlightcolor It represents the color of the focus highlight when the widget has the focus.

13 highlightbackground The color of the focus highlight when the widget is not having the focus.

14 image It can be set to an image object if we want to display an image on the


radiobutton instead the text.

15 justify It represents the justification of the multi-line text. It can be set to


CENTER(default), LEFT, or RIGHT.

16 padx The horizontal padding of the widget.

17 pady The vertical padding of the widget.


18 relief The type of the border. The default value is FLAT.

19 selectcolor The color of the radio button when it is selected.

20 selectimage The image to be displayed on the radiobutton when it is selected.

21 state It represents the state of the radio button. The default state of the
Radiobutton is NORMAL. However, we can set this to DISABLED to make
the radiobutton unresponsive.

22 text The text to be displayed on the radiobutton.

23 textvariable It is of String type that represents the text displayed by the widget.

24 underline The default value of this option is -1, however, we can set this option to
the number of character which is to be underlined.

25 value The value of each radiobutton is assigned to the control variable when it is
turned on by the user.

26 variable It is the control variable which is used to keep track of the user's choices.
It is shared among all the radiobuttons.

27 width The horizontal dimension of the widget. It is represented as the number of


characters.

28 wraplength We can wrap the text to the number of lines by setting this option to the
desired number so that each line contains only that number of characters.
Methods
The radiobutton widget provides the following methods.

SN Method Description

1 deselect() It is used to turn of the radiobutton.

2 flash() It is used to flash the radiobutton between its active and normal colors few times.

3 invoke() It is used to call any procedure associated when the state of a Radiobutton is
changed.

4 select() It is used to select the radiobutton.

Example
1. from tkinter import *
2.
3. def selection():
4. selection = "You selected the option " + str([Link]())
5. [Link](text = selection)
6.
7. top = Tk()
8. [Link]("300x150")
9. radio = IntVar()
[Link] = Label(text = "Favourite programming language:")
11. [Link]()
12.R1 = Radiobutton(top, text="C", variable=radio, value=1,
13. command=selection)
[Link]( anchor = W )
15.
16.R2 = Radiobutton(top, text="C++", variable=radio, value=2,
17. command=selection)
[Link]( anchor = W )
19.
20.R3 = Radiobutton(top, text="Java", variable=radio, value=3,
21. command=selection)
[Link]( anchor = W)
23.
[Link] = Label(top)
25. [Link]()
[Link]()

Output:

Python Tkinter Scale


The Scale widget is used to implement the graphical slider to the python
application so that the user can slide through the range of values shown on
the slider and select the one among them.

We can control the minimum and maximum values along with the resolution
of the scale. It provides an alternative to the Entry widget when the user is
forced to select only one value from the given range of values.

The syntax to use the Scale widget is given below.

Syntax
1. w = Scale(top, options)

A list of possible options is given below.


SN Option Description

1 activebackground The background color of the widget when it has the focus.

2 bg The background color of the widget.

3 bd The border size of the widget. The default is 2 pixel.

4 command It is set to the procedure which is called each time when we move the slider.
If the slider is moved rapidly, the callback is done when it settles.

5 cursor The mouse pointer is changed to the cursor type assigned to this option. It
can be an arrow, dot, etc.

6 digits If the control variable used to control the scale data is of string type, this
option is used to specify the number of digits when the numeric scale is
converted to a string.

7 font The font type of the widget text.

8 fg The foreground color of the text.

9 from_ It is used to represent one end of the widget range.

10 highlightbackground The highlight color when the widget doesn't have the focus.

11 highlighcolor The highlight color when the widget has the focus.

12 label This can be set to some text which can be shown as a label with the scale.
It is shown in the top left corner if the scale is horizontal or the top right
corner if the scale is vertical.

13 length It represents the length of the widget. It represents the X dimension if the
scale is horizontal or y dimension if the scale is vertical.

14 orient It can be set to horizontal or vertical depending upon the type of the scale.

15 relief It represents the type of the border. The default is FLAT.


16 repeatdelay This option tells the duration up to which the button is to be pressed before
the slider starts moving in that direction repeatedly. The default is 300 ms.

17 resolution It is set to the smallest change which is to be made to the scale value.

18 showvalue The value of the scale is shown in the text form by default. We can set this
option to 0 to suppress the label.

19 sliderlength It represents the length of the slider window along the length of the scale.
The default is 30 pixels. However, we can change it to the appropriate value.

20 state The scale widget is active by default. We can set this to DISABLED to make
it unresponsive.

21 takefocus The focus cycles through the scale widgets by default. We can set this option
to 0 if we don't want this to happen.

22 tickinterval The scale values are displayed on the multiple of the specified tick interval.
The default value of the tickinterval is 0.

23 to It represents a float or integer value that specifies the other end of the range
represented by the scale.

24 troughcolor It represents the color of the through.

25 variable It represents the control variable for the scale.

26 width It represents the width of the through part of the widget.

Methods
SN Method Description

1 get() It is used to get the current value of the scale.

2 set(value) It is used to set the value of the scale.


Example
1. from tkinter import *
2.
3. def select():
4. sel = "Value = " + str([Link]())
5. [Link](text = sel)
6.
7. top = Tk()
8. [Link]("200x100")
9. v = DoubleVar()
[Link] = Scale( top, variable = v, from_ = 1, to = 50, orient = HORIZONTA
L)
11. [Link](anchor=CENTER)
12.
13. btn = Button(top, text="Value", command=select)
[Link](anchor=CENTER)
15.
[Link] = Label(top)
17. [Link]()
18.
19. [Link]()

Output:
Python Tkinter Scrollbar
The scrollbar widget is used to scroll down the content of the other widgets
like listbox, text, and canvas. However, we can also create the horizontal
scrollbars to the Entry widget.

The syntax to use the Scrollbar widget is given below.

Syntax
1. w = Scrollbar(top, options)

A list of possible options is given below.


SN Option Description

1 activebackground The background color of the widget when it has the focus.

2 bg The background color of the widget.

3 bd The border width of the widget.

4 command It can be set to the procedure associated with the list which can be called
each time when the scrollbar is moved.

5 cursor The mouse pointer is changed to the cursor type set to this option which
can be an arrow, dot, etc.

6 elementborderwidth It represents the border width around the arrow heads and slider. The
default value is -1.

7 Highlightbackground The focus highlighcolor when the widget doesn't have the focus.

8 highlighcolor The focus highlighcolor when the widget has the focus.

9 highlightthickness It represents the thickness of the focus highlight.

10 jump It is used to control the behavior of the scroll jump. If it set to 1, then the
callback is called when the user releases the mouse button.

11 orient It can be set to HORIZONTAL or VERTICAL depending upon the orientation


of the scrollbar.

12 repeatdelay This option tells the duration up to which the button is to be pressed before
the slider starts moving in that direction repeatedly. The default is 300 ms.

13 repeatinterval The default value of the repeat interval is 100.

14 takefocus We can tab the focus through this widget by default. We can set this option
to 0 if we don't want this behavior.

15 troughcolor It represents the color of the trough.


16 width It represents the width of the scrollbar.

Methods
The widget provides the following methods.

SN Method Description

1 get() It returns the two numbers a and b which represents the current position of the
scrollbar.

2 set(first, It is used to connect the scrollbar to the other widget w. The yscrollcommand or
last) xscrollcommand of the other widget to this method.

Example
1. from tkinter import *
2.
3. top = Tk()
4. sb = Scrollbar(top)
5. [Link](side = RIGHT, fill = Y)
6.
7. mylist = Listbox(top, yscrollcommand = [Link] )
8.
9. for line in range(30):
10. [Link](END, "Number " + str(line))
11.
[Link]( side = LEFT )
13. [Link]( command = [Link] )
14.
15. mainloop()

Output:
Python Tkinter Text
The Text widget is used to show the text data on the Python application.
However, Tkinter provides us the Entry widget which is used to implement
the single line text box.

The Text widget is used to display the multi-line formatted text with various
styles and attributes. The Text widget is mostly used to provide the text
editor to the user.

The Text widget also facilitates us to use the marks and tabs to locate the
specific sections of the Text. We can also use the windows and images with
the Text as it can also be used to display the formatted text.

The syntax to use the Text widget is given below.

Syntax
1. w = Text(top, options)

A list of possible options that can be used with the Text widget is given
below.
SN Option Description

1 bg The background color of the widget.

2 bd It represents the border width of the widget.

3 cursor The mouse pointer is changed to the specified cursor type, i.e. arrow, dot,
etc.

4 exportselection The selected text is exported to the selection in the window manager. We
can set this to 0 if we don't want the text to be exported.

5 font The font type of the text.

6 fg The text color of the widget.

7 height The vertical dimension of the widget in lines.

8 highlightbackground The highlightcolor when the widget doesn't has the focus.

9 highlightthickness The thickness of the focus highlight. The default value is 1.

10 highlighcolor The color of the focus highlight when the widget has the focus.

11 insertbackground It represents the color of the insertion cursor.

12 insertborderwidth It represents the width of the border around the cursor. The default is 0.

13 insertofftime The time amount in Milliseconds during which the insertion cursor is off in
the blink cycle.

14 insertontime The time amount in Milliseconds during which the insertion cursor is on in
the blink cycle.

15 insertwidth It represents the width of the insertion cursor.

16 padx The horizontal padding of the widget.


17 pady The vertical padding of the widget.

18 relief The type of the border. The default is SUNKEN.

19 selectbackground The background color of the selected text.

20 selectborderwidth The width of the border around the selected text.

21 spacing1 It specifies the amount of vertical space given above each line of the text.
The default is 0.

22 spacing2 This option specifies how much extra vertical space to add between
displayed lines of text when a logical line wraps. The default is 0.

23 spacing3 It specifies the amount of vertical space to insert below each line of the text.

24 state It the state is set to DISABLED, the widget becomes unresponsive to the
mouse and keyboard unresponsive.

25 tabs This option controls how the tab character is used to position the text.

26 width It represents the width of the widget in characters.

27 wrap This option is used to wrap the wider lines into multiple lines. Set this option
to the WORD to wrap the lines after the word that fit into the available
space. The default value is CHAR which breaks the line which gets too wider
at any character.

28 xscrollcommand To make the Text widget horizontally scrollable, we can set this option to
the set() method of Scrollbar widget.

29 yscrollcommand To make the Text widget vertically scrollable, we can set this option to the
set() method of Scrollbar widget.
Methods
We can use the following methods with the Text widget.

SN Method Description

1 delete(startindex, This method is used to delete the characters of the specified range.
endindex)

2 get(startindex, It returns the characters present in the specified range.


endindex)

3 index(index) It is used to get the absolute index of the specified index.

4 insert(index, string) It is used to insert the specified string at the given index.

5 see(index) It returns a boolean value true or false depending upon whether the text
at the specified index is visible or not.

Mark handling methods


Marks are used to bookmark the specified position between the characters
of the associated text.

SN Method Description

1 index(mark) It is used to get the index of the specified mark.

2 mark_gravity(mark, gravity) It is used to get the gravity of the given mark.

3 mark_names() It is used to get all the marks present in the Text widget.

4 mark_set(mark, index) It is used to inform a new position of the given mark.

5 mark_unset(mark) It is used to remove the given mark from the text.


Tag handling methods
The tags are the names given to the separate areas of the text. The tags
are used to configure the different areas of the text separately. The list of
tag-handling methods along with the description is given below.

SN Method Description

1 tag_add(tagname, startindex, This method is used to tag the string present in the
endindex) specified range.

2 tag_config This method is used to configure the tag properties.

3 tag_delete(tagname) This method is used to delete a given tag.

4 tag_remove(tagname, startindex, This method is used to remove a tag from the specified
endindex) range.

Example
1. from tkinter import *
2.
3. top = Tk()
4. text = Text(top)
5. [Link](INSERT, "Name.....")
6. [Link](END, "Salary.....")
7.
8. [Link]()
9.
[Link].tag_add("Write Here", "1.0", "1.4")
11. text.tag_add("Click Here", "1.8", "1.13")
12.
13. text.tag_config("Write Here", background="yellow", foregroun
d="black")
[Link].tag_config("Click Here", background="black", foreground="white")
15.
[Link]()

Output:
Tkinter Toplevel
The Toplevel widget is used to create and display the toplevel windows
which are directly managed by the window manager. The toplevel widget
may or may not have the parent window on the top of them.

The toplevel widget is used when a python application needs to represent


some extra information, pop-up, or the group of widgets on the new
window.

The toplevel windows have the title bars, borders, and other window
decorations.

The syntax to use the Toplevel widget is given below.

Syntax
1. w = Toplevel(options)

A List of possible options is given below.


SN Options Description

1 bg It represents the background color of the window.

2 bd It represents the border size of the window.

3 cursor The mouse pointer is changed to the cursor type set to the arrow, dot, etc. when the
mouse is in the window.

4 class_ The text selected in the text widget is exported to be selected to the window manager.
We can set this to 0 to make this behavior false.

5 font The font type of the text inserted into the widget.

6 fg The foreground color of the widget.

7 height It represents the height of the window.

8 relief It represents the type of the window.

9 width It represents the width of the window,


Methods
The methods associated with the Toplevel widget is given in the following
list.

SN Method Description

1 deiconify() This method is used to display the window.

2 frame() It is used to show a system dependent window identifier.

3 group(window) It is used to add this window to the specified window group.

4 iconify() It is used to convert the toplevel window into an icon.

5 protocol(name, It is used to mention a function which will be called for the specific
function) protocol.

6 state() It is used to get the current state of the window. Possible values are
normal, iconic, withdrawn, and icon.

7 transient([master]) It is used to convert this window to a transient window (temporary).

8 withdraw() It is used to delete the window but doesn't destroy it.

9 maxsize(width, height) It is used to declare the maximum size for the window.

10 minsize(width, height) It is used to declare the minimum size for the window.

11 positionfrom(who) It is used to define the position controller.

12 resizable(width, It is used to control whether the window can be resizable or not.


height)

13 sizefrom(who) It is used to define the size controller.

14 title(string) It is used to define the title for the window.


Example
1. from tkinter import *
2.
3. root = Tk()
4.
5. [Link]("200x200")
6.
7. def open():
8. top = Toplevel(root)
9. [Link]()
10.
11. btn = Button(root, text = "open", command = open)
12.
13. [Link](x=75,y=50)
14.
15. [Link]()

Output:
Python Tkinter Spinbox
The Spinbox widget is an alternative to the Entry widget. It provides the
range of values to the user, out of which, the user can select the one.

It is used in the case where a user is given some fixed number of values to
choose from.

We can use various options with the Spinbox to decorate the widget. The
syntax to use the Spinbox is given below.

Syntax
1. w = Spinbox(top, options)

A list of possible options is given below.


SN Option Description

1 activebackground The background color of the widget when it has the focus.

2 bg The background color of the widget.

3 bd The border width of the widget.

4 command The associated callback with the widget which is called each time the state
of the widget is called.

5 cursor The mouse pointer is changed to the cursor type assigned to this option.

6 disabledbackground The background color of the widget when it is disabled.

7 disabledforeground The foreground color of the widget when it is disabled.

8 fg The normal foreground color of the widget.

9 font The font type of the widget content.

10 format This option is used for the format string. It has no default value.

11 from_ It is used to show the starting range of the widget.

12 justify It is used to specify the justification of the multi-line widget content. The
default is LEFT.

13 relief It is used to specify the type of the border. The default is SUNKEN.

14 repeatdelay This option is used to control the button auto repeat. The value is given in
milliseconds.

15 repeatinterval It is similar to repeatdelay. The value is given in milliseconds.

16 state It represents the state of the widget. The default is NORMAL. The possible
values are NORMAL, DISABLED, or "readonly".
17 textvariable It is like a control variable which is used to control the behaviour of the
widget text.

18 to It specify the maximum limit of the widget value. The other is specified by
the from_ option.

19 validate This option controls how the widget value is validated.

20 validatecommand It is associated to the function callback which is used for the validation of
the widget content.

21 values It represents the tuple containing the values for this widget.

22 vcmd It is same as validation command.

23 width It represents the width of the widget.

24 wrap This option wraps up the up and down button the Spinbox.

25 xscrollcommand This options is set to the set() method of scrollbar to make this widget
horizontally scrollable.

Methods
There are the following methods associated with the widget.

SN Option Description

1 delete(startindex, This method is used to delete the characters present at the specified
endindex) range.

2 get(startindex, endindex) It is used to get the characters present in the specified range.

3 identify(x, y) It is used to identify the widget's element within the specified range.

4 index(index) It is used to get the absolute value of the given index.


5 insert(index, string) This method is used to insert the string at the specified index.

6 invoke(element) It is used to invoke the callback associated with the widget.

Example
1. from tkinter import *
2.
3. top = Tk()
4.
5. [Link]("200x200")
6.
7. spin = Spinbox(top, from_= 0, to = 25)
8.
9. [Link]()
10. [Link]()
11. Output:

12.
Tkinter PanedWindow
The PanedWindow widget acts like a Container widget which contains one
or more child widgets (panes) arranged horizontally or vertically. The child
panes can be resized by the user, by moving the separator lines known as
sashes by using the mouse.

Each pane contains only one widget. The PanedWindow is used to


implement the different layouts in the python applications.

The syntax to use the PanedWindow is given below.

Syntax
1. w= PanedWindow(master, options)

A list of possible options is given below.

SN Option Description

1 bg It represents the background color of the


widget when it doesn't have the focus.

2 bd It represents the 3D border size of the widget.


The default option specifies that the trough
contains no border whereas the arrowheads
and slider contain the 2-pixel border size.

3 borderwidth It represents the border width of the widget.


The default is 2 pixel.

4 cursor The mouse pointer is changed to the specified


cursor type when it is over the window.

5 handlepad This option represents the distance between


the handle and the end of the sash. For the
horizontal orientation, it is the distance
between the top of the sash and the handle.
The default is 8 pixels.
6 handlesize It represents the size of the handle. The default
size is 8 pixels. However, the handle will always
be a square.

7 height It represents the height of the widget. If we do


not specify the height, it will be calculated by
the height of the child window.

8 orient The orient will be set to


HORIZONTAL if we want to place the child
windows side by side. It can be set to
VERTICAL if we want to place the child
windows from top to bottom.

9 relief It represents the type of the border. The


default is FLAT.

10 sashpad It represents the padding to be done around


each sash. The default is 0.

11 sashrelief It represents the type of the border around


each of the sash. The default is FLAT.

12 sashwidth It represents the width of the sash. The default


is 2 pixels.

13 showhandle It is set to True to display the handles. The


default value is false.

14 Width It represents the width of the widget. If we


don't specify the width of the widget, it will be
calculated by the size of the child widgets.
Methods
There are the following methods that are associated with the PanedWindow.

SN Method Description

1 add(child, options) It is used to add a window to the parent window.

2 get(startindex, endindex) This method is used to get the text present at the specified range.

3 config(options) It is used to configure the widget with the specified options.

Example
1. # !/usr/bin/python3
2. from tkinter import *
3.
4. def add():
5. a = int([Link]())
6. b = int([Link]())
7. leftdata = str(a+b)
8. [Link](1,leftdata)
9.
10.w1 = PanedWindow()
11. [Link](fill = BOTH, expand = 1)
12.
13. left = Entry(w1, bd = 5)
[Link](left)
15.
16.w2 = PanedWindow(w1, orient = VERTICAL)
17. [Link](w2)
18.
19. e1 = Entry(w2)
20.e2 = Entry(w2)
21.
[Link](e1)
23. [Link](e2)
24.
25. bottom = Button(w2, text = "Add", command = add)
[Link](bottom)
27.
[Link]()

Output:

Tkinter LabelFrame
The LabelFrame widget is used to draw a border around its child widgets.
We can also display the title for the LabelFrame widget. It acts like a
container which can be used to group the number of interrelated widgets
such as Radiobuttons.

This widget is a variant of the Frame widget which has all the features of a
frame. It also can display a label.

The syntax to use the LabelFrame widget is given below.

Syntax
1. w = LabelFrame(top, options)

A list of options is given below.

SN Option Description

1 bg The background color of the widget.

2 bd It represents the size of the border shown around the indicator. The default
is 2 pixels.

3 Class The default value of the class is LabelFrame.


4 colormap This option is used to specify which colomap is to be used for this widget.
By colormap, we mean the 256 colors that are used to form the graphics.
With this option, we can reuse the colormap of another window on this
widget.

5 container If this is set to true, the LabelFrame becomes the container widget. The
default value is false.

6 cursor It can be set to a cursor type, i.e. arrow, dot, etc. the mouse pointer is
changed to the cursor type when it is over the widget.

7 fg It represents the foreground color of the widget.

8 font It represents the font type of the widget text.

9 height It represents the height of the widget.

10 labelAnchor It represents the exact position of the text within the widget. The default is
NW(north-west)

11 labelwidget It represents the widget to be used for the label. The frame uses the text
for the label if no value specified.

12 highlightbackground The color of the focus highlight border when the widget doesn't have the
focus.

13 highlightcolor The color of the focus highlight when the widget has the focus.

14 highlightthickness The width of the focus highlight border.

15 padx The horizontal padding of the widget.

16 pady The vertical padding of the widget.

17 relief It represents the border style. The default value is GROOVE.

18 text It represents the string containing the label text.

19 width It represents the width of the frame.


Example
1. # !/usr/bin/python3
2. from tkinter import *
3.
4. top = Tk()
5. [Link]("300x200")
6.
7. labelframe1 = LabelFrame(top, text="Positive Comments")
8. [Link](fill="both", expand="yes")
9.
[Link] = Label(labelframe1, text="Place to put the positive comments")

11. [Link]()
12.
13. labelframe2 = LabelFrame(top, text = "Negative Comments")

[Link](fill="both", expand = "yes")


15.
[Link] = Label(labelframe2,text = "Place to put the negative comme
nts")
17. [Link]()
18.
19. [Link]()

Output:
Tkinter messagebox
The messagebox module is used to display the message boxes in the
python applications. There are the various functions which are used to
display the relevant messages depending upon the application
requirements.

The syntax to use the messagebox is given below.

Syntax
1. messagebox.function_name(title, message [, options])
Parameters
o function_name: It represents an appropriate message box function.
o title: It is a string which is shown as a title of a message box.
o message: It is the string to be displayed as a message on the message
box.
o options: There are various options which can be used to configure the
message dialog box.

The two options that can be used are default and parent.

1. default

The default option is used to mention the types of the default button, i.e.
ABORT, RETRY, or IGNORE in the message box.

2. parent

The parent option specifies the parent window on top of which, the message
box is to be displayed.

There is one of the following functions used to show the appropriate


message boxes. All the functions are used with the same syntax but have
the specific functionalities.

1. showinfo()
The showinfo() messagebox is used where we need to show some relevant
information to the user.

Example
1. # !/usr/bin/python3
2.
3. from tkinter import *
4.
5. from tkinter import messagebox
6.
7. top = Tk()
8.
9. [Link]("100x100")
10.
11. [Link]("information","Information")
12.
13. [Link]()

Output:

2. showwarning()
This method is used to display the warning to the user. Consider the
following example.

Example
1. # !/usr/bin/python3
2. from tkinter import *
3.
4. from tkinter import messagebox
5.
6. top = Tk()
7. [Link]("100x100")
8. [Link]("warning","Warning")
9.
[Link]()
Output:

3. showerror()
This method is used to display the error message to the user. Consider the
following example.

Example
1. # !/usr/bin/python3
2. from tkinter import *
3. from tkinter import messagebox
4.
5. top = Tk()
6. [Link]("100x100")
7. [Link]("error","Error")
8. [Link]()

Output:

4. askquestion()
This method is used to ask some question to the user which can be
answered in yes or no. Consider the following example.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. from tkinter import messagebox
4.
5. top = Tk()
6. [Link]("100x100")
7. [Link]("Confirm","Are you sure?")
8. [Link]()

Output:

5. askokcancel()
This method is used to confirm the user's action regarding some application
activity. Consider the following example.

Example
1. # !/usr/bin/python3
2. from tkinter import *
3. from tkinter import messagebox
4.
5. top = Tk()
6. [Link]("100x100")
7. [Link]("Redirect","Redirecting you to [Link]
[Link]")
8. [Link]()

Output:
6. askyesno()
This method is used to ask the user about some action to which, the user
can answer in yes or no. Consider the following example.

Example
1. # !/usr/bin/python3
2. from tkinter import *
3. from tkinter import messagebox
4.
5. top = Tk()
6. [Link]("100x100")
7. [Link]("Application","Got It?")
8. [Link]()

Output:

7. askretrycancel()
ADVERTISEMENT

This method is used to ask the user about doing a particular task again or
not. Consider the following example.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. from tkinter import messagebox
4.
5. top = Tk()
6. [Link]("100x100")
7. [Link]("Application","try again?")
8.
9. [Link]()

Output:
Python File Handling
Introduction:
Python supports the file-handling process. Till now, we were taking the
input from the console and writing it back to the console to interact with
the user. Users can easily handle the files, like read and write the files in
Python. In another programming language, the file-handling process is
lengthy and complicated. But we know Python is an easy programming
language. So, like other things, file handling is also effortless and short in
Python.

Sometimes, it is not enough to only display the data on the console. The
data to be displayed may be very large, and only a limited amount of data
can be displayed on the console since the memory is volatile, it is impossible
to recover the programmatically generated data again and again.

The file handling plays an important role when the data needs to be stored
permanently into the file. A file is a named location on disk to store related
information. We can access the stored information (non-volatile) after the
program termination.

In Python, files are treated in two modes as text or binary. The file may be
in the text or binary format, and each line of a file is ended with the special
character like a comma (,) or a newline character. Python executes the
code line by line. So, it works in one line and then asks the interpreter to
start the new line again. This is a continuous process in Python.

Hence, a file operation can be done in the following order.

o Open a file
o Read or write - Performing operation
o Close the file

Opening a file
A file operation starts with the file opening. At first, open the File then
Python will start the operation. File opening is done with the open() function
in Python. This function will accepts two arguments, file name and access
mode in which the file is accessed. When we use the open() function, that
time we must be specified the mode for which the File is opening. The
function returns a file object which can be used to perform various
operations like reading, writing, etc.
Syntax:

The syntax for opening a file in Python is given below -

1. file object = open(<file-name>, <access-mode>, <buffering>)

The files can be accessed using various modes like read, write, or append.
The following are the details about the access mode to open a file.

SN Access Description
mode

1 r r means to read. So, it opens a file for read-only operation. The file pointer exists at
the beginning. The file is by default open in this mode if no access mode is passed.

2 rb It opens the file to read-only in binary format. The file pointer exists at the beginning
of the file.

3 r+ It opens the file to read and write both. The file pointer exists at the beginning of
the file.

4 rb+ It opens the file to read and write both in binary format. The file pointer exists at
the beginning of the file.

5 w It opens the file to write only. It overwrites the file if previously exists or creates a
new one if no file exists with the same name. The file pointer exists at the beginning
of the file.

6 wb It opens the file to write only in binary format. It overwrites the file if it exists
previously or creates a new one if no file exists. The file pointer exists at the
beginning of the file.

7 w+ It opens the file to write and read both. It is different from r+ in the sense that it
overwrites the previous file if one exists whereas r+ doesn't overwrite the previously
written file. It creates a new file if no file exists. The file pointer exists at the
beginning of the file.

8 wb+ It opens the file to write and read both in binary format. The file pointer exists at
the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at the end of the
previously written file if exists any. It creates a new file if no file exists with the same
name.

10 ab It opens the file in the append mode in binary format. The pointer exists at the end
of the previously written file. It creates a new file in binary format if no file exists
with the same name.

11 a+ It opens a file to append and read both. The file pointer remains at the end of the
file if a file exists. It creates a new file if no file exists with the same name.

12 ab+ It opens a file to append and read both in binary format. The file pointer remains at
the end of the file.

Let's look at the simple example to open a file named "[Link]" (stored in
the same directory) in read mode and printing its content on the console.

Program code for read mode:

It is a read operation in Python. We open an existing file with the given


code and then read it. The code is given below -

1. #opens the file [Link] in read mode


2. fileptr = open("[Link]","r")
3.
4. if fileptr:
5. print("file is opened successfully")

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

<class '_io.TextIOWrapper'>
file is opened successfully

In the above code, we have passed filename as a first argument and


opened file in read mode as we mentioned r as the second argument.
The fileptr holds the file object and if the file is opened successfully, it will
execute the print statement
Program code for Write Mode:

It is a write operation in Python. We open an existing file using the given


code and then write on it. The code is given below -

1. file = open('[Link]','w')
2. [Link]("Here we write a command")
3. [Link]("Hello users of JAVATPOINT")
4. [Link]()

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

1. > Hi
2. ERROR!
3. Traceback (most recent call last):
4. File "<stdin>", line 1, in <module>
5. NameError: name 'Hi' is not defined

The close() Method


The close method used to terminate the program. Once all the operations
are done on the file, we must close it through our Python script using
the close() method. Any unwritten information gets destroyed once
the close() method is called on a file object.

We can perform any operation on the file externally using the file system
which is the currently opened in Python; hence it is good practice to close
the file once all the operations are done. Earlier use of the close() method
can cause the of destroyed some information that you want to write in your
File.

The syntax to use the close() method is given below.

Syntax

The syntax for closing a file in Python is given below -

1. [Link]()
Consider the following example.

Program code for Closing Method:

Here we write the program code for the closing method in Python. The code
is given below -

1. # opens the file [Link] in read mode


2. fileptr = open("[Link]","r")
3.
4. if fileptr:
5. print("The existing file is opened successfully in Python")
6.
7. #closes the opened file
8. [Link]()

After closing the file, we cannot perform any operation in the file. The file
needs to be properly closed. If any exception occurs while performing some
operations in the file then the program terminates without closing the file.

We should use the following method to overcome such type of problem.

1. try:
2. fileptr = open("[Link]")
3. # perform file operations
4. finally:
5. [Link]()

The with statement


The with statement was introduced in python 2.5. The with statement is
useful in the case of manipulating the files. It is used in the scenario where
a pair of statements is to be executed with a block of code in between.

Syntax:

The syntax of with statement of a file in Python is given below -

1. with open(<file name>, <access mode>) as <file-pointer>:


2. #statement suite

The advantage of using with statement is that it provides the guarantee to


close the file regardless of how the nested block exits.
It is always suggestible to use the with statement in the case of files
because, if the break, return, or exception occurs in the nested block of
code then it automatically closes the file, we don't need to write
the close() function. It doesn't let the file to corrupt.

Program code 1 for with statement:

Here we write the program code for with statement in Python. The code is
given below -

1. with open("[Link]",'r') as f:
2. content = [Link]();
3. print(content)

Program code 2 for with statement:

Here we write the program code for with statement in Python. The code is
given below -

1. with open("[Link]", "H") as f:


2. A = [Link]("Hello Coders")
3. Print(A)

Writing the file


To write some text to a file, we need to open the file using the open method
and then we can use the write method for writing in this File. If we want to
open a file that does not exist in our system, it creates a new one. On the
other hand, if the File exists, then erase the past content and add new
content to this File. the It is done by the following access modes.

w: It will overwrite the file if any file exists. The file pointer is at the
beginning of the file.

a: It will append the existing file. The file pointer is at the end of the file. It
creates a new file if no file exists.

Program code 1 for Write Method:

Here we write the program code for write method in Python. The code is
given below -

1. # open the [Link] in append mode. Create a new file if no such file
exists.
2. fileptr = open("[Link]", "w")
3.
4. # appending the content to the file
5. [Link](''''''''Python is the modern programming language. It is
done any kind of program in shortest way.''')
6.
7. # closing the opened the file
8. [Link]()

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

[Link]
Python is the modern programming language. It is done any kind of program in shortest
way.

We have opened the file in w mode. The [Link] file doesn't exist, it created
a new file and we have written the content in the file using the write()
function

Program code 2 for Write Method:

Here we write the program code for write method in Python. The code is
given below -

1. with open([Link]', 'w') as file2:


2. [Link]('Hello coders')
3. [Link]('Welcome to Nettech)

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Hello coders
Welcome to Nettech

Program code 3 for Write Method:

Here we write the program code for write method in Python. The code is
given below -

1. #open the [Link] in write mode.


2. fileptr = open("[Link]","a")
3.
4. #overwriting the content of the file
5. [Link](" Python has an easy syntax and user-
friendly interaction.")
6.
7. #closing the opened file
8. [Link]()

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Python is the modern day language. It makes things so simple.


It is the fastest growing language Python has an easy syntax and user-friendly
interaction.

Snapshot of the [Link]

We can see that the content of the file is modified. We have opened the file
in a mode and it appended the content in the existing [Link].

To read a file using the Python script, the Python provides


the read() method. The read() method reads a string from the file. It can
read the data in the text as well as a binary format.

Syntax:

The syntax of read() method of a file in Python is given below -

1. [Link](<count>)

Here, the count is the number of bytes to be read from the file starting
from the beginning of the file. If the count is not specified, then it may read
the content of the file until the end.
Program code for read() Method:

Here we write the program code for read() method in Python. The code is
given below -

1. #open the [Link] in read mode. causes error if no such file exists.

2. fileptr = open("[Link]","r")
3. #stores all the data of the file into the variable content
4. content = [Link](10)
5. # prints the type of the data stored in the file
6. print(type(content))
7. #prints the content of the file
8. print(content)
9. #closes the opened file
[Link]()

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

<class 'str'>
Python is

In the above code, we have read the content of [Link] by using


the read() function. We have passed count value as ten which means it
will read the first ten characters from the file.

If we use the following line, then it will print all content of the file. So, it
only prints 'Python is'. For read the whole file contents, the code is given
below -

1. content = [Link]()
2. print(content)

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Python is the modern-day language. It makes things so simple.


It is the fastest-growing programming language Python has easy an syntax and user-
friendly interaction.
Read file through for loop
We can use read() method when we open the file. Read method is also
done through the for loop. We can read the file using for loop. Consider the
following example.

Program code 1 for Read File using For Loop:

Here we give an example of read file using for loop. The code is given below
-

1. #open the [Link] in read mode. causes an error if no such file exist
s.
2. fileptr = open("[Link]","r");
3. #running a for loop
4. for i in fileptr:
5. print(i) # i contains each line of the file

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Python is the modern day language.

It makes things so simple.

Python has easy syntax and user-friendly interaction.

Program code 2 for Read File using For Loop:

Here we give an example of read file using for loop. The code is given below
-

1. A = ["Hello\n", "Coders\n", "JavaTpoint\n"]


2. f1 = open('[Link]', 'w')
3. [Link](A)
4. [Link]()
5. f1 = open('[Link]', 'r')
6. Lines = [Link]()
7. count = 0
8. for line in Lines:
9. count += 1
10. print("Line{}: {}".format(count, [Link]()))

Output:

Line1: H
Line2: e
Line3: l
Line4: l
Line5: o
Line6:
Line7: C
Line8: o
Line9: d
Line10: e
Line11: r
Line12: s
Line13:
Line14: J
Line15: a
Line16: v
Line17: a
Line18: T
Line19: p
Line20: o
Line21: i
Line22: n
Line23: t
Line24:

Read Lines of the file


Python facilitates to read the file line by line by using a
function readline() method. The readline() method reads the lines of the
file from the beginning, i.e., if we use the readline() method two times,
then we can get the first two lines of the file.

Consider the following example which contains a function readline() that


reads the first line of our file "[Link]" containing three lines. Consider
the following example.

Here we give the example of reading the lines using the readline() function
in Python. The code is given below -

1. #open the [Link] in read mode. causes error if no such file exists.
2. fileptr = open("[Link]","r");
3. #stores all the data of the file into the variable content
4. content = [Link]()
5. content1 = [Link]()
6. #prints the content of the file
7. print(content)
8. print(content1)
9. #closes the opened file
[Link]()

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Python is the modern day language.

It makes things so simple.

We called the readline() function two times that's why it read two lines
from the [Link] means, if you called readline() function n times in your
program, then it read n number of lines from the file. This is the uses of
readline() function in Python. Python provides also
the readlines() method which is used for the reading lines. It returns the
list of the lines till the end of file(EOF) is reached.

Example 2:
Here we give the example of reading the lines using the readline() function
in Python. The code is given below -

1. #open the [Link] in read mode. causes error if no such file exists.

2. fileptr = open("[Link]","r");
3.
4. #stores all the data of the file into the variable content
5. content = [Link]()
6.
7. #prints the content of the file
8. print(content)
9.
10.#closes the opened file
11. [Link]()

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

['Python is the modern day language.\n', 'It makes things so simple.\n', 'Python has easy
syntax and user-friendly interaction.']

Example 3:

Here we give the example of reading the lines using the readline() function
in Python. The code is given below -

1. A = ["Hello\n", "Coders\n", "JavaTpoint\n"]


2. f1 = open('[Link]', 'w')
3. [Link](A)
4. [Link]()
5. f1 = open('[Link]', 'r')
6. Lines = [Link]()
7. count = 0
8. for line in Lines:
9. count += 1
10. print("Line{}: {}".format(count, [Link]()))

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Line1: Hello
Line2: Coders
Line3: JavaTpoint

Creating a new file


The new file can be created by using one of the following access modes
with the function open().The open() function used so many parameters.
The syntax of it is given below -

file = open(path_to_file, mode)

x, a and w is the modes of open() function. The uses of these modes are
given below -
x: it creates a new file with the specified name. It causes an error a file
exists with the same name.

a: It creates a new file with the specified name if no such file exists. It
appends the content to the file if the file already exists with the specified
name.

w: It creates a new file with the specified name if no such file exists. It
overwrites the existing file.

Consider the following example.

Program code1 for Creating a new file:

Here we give an example for creating a new file in Python. For creates a
file, we have to used the open() method. The code is given below -

1. #open the [Link] in read mode. causes error if no such file exists.

2. fileptr = open("[Link]","x")
3. print(fileptr)
4. if fileptr:
5. print("File created successfully")

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

<_io.TextIOWrapper name='[Link]' mode='x' encoding='cp1252'>


File created successfully

Program code2 for creating a new file:

Here we give an example for creating a new file in Python. For creates a
file, we have to use the open() method. Here we use try block for erase the
errors. The code is given below -

1. try:
2. with open('[Link]', 'w') as f:
3. [Link]('Here we create a new file')
4. except FileNotFoundError:
5. print("The file is does not exist")
6.
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The file is does not exist

File Pointer positions


Python provides the tell() method which is used to print the byte number
at which the file pointer currently exists. The tell() methods is return the
position of read or write pointer in this file. The syntax of tell() method is
given below -

1. [Link]()

Program code1 for File Pointer Position:

Here we give an example for how to find file pointer position in Python.
Here we use tell() method and it is return byte number. The code is given
below -

1. # open the file [Link] in read mode


2. fileptr = open("[Link]","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",[Link]())
6.
7. #reading the content of the file
8. content = [Link]();
9.
10.#after the read operation file pointer modifies. tell() returns the location o
f the fileptr.
11.
[Link]("After reading, the filepointer is at:",[Link]())

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The filepointer is at byte : 0


After reading, the filepointer is at: 117
Program code2 for File Pointer Position:

Here we give another example for how to find file pointer position in Python.
Here we also use tell() method, which is return byte number. The code is
given below -

1. file = open("[Link]", "r")


2. print("The pointer position is: ", [Link]())

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The pointer position is: 0

Modifying file pointer position


In real-world applications, sometimes we need to change the file pointer
location externally since we may need to read or write the content at
various locations.

For this purpose, the Python provides us the seek() method which enables
us to modify the file pointer position externally. That means, using seek()
method we can easily change the cursor in the file, from where we want to
read or write a file.

Syntax:

The syntax for seek() method is given below -

1. <file-ptr>.seek(offset[, from)

The seek() method accepts two parameters:

offset: It refers to the new position of the file pointer within the file.

from: It indicates the reference position from where the bytes are to be
moved. If it is set to 0, the beginning of the file is used as the reference
position. If it is set to 1, the current position of the file pointer is used as
the reference position. If it is set to 2, the end of the file pointer is used as
the reference position.

Consider the following example.


Here we give the example of how to modifying the pointer position using
seek() method in Python. The code is given below -

1. # open the file [Link] in read mode


2. fileptr = open("[Link]","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",[Link]())
6.
7. #changing the file pointer location to 10.
8. [Link](10);
9.
10.#tell() returns the location of the fileptr.
11. print("After reading, the filepointer is at:",[Link]())

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The filepointer is at byte : 0


After reading, the filepointer is at: 10

Python OS module:
Renaming the file
The Python os module enables interaction with the operating system. It
comes from the Python standard utility module. The os module provides a
portable way to use the operating system-dependent functionality in
Python. The os module provides the functions that are involved in file
processing operations like renaming, deleting, etc. It provides us the
rename() method to rename the specified file to a new name. Using the
rename() method, we can easily rename the existing File. This method has
not any return value. The syntax to use the rename() method is given
below.

Syntax:

The syntax of rename method in Python is given below -

1. rename(current-name, new-name)
The first argument is the current file name and the second argument is the
modified name. We can change the file name bypassing these two
arguments.

Program code 1 for rename() Method:

Here we give an example of the renaming of the files using rename()


method in Python. The current file name is [Link], and the new file name
is [Link]. The code is given below -

1. import os
2.
3. #rename [Link] to [Link]
4. [Link]("[Link]","[Link]")

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The above code renamed current [Link] to [Link]

Program code 2 for rename() Method:

Here we give an example of the renaming of the files using rename()


method in Python. The current file name is the source, and the new file
name is the destination. The code is given below -

1. import os
2. def main():
3. i=0
4. path="D:/JavaTpoint/"
5. for filename in [Link](path):
6. destination = "new" + str(i) + ".png"
7. source = path + filename
8. destination = path + destination
9. [Link](source, destination)
10. i += 1
11.
[Link] __name__ == '__main__':
13. main()
Removing the file
The os module provides the remove() method which is used to remove
the specified file.

Syntax:

The syntax of remove method is given below -

1. remove(file-name)

Program code 1 for remove() method:

1. import os;
2. #deleting the file named [Link]
3. [Link]("[Link]")

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The file named [Link] is deleted.

Program code 2 for remove() Method:

Here we give an example of removing a file using the remove() method in


Python. The file name is [Link], which the remove() method deletes. Print
the command "This file is not existed" if the File does not exist. The code is
given below -

1. import os
2. if [Link]("[Link] "):
3. [Link]("[Link] ")
4. else:
5. print("This file is not existed")

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

This file is not existed


Creating the new directory
The mkdir() method is used to create the directories in the current
working [Link] creates dictionary in numeric mode. If the file already
presents in the system, then it occurs error, which is known as
FileExistsError in Python. The mkdir() method does not return any kind of
value. The syntax to create the new directory is given below.

Syntax:

The syntax of mkdir() method in Python is given below -

1. [Link] (path, mode = 0o777, *, dir_fd = None)

Output:

Parameter:

The syntax of mkdir() method in Python is given below -

path - A path like object represent a path either bytes or the strings object.

mode - Mode is represented by integer value, which means mode is


created. If mode is not created then the default value will be 0o777. Its use
is optional in mkdir() method.

dir_fd - When the specified path is absolute, in that case dir_fd is ignored.
Its use is optional in mkdir() method.

Program code 1 for mkdir() Method:

Here we give the example of mkdir() method by which we can create new
dictionary in Python. The code is given below -

1. import os
2.
3. #creating a new directory with the name new
4. [Link]("new")

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Create a new dictionary which is named new


Program code 2 for mkdir() Method:

Here we give the example of mkdir() method by which we can create new
dictionary in Python. The code is given below -

1. import os
2. path = '/D:/Nettech'
3. try:
4. [Link](path)
5. except OSError as error:
6. print(error)

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

[Error 20] File exists: '/D:/Nettech'

The getcwd() method:


This method returns the current working directory which have absolute
value. The getcwd() method returns the string value which represents the
working dictionary in Python. In getcwd() method, do not require any
parameter.

The syntax to use the getcwd() method is given below.

Syntax

The syntax of getcwd() method in Python is given below -

1. [Link]()

Program code 1 for getcwd() Method:

Here we give the example of getcwd() method by which we can create new
dictionary in Python. The code is given below -

1. import os
2. [Link]()
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

'C:\\Users\\Tushar Gupta'

Program code 2 for getcwd() Method:

Here we give the example of getcwd() method by which we can create new
dictionary in Python. The code is given below -

1. import os
2. c = [Link]()
3. print("The working directory is:", c)

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The working directory is: C:\\Users\\Nettech

Changing the current working directory


The chdir() method is used to change the current working directory to a
specified [Link] chdir() method takes a single argument for the new
dictionary path. The chdir() method does not return any kind of value.

Syntax

The syntax of chdir() method is given below -

1. chdir("new-directory")

Program code 1 for chdir() Method:

Here we give the example of chdir() method by which we can change the
current working dictionary into new dictionary in Python. The code is given
below -

1. import os
2. # Changing current directory with the new directiory
3. [Link]("C:\\Users\\Tushar Gupta\\Documents")
4. #It will display the current working directory
5. [Link]()
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

'C:\\Users\\ Tushar Gupta \\Documents'

Program code 2 for chdir() Method:

Here we give another example of chdir() method by which we can change


the current working dictionary into new dictionary in Python. The code is
given below -

1. import os
2. [Link](r"C:\Users\Nettech")
3. print("Currently working directory is changed")

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

Currently working directory is changed

Deleting directory:
The rmdir() method is used to delete the specified directory. If the directory
is not empty then there is occurs OSError. The rmdir() method does not
have and kind of return value.

Syntax

1. [Link](directory name)

Program code 1 for rmdir() Method:

Here we give the example of rmdir() method by which we can delete a


dictionary in Python. The code is given below -

1. import os
2. #removing the new directory
3. [Link]("directory_name")

Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

It will remove the specified directory.

Program code 2 for rmdir() Method:

Here we give another example of rmdir() method by which we can delete a


dictionary in Python. The code is given below -

1. import os
2. directory = "Nettech"
3. parent = "/D:/User/Documents"
4. path = [Link](parent, directory)
5. [Link](path)
6. print("The directory '%s' is successfully removed", %directory)

Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

The directory 'Nettech' is successfully removed

Output:

Here we give the example of rmdir() method by which we can delete a


dictionary in Python. Here we use try block for handle the error. The code
is given below -

1. import os
2. dir = "Nettech"
3. parent = "/D:/User/Documents"
4. path = [Link](parent, dir)
5. try:
6. [Link](path)
7. print("The directory '%s' is successfully removed", %dir)
8. except OSError as error:
9. print(error)
10. print("The directory '%s' cannot be removed successfully", %dir)
Output:

Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -

[Error 30] Permission denied: '/D:/User/Documents/Nettech'


The directory 'Nettech’ cannot be removed successfully

Writing Python output to the files:


In Python, there are the requirements to write the output of a Python script
to a file.

The check_call() method of module subprocess is used to execute a


Python script and write the output of that script to a file.

The following example contains two python scripts. The script [Link]
executes the script [Link] and writes its output to the text file [Link].

Program code:

[Link]

1. temperatures=[10,-20,-289,100]
2. def c_to_f(c):
3. if c< -273.15:
4. return "That temperature doesn't make sense!"
5. else:
6. f=c*9/5+32
7. return f
8. for t in temperatures:
9. print(c_to_f(t))

[Link]

1. import subprocess
2.
3. with open("[Link]", "wb") as f:
4. subprocess.check_call(["python", "[Link]"], stdout=f)
File Related Methods:
The file object provides the following methods to manipulate the files on
various operating systems. Here we discuss the method and their uses in
Python.

SN Method Description

1 [Link]() It closes the opened file. The file once closed, it can't be read or write
anymore.

2 [Link]() It flushes the internal buffer.

3 [Link]() It returns the file descriptor used by the underlying implementation to


request I/O from the OS.

4 [Link]() It returns true if the file is connected to a TTY device, otherwise returns
false.

5 [Link]() It returns the next line from the file.

6 [Link]([size]) It reads the file for the specified size.

7 [Link]([size]) It reads one line from the file and places the file pointer to the beginning
of the new line.

8 [Link]([sizehint]) It returns a list containing all the lines of the file. It reads the file until
the EOF occurs using readline() function.

9 [Link](offset[,from) It modifies the position of the file pointer to a specified offset with the
specified reference.

10 [Link]() It returns the current position of the file pointer within the file.

11 [Link]([size]) It truncates the file to the optional specified size.

12 [Link](str) It writes the specified string to a file

13 [Link](seq) It writes a sequence of the strings to a file.

You might also like