Introduction To Python Part 2
Introduction To Python Part 2
Functions
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also
create your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ).
Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of
the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.
User defined Function with parameters All parameters (arguments) in the Python language are
passed by reference. It means if you change what a parameter refers to within a function, the change
also reflects back in the calling function.
All parameters (arguments) in the Python language are passed by reference. It means if you change
what a parameter refers to within a function, the change also reflects back in the calling function.
Function Arguments
You can call a function by using the following types of formal arguments −
Required arguments
Example
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
Example
Output
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument.
Example
Output
V
a
r
i
Variable-length arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments. An asterisk (*) is placed before the
variable name that holds the values of all non-key word variable arguments. This tuple remains
empty if no additional arguments are specified during the function call.
Output
You’ll see that you’ll get a NameError that says that the name 'total' is not defined when you try to
print out the local variable total that was defined inside the function body. The init variable, on the
other hand, can be printed out without any problems.
OUTPUT
Note:
An anonymous function cannot be a direct call to print because lambda requires an expression
Lambda functions have their own local namespace and cannot access variables other than those in
their parameter list and those in the global namespace.
OUTPUT
Output
OUTPUT
from...import * Statement
It is also possible to import all names from a module into the current namespace by using the
following import statement
Accessing Attributes:
You access the object's attributes using the dot operator with object. Class variable would be
accessed using class name
Note: You can add, remove, or modify attributes of classes and objects at any time
Instead of using the normal statements to access attributes, you can use the following functions −
The getattr(obj, name[, default]) − to access the attribute of object.
The hasattr(obj,name) − to check if an attribute exists or not.
The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it would
be created.
The delattr(obj, name) − to delete an attribute.
GUI Programming
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 http://wxpython.org.
JPython − JPython is a Python port for Java which gives Python scripts seamless access to Java
class libraries on the local machine http://www.jython.org.
Tkinter
Creating a GUI using tkinter is an easy task.
To create a tkinter:
1. Importing the module – tkinter
2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.
There are two main methods used you the user need to remember while creating the Python
application with GUI.
To create a main window, tkinter offers a method Tk(..). To change the name of the window,
you can change the className to the desired one. The basic code used to create the main window
of the application is:
mainloop(): There is a method known by the name mainloop() is used when you are ready
for the application to run. mainloop() is an infinite loop used to run the application, wait for
an event to occur and process the event till the window is not closed.
Syntax: m.mainloop()
tkinter also offers access to the geometric configuration of the widgets which can organize the
widgets in the parent windows. There are mainly three geometry manager classes class.
1. pack() method:It organizes the widgets in blocks before placing in the parent widget.
2. grid() method:It organizes the widgets in grid (table-like structure) before placing in the
parent widget.
3. place() method:It organizes the widgets by placing them on specific positions directed by
the programmer.
Widgets
There are a number of widgets which you can put in your tkinter application. Some of the major
widgets are explained below:
Operator & Description
w = CheckButton(master, option=value)
There are number of options which are used to change the format of this widget. Number of options
can be passed as parameters separated by commas. Some of them are listed below.
Title: To set the title of the widget.
activebackground: to set the background color when widget is under the cursor.
activeforeground: to set the foreground color when widget is under the cursor.
bg: to set the normal background
command: to call a function.
font: to set the font on the button label.
image: to set the image on the widget
Output
options − Here is the list of most commonly used options for this widget. These options can
be used as key-value pairs separated by commas.
command
A procedure to be called every time the slider is moved. This procedure will be passed one argument,
the new scale value. If the slider is moved rapidly, you may not get a callback for every possible
position, but you'll certainly get a callback when it settles.
cursor
If you set this option to a cursor name (arrow, dot etc.), the mouse cursor will change to that pattern
when it is over the scale.
digits
The way your program reads the current value shown in a scale widget is through a control variable.
The control variable for a scale can be an IntVar, a DoubleVar (float), or a StringVar. If it is a string
variable, the digits option controls how many digits to use when the numeric scale value is converted
to a string.
from_
A float or integer value that defines one end of the scale's range.
highlightbackground
The color of the focus highlight when the scale does not have focus.
highlightcolor
The color of the focus highlight when the scale has the focus.
label
You can display a label within the scale widget by setting this option to the label's text. The label
appears in the top left corner if the scale is horizontal, or the top right corner if vertical. The default
is no label.
length
The length of the scale widget. This is the x dimension if the scale is horizontal, or the y dimension
if vertical. The default is 100 pixels.
relief
Specifies the appearance of a decorative border around the label. The default is FLAT; for other
values.
repeatdelay
This option controls how long button 1 has to be held down in the trough before the slider starts
moving in that direction repeatedly. Default is repeatdelay=300, and the units are milliseconds.
resolution
Normally, the user will only be able to change the scale in whole units. Set this option to some other
value to change the smallest increment of the scale's value. For example, if from_=-1.0 and to=1.0,
and you set resolution=0.5, the scale will have 5 possible values: -1.0, -0.5, 0.0, +0.5, and +1.0.
showvalue
Normally, the current value of the scale is displayed in text form by the slider (above it for horizontal
scales, to the left for vertical scales). Set this option to 0 to suppress that label.
sliderlength
Normally the slider is 30 pixels along the length of the scale. You can change that length by setting
Output
Coding Style
Now that you are about to write longer, more complex pieces of Python, it is a good time to talk
about coding style.
Every Python developer should adopt a coding style as mentioned below:
Use 4-space indentation, and no tabs.
4 spaces are a good compromise between small indentation (allows greater nesting depth)
and large indentation (easier to read). Tabs introduce confusion, and are best left out.
Wrap lines so that they don’t exceed 79 characters.
This helps users with small displays and makes it possible to have several code files side-by-
side on larger displays.
Use blank lines to separate functions and classes, and larger blocks of code inside
functions.
When possible, put comments on a line of their own.
Use docstrings.
Use spaces around operators and after commas, but not directly inside bracketing
constructs: a= f(1, 2) + g(3, 4).
Name your classes and functions consistently; the convention is to use CamelCase for
classes and lower_case_with_underscores for functions and methods. Always use self as the
name for the first method argument (see A First Look at Classes for more on classes and
methods).
Don’t use fancy encodings if your code is meant to be used in international environments.
Python’s default, UTF-8, or even plain ASCII work best in any case.
Likewise, don’t use non-ASCII characters in identifiers if there is only the slightest chance
people speaking a different language will read or maintain the code.