Variable Declaration Python
Variable Declaration Python
Introduction to Python
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.
Python Syntax compared to other programming languages
Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets
for this purpose.
Chapter-2
Variable Declaration
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
Example:1
x = 5
y = "John"
print(type(x))
print(type(y))
Example:2
x = "John"
print(x)
x = 'John'
print(x)
Example: 3
a=4
A = "Sally"
Print (a)
Print (A)
Example: 4
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
print(myvar)
print(my_var)
print(_my_var)
print(myVar)
print(MYVAR)
print(myvar2)
Example:5
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Example :6
x = str(3)
y = int(3)
z = float(3)
print(x)
print(y)
print(z)
String
Strings in python are surrounded by either single quotation marks, or double quotation marks.
Example:1
print("Hello")
print('Hello')
Example:2
a = "Hello"
print(a)
Python List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Example:1
thislist = ["apple", "banana", "cherry"]
print(thislist)
Python Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set,
and Dictionary, all with different qualities and usage.
Example:1
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Example:2
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Python Set
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple,
and Dictionary, all with different qualities and usage.
Example:1
thisset = {"apple", "banana", "cherry"}
print(thisset)
Python Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and does not allow duplicates.
Example:1
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(thisdict)
In the example below, we use the + operator to add together two values:
Example
print(10 + 5)
Types
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
1.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
Example:1
x=5
y=3
print(x + y)
2.comparsion operators
== Equal x == y
!= Not equal x != y
equal to
to
Example:1
x=5
y=3
print(x == y)
3.Logical Operators
true 10
statements is true
Example:1
x=5
4.Bitwis Operators
Example:1
X=5
Y=12
Z=x*y
Print(z)
5.Assignment Operator
= 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
Example:1
x=5
x -= 3
print(x)
6.Identity Operator
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:
(is)
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
print(x is y)
print(x == y)
Example:2
(is not)
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z)
7.Membership operators
object
Example
x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list
Example 2
x = ["apple", "banana"]
print("pineapple" not in x)
# returns True because a sequence with the value "pineapple" is not in the list
Chapter 4
Condition Execution
If Statement
Example:1
a = 33
b = 200
if b > a:
Example:1
a = 200
b = 33
if b > a:
else:
If Elif Statement
The elif keyword is pythons way of saying "if the previous conditions were not true, then
try this condition".
Example:1
a = 33
b = 33
if b > a:
elif a == b:
Nested if Statement
You can have if statements inside if statements, this is called nested if statements.
Example:1
a = 200
b = 33
if b > a:
elif a == b:
print("a and b are equal")
else:
Iteration
For loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string).
Example:1
for x in fruits:
print(x)
Range () Function
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and stops before a specified number.
Example:1
x = range(6)
for n in x:
print(n)
for x in range(6):
print(x)
else:
print("Finally finished!")
While loop
With the while loop we can execute a set of statements as long as a condition is true.
Example:1
i = 1
while i < 6:
print(i)
i += 1
i = 1
while i < 6:
print(i)
i += 1
else:
Break statement
With the break statement we can stop the loop even if the while condition is true:
Example:1
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example:1
for i in range(9):
if i == 3:
continue
print(i)
CHAPTER 5
PYTHON FUNCTION
Function is a group of related statements.
Creating a Function
Calling a Function
def my_function():
my_function()
Arguments
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Number of Arguments
my_function("Emil", "Refsnes")
Return Statement
print(my_function(3))
print(my_function(5))
print(my_function(9))
Keyword Arguments,
You can also send arguments with the key = value syntax.
Example:
Example:
def my_function(*kids):
print("The youngest child is " + kids[2])
Local Scope:
A variable created inside a function belongs to the local scope of that function, and
can only be used inside that function.
Example:
def myfunc():
x = 300
print(x)
myfunc()
Global Scope:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Python Lambda
A lambda function can take any number of arguments, but can only have one
expression.
Example:1
x = lambda a: a + 10
print(x(5))
Example 2:
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
Example:
o/p
362880
720
479001600
CHAPTER-6
PYTHON MODULES
MODULES:
Creating modules:
To create a module just save the code you want in a file with the file extension .py:
EXAMPLE:
def greeting(name):
Use a Module
Now we can use the module we just created, by using the import statement.
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Variables in Module
The module can contain functions, as already described, but also variables of all types
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
import mymodule
a = mymodule.person1["age"]
print(a)
There is a built-in function to list all the function names (or variable names) in a module.
The dir() function:
EXAMPLE:
import platform
x = dir(platform)
print(x)
You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
Example
print (person1["age"])
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
EXAMPLE:
print(x)
print(y)
print(z)
print(type(x))
print(type(y))
print(type(z))
Python Math
Python has a set of built-in math functions, including an extensive math module, that allows
you to perform mathematical tasks on numbers.
The min() and max() functions can be used to find the lowest or highest value in an iterable:
EXAMPLE:
print(x)
print(y)
CHAPTER-7
SEQUENCES
List
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Example
thislist = ["apple", "banana", "cherry"]
print(thislist)
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
print(thislist)
List Length
To determine how many items a list has, use the len() function:
type()
From Python's perspective, lists are defined as objects with the data type 'list':
print(type(mylist))
Access Items
List items are indexed and you can access them by referring to the index number:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Negative Indexing
-1 refers to the last item, -2 refers to the second last item etc.
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.
Python Arrays
Example:
x = cars[0]
print(x)
Use the len() method to return the length of an array (the number of elements in an array).
cars = ["Ford", "Volvo", "BMW"]
x = len(cars)
print(x)
You can use the for in loop to loop through all the elements of an array.
cars = ["Ford", "Volvo", "BMW"]
for x in cars:
print(x)
cars.append("Honda")
print(cars)
You can use the pop() method to remove an element from the array.
print(cars)
CHAPTER-7
PYTHON STRINGS,SETS & DICTIONARY
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
print("Hello")
print('Hello')
Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:
a = "Hello"
print(a)
Multiline Strings
print(a)
String Length
a = "Hello, World!"
print(len(a))
Capitalize:
x = txt.capitalize()
print (x)
upper:
txt = "THIS IS NOW!"
x = txt.isupper()
print(x)
join
string.join(iterable) ->syntax
x = "#".join(myTuple)
print(x)
String format()
price = 49
print(txt.format(price))
Python Sets
print(thisset)
print(thisset)
To determine how many items a set has, use the len() method
print(len(thisset))
thisset.remove("banana")
print(thisset)
Python Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
CHAPTER-8
PYTHON FILE I/O
Python has several functions for creating, reading, updating, and deleting files.
File Handling
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
"t" - Text - Default value. Text mode
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
demofile.txt
The open() function returns a file object, which has a read() method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
Example 1
If the file is located in a different location, you will have to specify the file path, like this:
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
By default the read() method returns the whole text, but you can also specify how many characters you
want to return:
Example
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
Example
f = open("demofile.txt", "r")
print(f.readline())
Example 1
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Python Directory
If there are a large number of files to handle in our Python program, we can arrange our code
within different directories to make things more manageable.
We can get the present working directory using the getcwd() method of the os module.
This method returns the current working directory in the form of a string. We can also use
the getcwdb() method to get it as bytes object.
>>> import os
>>> os.getcwd()
'C:\\Program Files\\PyScripter'
>>> os.getcwdb()
b'C:\\Program Files\\PyScripter'
Changing Directory
We can change the current working directory by using the chdir() method.
>>> os.chdir('C:\\Python33')
>>> print(os.getcwd())
C:\Python33
All files and sub-directories inside a directory can be retrieved using the listdir() method.
>>> print(os.getcwd())
C:\Python33
>>> os.listdir()
['DLLs',
'Doc',
'include',
'Lib',
'libs',
'LICENSE.txt',
'NEWS.txt',
'python.exe',
'pythonw.exe',
'README.txt',
'Scripts',
'tcl',
'Tools']
>>> os.listdir('G:\\')
['$RECYCLE.BIN',
'Movies',
'Music',
'Photos',
'Series',
'System Volume Information']
>>> os.mkdir('test')
>>> os.listdir()
['test']
>>> os.listdir()
['test']
>>> os.rename('test','new_one')
>>> os.listdir()
['new_one']
>>> os.listdir()
['new_one', 'old.txt']
>>> os.remove('old.txt')
>>> os.listdir()
['new_one']
>>> os.rmdir('new_one')
>>> os.listdir()
[]
CHAPTER-9
PYTHON ERRORS AND BULIT-IN EXCEPTION
The try block lets you test a block of code for errors.
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate an
error message.
Example
try:
print(x)
except:
print("An exception occurred")
KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+C or Delete).
MemoryError Raised when an operation runs out of memory.
RuntimeError Raised when an error does not fall under any other category.
UnicodeTranslateErro
r Raised when a Unicode-related error occurs during translating.
Raised when a function gets an argument of correct type but imprope
ValueError
value.
AssertionError
x = 1
y = 0
AttributeError
X = 10
# Raises an AttributeError
X.append(6)
EOFError
n = int(input())
print(n * 10)
FloatingPointError
a = Decimal('1.1')
b = 2.2
c = a + b
key error:
>>> prices = { 'Pen' : 10, 'Pencil' : 5, 'Notebook' : 25}
>>> prices['Eraser']
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
prices['Eraser']
KeyError: 'Eraser'
IndentationError:
>>> print("hai")
CHAPTER-10
PYTHON NAMESPACE AND SCOPE
Namespace is a collection of names.( identifier)
A namespace containing all the built-in names is created when we start the Python interpreter
and exists as long as the interpreter runs.a namespace as a mapping of every name,you have
defined to corresponding objects.
2.global namespace->(a=10)
This is the reason that built-in functions like id() , print() id()->(we can get the address (in RAM)
a = 2
print('id(2) =', id(2))
Output
id(2) = 9302208
id(a) = 9302208
def outer_function():
b = 20
def inner_func():
c = 30
a = 10
Here, the variable a is in the global namespace. Variable b is in the local namespace
of outer_function() and c is in the nested local namespace of inner_function() .
Chapter 11
Create a Class
class MyClass:
x=5
print(MyClass)
o/p
<class '__main__.MyClass'>
Create Object
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
o/p
5
The examples above are classes and objects in their simplest form, and are not really useful in
real life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being
initiated.
Use the __init__() function to assign values to object properties, or other operations that are
necessary to do when the object is being created:
Example:1
class Person:
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
o/p:
john
36
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the object.
Example
Example:1
class Person:
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
o/p
The self parameter is a reference to the current instance of the class, and is used to access variables
that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first parameter
of any function in the class:
Example:
class Person:
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
p1 = Person("John", 36)
p1.myfunc()
output:
Hello my name is John
Example
class Person:
self.name = name
self.age = age
def myfunc(self):
p1 = Person("John", 36)
p1.age = 40
print(p1.age)
output:
40
Example
Delete the age property from the p1 object:
class Person:
self.name = name
self.age = age
def myfunc(self):
p1 = Person("John", 36)
del p1.age
print(p1.age)
output:
Attribute Error
Delete Objects
Example
class Person:
self.name = name
self.age = age
def myfunc(self):
p1 = Person("John", 36)
del p1
print(p1)
output
class definitions cannot be empty, but if you for some reason have a class definition with no
content, put in the pass statement to avoid getting an error.
Example:
for x in [0, 1, 2]
pass
Chapter 12
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from another
class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.
Any class can be a parent class, so the syntax is the same as creating any other class:
Example
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
Create a Child Class
To create a class that inherits the functionality from another class, send the parent class as a
parameter when creating the child class:
Example:1
class Person:
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
pass
x = Student("Mike", "Olsen")
x.printname()
So far we have created a child class that inherits the properties and methods from its parent.
We want to add the __init__() function to the child class (instead of the pass keyword).
Note: The __init__() function is called automatically every time the class is being used to
create a new object.
Example
class Person:
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname):
x = Student("Mike", "Olsen")
x.printname()
Python also has a super() function that will make the child class inherit all the methods and
properties from its parent:
class Person:
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
super().__init__(fname, lname)
x = Student("Mike", "Olsen")
x.printname()
By using the super() function, you do not have to use the name of the parent element, it will
automatically inherit the methods and properties from its parent.
Add properties
class Person:
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
super().__init__(fname, lname)
self.graduationyear = 2019
x = Student("Mike", "Olsen")
print(x.graduationyear)
o/p
2019
Add Methods
Example:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
x.welcome()
o/p
Chapter 13
Network programming
Python plays an essential role in network programming. The standard library of
Python has full support for network protocols, encoding, and decoding of data and other networking
concepts, and it is simpler to write network programs in Python than that of C++
socket
A socket is the end-point in a flow of communication between two programs or communication
channels operating over a network. They are created using a set of programming requests called
socket API (Application Programming Interface). Python's socket library offers classes for handling
common transports as a generic interface.
Sockets use protocols for determining the connection type for port-to-port communication between
client and server machines. The protocols are used for:
Each device connected to the Internet has a unique IP address which other machines use to find the device.
DNS servers eliminate the need for humans to memorize IP addresses such as 192.168.1.1 (in IPv4), or more
complex newer alphanumeric IP addresses such as 2400:cb00:2048:1::c629:d7a2 (in IPv6).
IP addressing
An IP address is a string of numbers separated by periods. IP addresses are expressed as a set of four
numbers — an example address might be 192.158.1.38. Each number in the set can range from 0 to 255.
So, the full IP addressing range goes from 0.0.0.0 to 255.255.255.255.
E-mail->smtp
FTP (File Transfer Protocol) etc...
The File Transfer Protocol (FTP) is a standard communication protocol used for the transfer of computer
files from a server to a client on a computer network
Socket Program
listen(): is used to establish and start TCP listener.
bind(): is used to bind-address (host-name, port number) to the socket.
accept(): is used to TCP client connection until the connection arrives.
connect(): is used to initiate TCP server connection.
send(): is used to send TCP messages.
recv(): is used to receive TCP messages.
sendto(): is used to send UDP messages
close(): is used to close a socket.
A Simple Network Program Using Python
Example
#server
import socket
s = socket.socket()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
conn,addr = s.accept()
conn.close()
#client
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.connect((host,port))
print(s.recv(1024))
s.close()
Save the filename client.py
Receive the message from server side Thank you for connection
Chapter 14
Multithreaded Programming
Threads
It is the execution of a tiny sequence of program instruction that can be managed
independently and is a distinctive part of the operating system. Modern OS manages multiple
programs using a time-sharing technique. In Python, there are two different kinds of thread. These
are:
Kernel Threads
User-space threads or User threads
Benefits of Thread
For a single process, multiple threads can be used to process and share the same data-space and
can communicate with each other by sharing information.
They use lesser memory overhead, and hence they are called lightweight processes.
A program can remain responsive to input when threads are used.
Threads can share and process the global variable's memory.
New Thread
It is achievable to execute functions in a separate thread using a module Thread. For doing
this, programmers can use the function - thread.start_new_thread().
Syntax:
def factorial(n):
global threadId
rc = 0
threadId += 1
rc = 1
else:
rc = returnNumber
return rc
start_new_thread(factorial, (5, ))
#start_new_thread(factorial, (4, ))
sleep(waiting)
The threading module, as described earlier, has a Thread class that is used for implementing
threads, and that class also contains some predefined methods used by programmers in multi-
threaded programming. These are:
CHAPTER 15
import mysql.connector
create table kalai(name varchar(25),age int,dept varchar(12),city varchar(5),pincode int)
select * from kalai
insert into kalai values('aaa',25,'ct','mkm',603306)
select * from kalai
insert into kalai values('bbb',24,'ct','ch',603758)
insert into kalai values('ccc',25,'ct','mkm',603306)
insert into kalai values('ddd',28,'ct','gh',603306)
insert into kalai values('eee',29,'it','mve',603306)
select * from kalai
alter table kalai add mark int
select * from kalai
update kalai SET mark=60 WHERE name='aaa';
select * from kalai
Create Connection
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword"
)
print(mydb)
DATABASE CONNECTION
import mysql.connector
Creating table
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
password="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor = mydb.cursor()
mycursor.execute(sql, val)
mydb.commit()
CHAPTER 16
GUI PROGRAMMING
Most of the programs we have done till now are text-based programming. But many applications need
GUI (Graphical User Interface).
Python provides various options for developing graphical user interfaces (GUIs). Most important are
listed below.
Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would
look this option in this chapter.
wxPython − This is an open-source Python interface for wxWindows.
JPython − JPython is a Python port for Java which gives Python scripts seamless access to
Java class libraries on the local machine
TKINTER PROGRAMMING:
Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface
to the Tk GUI toolkit.
Example
import tkinter as tk
root = tk.Tk()
root.title("First Tkinter Window")
root.mainloop()
LABLE WIDGET
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
LABELFRAME WIDGET
The LabelFrame widget is used to draw a border around its child widgets.
top = Tk()
top.geometry("300x200")
top.mainloop()
ENTRY WIDGET
Python offers multiple options for developing a GUI (Graphical User Interface).
Out of all the GUI methods, Tkinter is the most commonly used method
Syntax
entry = tk.Entry(parent, options)
1) Parent: The Parent window or frame in which the widget to display.
2) Options: The various options provided by the entry widget are:
Example
import tkinter as tk
root = tk.Tk()
root.title("First Tkinter Window")
root.mainloop()
BUTTON WIDGET
Tkinter is Python’s standard GUI (Graphical User Interface) package. It is one of the
most commonly used packages for GUI applications which comes with Python itself. Let’s
see how to create a button using Tkinter.
import tkinter as tk
def write_slogan():
print("Tkinter is easy to use!")
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Hello",
command=write_slogan)
slogan.pack(side=tk.LEFT)
root.mainloop()
checkbutton widget
The Tkinter Checkbutton widget can contain text, but only in a single font, or images, and a
button can be associated with a Python function or method.
Example
LISTBOX WIDGET
The ListBox widget is used to display different types of items. These items must be of
the same type of font and having the same font color.
MENU WIDGET
Menus are the important part of any GUI. A common use of menus is to
provide convenient access to various operations such as saving or opening a file, quitting a
program, or manipulating data.
# Creating Menubar
menubar = Menu(root)
# display Menu
root.config(menu = menubar)
mainloop()
MESSAGE WIDGET
The Message widget is used to show the message to the user regarding the
behavior of the python application
root = Tk()
root.geometry("300x200")
msg = Message( root, text = "A computer science portal for geeks")
msg.pack()
root.mainloop()
CHAPTER-17
IMAGE PROCESSING IN PYTHON WITH PILLOW
BASIC INSTALLATION:
Step 3: cd scripts
OpenCV − Image processing library mainly focused on real-time computer vision with
application in wide-range of areas like 2D and 3D feature toolkits, facial & gesture
recognition, Human-computer interaction, Mobile robotics, Object identification and
others.
Python Imaging Library (PIL) − To perform basic operations on images like create
thumnails, resize, rotation, convert between different file formats etc.
Image: Open() and show()
#Open Image
im = Image.open("TajMahal.jpg")
im.rotate(45).show()
output
>>> im
>>> im.size
(1000, 667)
>>> im.format
'JPEG'
>>>
We can change the format of image from one form to another, like below
>>> im.save('TajMahal.png')
Resize-thumbnails()