Python Programming Language Overview
Python Programming Language Overview
What is Python?
Python is a popular programming language. It was created by
Guido van Rossum, and released in 1991.
It is used for:
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 --version
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:
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]
Hello, World!
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!")
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])
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!")
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
Example
if 5 > 2:
print("Five is greater than two!")
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
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.
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.
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
Example
print("Hello, World!") #This is a comment
Example
#print("Hello, World!")
print("Cheers, Mate!")
Multiline Comments
Python does not really have a syntax for multiline comments.
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!")
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:
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)
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:
Example
x = "Python is awesome"
print(x)
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
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".
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)
Example
x=5
y = "John"
print(x, y)
Python Data Types
Built-in Data Types
In programming, data type is an important concept.
Example
Print the data type of the variable x:
x=5
print(type(x))
Example Data
Type
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
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:
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = range(6) range
x = bool(5) bool
x = memoryview(bytes(5)) memoryview
Python Numbers
There are three numeric types in Python:
• int
• float
• complex
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
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))
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.
Example
print(10 + 5)
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:
+ 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:
= 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
:= print(x := 3) x=3
print(x)
Python Comparison Operators
Comparison operators are used to compare two values:
== Equal x == y
!= Not equal x != y
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:
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 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)
Operator Description
() Parentheses
** Exponentiation
* / // % Multiplication, division,
floor division, and modulus
^ Bitwise XOR
| Bitwise OR
And AND
Or OR
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.
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:
Strings
Strings in python are surrounded by either single quotation
marks, or double quotation marks.
Example
print("Hello")
print('Hello')
Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
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:
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.
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:
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:
Example
print only if "expensive" is NOT present:
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])
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:
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)
age = 36
print([Link](age))
F-Strings
F-String was introduced in Python 3.6, and is now the preferred
way of formatting strings.
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)
Example
Display the price with 2 decimals:
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Example
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
endswith() Returns true if the string ends with the specified value
index() Searches the string for a specified value and returns the
position of where it was found
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
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
rpartition() Returns a tuple where the string is parted into three parts
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice
versa
title() Converts the first character of each word to upper case
• 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
Example
If statement:
a = 33
b = 200
if b > a:
print("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")
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")
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:
Example
One line if else statement:
a=2
b = 330
print("A") if a > b else print("B")
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.")
Example
a = 33
b = 200
if b > a:
pass
Python Loops
Python has two primitive loop commands:
• while loops
• for loops
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:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Example
Exit the loop when x is "banana":
Example
Exit the loop when x is "banana", but this time the break comes
before the print:
Example
Do not print banana:
Example
Using the range() function:
for x in range(6):
print(x)
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):
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:
for x in adj:
for y in fruits:
print(x, y)
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
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
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
Output
[10, 12, 14, 16]
Output
Even numbers: [2, 4, 6, 8, 10]
Python Collections (Arrays)
There are four collection data types in the Python programming
language:
Python Lists
List
Lists are used to store multiple items in a single variable.
Example
Create a List:
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:
Example
Print the number of items in the list:
Example
String, int and boolean data types:
Example
A list with strings, integers and boolean values:
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?
Example
Using the list() constructor to make a List:
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:
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:
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).
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:])
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Example
Example
Change the second item:
Example
Change the values "banana" and "cherry" with the values
"blackcurrant" and "watermelon":
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:
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:
Insert Items
To insert a new list item, without replacing any of the existing
values, we can use the insert() method.
Example
Insert "watermelon" as the third item:
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:
Insert Items
To insert a list item at a specified index, use the insert() method.
Example
Insert an item as the second position:
Extend List
To append elements from another list to the current list, use
the extend() method.
Example
Add the elements of tropical to thislist:
Example
Add elements of a tuple to a list:
Example
Remove "banana":
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":
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:
Example
Remove the first item:
Example
Delete the entire list:
Example
Print all items in the list, one by one:
Learn more about for loops in our Python For Loops Chapter.
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].
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.
Example
Print all items, using a while loop to go through all the index
numbers
Example
A short hand for loop that will print all items in a list:
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.
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"]
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":
Example
With no if statement:
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:
Example
Accept only numbers lower than 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:
Example
Set all values in the new list to 'hello':
The expression can also contain conditions, not like a filter, but as
a way to manipulate the outcome:
Example
Return "orange" instead of "banana":
Example
Sort the list alphabetically:
Example
Sort the list numerically:
Sort Descending
To sort descending, use the keyword argument reverse = True:
Example
Sort the list descending:
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)
Example
Case sensitive sorting can give an unexpected result:
Example
Perform a case-insensitive sort of the list:
Reverse Order
What if you want to reverse the order of a list, regardless of the
alphabet?
Example
Reverse the order of the list items:
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:
Example
Make a copy of a list with the list() method:
Example
Join two list:
Another way to join two lists is by appending all the items from
list2 into list1, one by one:
Example
Append list2 into list1:
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:
[Link](list2)
print(list1)
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
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
Tuple
Tuples are used to store multiple items in a single variable.
Example
Create a Tuple:
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:
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
Example
One item tuple, remember the comma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Example
String, int and boolean data types:
Example
A tuple with strings, integers and boolean values:
<class 'tuple'>
Example
What is the data type of a tuple?
Example
Using the tuple() method to make a tuple:
Example
Print the second item in the tuple:
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:
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).
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:])
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])
Example
Check if "apple" is present in the tuple:
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:
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.
Example
Create a new tuple with the value "orange", and add that tuple:
print(thistuple)
Remove Items
Note: You cannot remove items in a tuple.
Example
The del keyword can delete the tuple completely:
Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is
called "packing" a tuple:
Example
Packing a tuple:
Example
Unpacking a tuple:
print(green)
print(yellow)
print(red)
Example
Assign the rest of the values as a list called "red":
print(green)
print(yellow)
print(red)
Example
Add a list of values the "tropic" variable:
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:
Example
Print all items by referring to their index number:
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:
Example
Join two tuples:
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:
print(mytuple)
Python - Tuple Methods
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
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.
* Note: Set items are unchangeable, but you can remove items
and add new items.
Example
Create a Set:
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.
Example
Duplicate values will be ignored:
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:
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:
print(thisset)
Example
Get the number of items in a set:
print(len(thisset))
Example
String, int and boolean data types:
Example
A set with strings, integers and boolean values:
<class 'set'>
Example
What is the data type of a set?
Example
Using the set() constructor to make a set:
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:
for x in thisset:
print(x)
Example
Check if "banana" is present in the set:
print("banana" in thisset)
Example
Check if "banana" is NOT present in the set:
Add Items
Once a set is created, you cannot change its items, but you can
add new items.
Example
Add an item to a set, using the add() method:
[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:
[Link](tropical)
print(thisset)
Example
Add elements of a list to at set:
[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:
[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:
[Link]("banana")
print(thisset)
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:
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:
[Link]()
print(thisset)
Example
The del keyword will delete the set completely:
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:
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 difference() method keeps the items from the first set that
are not in the other set(s).
Union
The union() method returns a new set with all items from both
sets.
Example
Join set1 and set2 into a new set:
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}
Example
Join multiple sets with the union() method:
Example
Use | to join two sets:
Example
Join a set with a tuple:
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:
[Link](set2)
print(set1)
Note: Both union() and update() will exclude any duplicate items.
Intersection
Keep ONLY the duplicates
Example
Join set1 and set2, but keep only the duplicates:
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:
Note: The & operator only allows you to join sets with sets, and
not with other data types like you can with
the intersection() method.
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:
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:
set3 = [Link](set2)
print(set3)
Example
Use - to join two sets:
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.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:
set3 = set1.symmetric_difference(set2)
print(set3)
Example
Use ^ to join two sets:
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.
Example
Use the symmetric_difference_update() method to keep the
items that are not present in both sets:
Dictionary
Dictionaries are used to store data values in key:value pairs.
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.
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.
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))
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))
Example
Using the dict() method to make a dictionary:
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]()
car["color"] = "white"
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]()
car["year"] = 2020
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]()
car["color"] = "red"
Example
Get a list of the key:value pairs
x = [Link]()
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]()
car["year"] = 2020
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]()
car["color"] = "red"
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.
Example
Update the "year" of the car by using the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})
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.
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
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)
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
}
}
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
}
Example
Print the name of child 2:
print(myfamily["child2"]["name"])
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
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:
thisdict = [Link](x, y)
print(thisdict)
Parameter Values
Parameter Description
value Optional. The value for all keys. Default value is None
More Examples
Example
Same example as above, but without specifying the value:
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
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
2 Canvas The canvas widget is used to draw the canvas 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.
8 Menubutton The Menubutton is used to display the menu items to the user.
13 Scrollbar It provides the scrollbar to the user so that the user can scroll
the window up and down.
However, the controls are less and widgets are generally added in
the less organized manner.
syntax
1. [Link](options)
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:
• 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:
Syntax
1. [Link](options)
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.
5 Command It is set to the function call which is scheduled when the function is called.
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.
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.
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.
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.
Syntax
1. W = Button(parent, options)
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
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.
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
11 xscrollcommand If the canvas is scrollable, this attribute should be the .set() method of the ho
13 yscrollcommand If the canvas is scrollable, this attribute should be the .set() method of the ve
Syntax
1. w = canvas(parent, options)
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:
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.
Syntax
1. w = checkbutton(master, options)
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.
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.
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.
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.
19 relief The type of the border of the checkbutton. By default, it is set to FLAT.
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.
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
2 flash() The checkbutton is flashed between the active and normal colors.
3 invoke() This will invoke the method associated with the checkbutton.
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.
Syntax
1. w = Entry (parent, options)
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.
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.
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.
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.
18 selectborderwidth The width of the border to display around 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.
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.
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.
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.
11 select_to(index) It selects all the characters from the beginning to the specified index.
Output:
Syntax
1. w = Frame(parent, options)
A list of possible options is given below.
SN Option Description
3 cursor The mouse pointer is changed to the cursor type set to different values like
an arrow, dot, etc.
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.
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")
Output:
There are the various options which can be specified to configure the text
or the part of the text shown in the Label.
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.
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.
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.
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.
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.
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:
The user can choose one or more items from the list depending upon the
configuration.
1. w = Listbox(parent, options)
A list of possible options is given below.
SN Option Description
3 cursor The mouse pointer will look like the cursor type like dot, arrow, etc.
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.
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.
SN Method Description
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.
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:
Output:
Syntax
1. w = Menubutton(Top, options)
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.
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.
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.
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.
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:
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.
Syntax
1. w = Menu(top, options)
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.
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.
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.
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
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.
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:
The message text contains more than one line. However, the message can
only be shown in the single font.
Syntax
1. w = Message(parent, options)
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.
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.
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).
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.
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.
5 bitmap It is used to display the graphics on the widget. It can be set to any
graphical or image object.
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.
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.
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.
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.
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
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.
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:
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.
Syntax
1. w = Scale(top, options)
1 activebackground The background color of the widget when it has the focus.
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.
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.
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.
Methods
SN Method Description
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.
Syntax
1. w = Scrollbar(top, options)
1 activebackground The background color of the widget when it has the focus.
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.
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.
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.
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.
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.
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
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.
8 highlightbackground The highlightcolor when the widget doesn't has the focus.
10 highlighcolor The color of the focus highlight when the widget has the focus.
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.
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.
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)
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.
SN Method Description
3 mark_names() It is used to get all the marks present in the Text widget.
SN Method Description
1 tag_add(tagname, startindex, This method is used to tag the string present in the
endindex) specified range.
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 windows have the title bars, borders, and other window
decorations.
Syntax
1. w = Toplevel(options)
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.
SN Method Description
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.
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.
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)
1 activebackground The background color of the widget when it has the focus.
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.
10 format This option is used for the format string. It has no default value.
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.
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.
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.
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.
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.
Syntax
1. w= PanedWindow(master, options)
SN Option Description
SN Method Description
2 get(startindex, endindex) This method is used to get the text present at the specified range.
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.
Syntax
1. w = LabelFrame(top, options)
SN Option Description
2 bd It represents the size of the border shown around the indicator. The default
is 2 pixels.
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.
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.
11. [Link]()
12.
13. labelframe2 = LabelFrame(top, text = "Negative Comments")
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.
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.
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.
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 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.
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
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
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.
Syntax
1. [Link]()
Consider the following example.
Here we write the program code for the closing method in Python. The code
is given below -
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.
1. try:
2. fileptr = open("[Link]")
3. # perform file operations
4. finally:
5. [Link]()
Syntax:
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)
Here we write the program code for with statement in Python. The code is
given below -
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.
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
Here we write the program code for write method in Python. The code is
given below -
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
Here we write the program code for write method in Python. The code is
given below -
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -
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].
Syntax:
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
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 -
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 -
Here we give an example of read file using for loop. The code is given below
-
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:
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 -
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 -
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
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.
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 -
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 -
1. [Link]()
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 -
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -
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 -
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -
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:
1. <file-ptr>.seek(offset[, from)
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.
Output:
Now we compile the above code in Python, and after successful compilation,
we run it. Then the output is given below -
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:
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.
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 -
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:
1. remove(file-name)
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 -
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 -
Syntax:
Output:
Parameter:
path - A path like object represent a path either bytes or the strings object.
dir_fd - When the specified path is absolute, in that case dir_fd is ignored.
Its use is optional in 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 -
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 -
Syntax
1. [Link]()
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'
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 -
Syntax
1. chdir("new-directory")
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 -
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 -
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)
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 -
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 -
Output:
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 -
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.
4 [Link]() It returns true if the file is connected to a TTY device, otherwise returns
false.
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.