SlideShare a Scribd company logo
Welcome to Python workshop
By – Mukul Kirti Verma
Python
General-purpose
Interpreted,
Interactive,
Object-oriented,
High-level programming language.
Why to Learn Python?
Python is a MUST for students and working professionals to become a great Software Engineer specially when they are
working in Web Development Domain. I will list down some of the key advantages of learning Python:
Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program
before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your
programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates
code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the
development of a wide range of applications from simple text processing to WWW browsers to games.
Major project developed in python
Area where python is used
 Web development
 Software development
 Machine Learning,
 IOT
 Data analysis
 App Development
 Game Development
History
Python is developed by Guido van Rossum in 1989 at the National Research Institute for Mathematics and
Computer Science in the Netherlands it was the successor to ABC and capable of exception handling and
interfacing with the Amoeba operating system
Python is derived from:
Modula-3,
C,
C++
Unix shell
Other scripting languages.
Python is available under the GNU General Public License (GPL).
The GNU General Public License is a free, copyleft license for software and other kinds of works.
Features
1. Easy-to-learn and understand
2.. A broad standard library
3.Open Source
4. Interactive Mode
5. Portable (Platform in dependent)
6. Extendable
7. Databases
8. GUI Programming
9. Object Oriented Programming.
10. It can be used as a scripting language
Features
9. Object Oriented Programming.
10. It can be used as a scripting language
11. It provides very high-level dynamic data types and supports dynamic type checking.
12.It supports automatic garbage collector.
13. Less line of code
Python uses two strategies for memory Management:
Reference counting:
Garbage collection:
Python is available
Unix, Linux
Win 9x/NT/2000
Macintosh (Intel, PPC, 68K)
OS/2
DOS (multiple versions)
Palm OS
Nokia mobile phones(Symbian)
Python Installation
1. Go to www.python.org
2. Go to Download menu
3. Click on windows menu
4. Download Python (what ever version you want.
5. Double click on downloaded Python.exe file and install it
Set environment variable
 Right click on My computer
 Click on Properties
 Then click on advance system setting In left hand side of the windows screen.
 Then click on Set Environment variables
 Now click on first New button and Add following
Set environment variable
1. Select “path” variable in system variables
2. Click on edit button
3. Add following path in the path variable
C:Users[Your_Current_User_Name]AppDataLocalProgramsPythonPython36;
4. Then click on ok Button.
5. Now open command prompt and type python
If python shall is running then environment variable is set properly.
Python Basic syntax
 Python Identifiers
 Reserved Words
 Comments in Python
 Input output In Python
 Variable Types
 Delete variable in python
1. Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with:
 Python does not allow A letter A to Z or a to z
 An underscore (_) followed by zero more letters,
 Underscores and digits (0 to 9).
 @, $, and % within identifiers.
 Python is a case sensitive programming language.
 White specs not in b/w the catheters
 E.g. My Name=“mukul”
Reserved Words
and from while
assert finally yield
break for with
class from try
continue global return
def If Raise
elif Import print
else In pass
is Except or
del lambda not
2. Multi-Line Statements
Statements in Python end with a new line. Even though, allow the use of the line continuation character () to denote that the
line should continue. For example −
• total = item_one + 
• item_two + 
• item_three
3. Comments in Python
A hash sign (#) is used to define a comment in python .Python compile ignore the line, which are started from #
1. Single line comment
Eg. # Python is a awesome language.
2. Multiline comment
Eg. “”” Python is a awesome
language isn’t it”””
4. Input output In Python
Input:
User can give the input to python program by input keyword
Ex. i=input() #in python 3.6
Ex. i=raw_input () # in python 2.7
Output:
Print keyword is used for print something on monitor
Ex. print(“Python is a awesome language”)# in python
version 3.6
Print “Python is a awesome language” # in python
version 2.7
5. Variable Declaration
Variables reserved the memory locations to store values.
Assignee value to variable
counter = 500 # An integer assignment
miles = 6000.0 # A floating point
name = “Mukul Kirti Verma” # A string
Note:-
1.In python no need to define main().
2.In python no need to define data type for variables.
6. Multiple Assignment
 single value to several variables
a = b = c = 1
 Multiple objects to multiple variables
a, b, c = 1,2,"john"
Delete variable in python
To delete the reference to a number object by using the del statement.
Syntax of the del statement is −
del var1,var2,var3,…..,varN
Ex x,y,z=6,7,8
del x,y,z
Python Data types
1. Int
2. Float
3. Complex
4. Boolean
5. String
6. List
7. Tuple
8. Dictionary
Types of Operator
Python supports the following types of operators:
1.Arithmetic Operators
2.Comparison (Relational) Operators
3.Assignment Operators
4.Logical Operators
5.Bitwise Operators
6.Membership Operators
7.Identity Operators
Arithmetic Operators
Operator Example
+ Addition 2+3=5
-- Subtraction 3-2=1
* Multiplication 2*3=6
/ Division 8/2=4
% Modulus
(it returns remainder)
3%2=1
** Exponent
(Performs exponential )
2**3=8
// Floor Division 5//2=2
Comparison Operators
Operator Example
== compare two values that they are
equal or not
(a==d) return True if they are equal ,return
False if they are not equal
!= compare two values that they are
equal or not
(a==d) return False if they are equal ,return
True if they are not equal
<> Similar to != Similar to !=
> Compare that left side value is
greater then the right side value
a>b return true if a is greater then b
< Compare that right side value is
greater then left side value
a<b return true if b is greater then b
>= Compare that left side value is
greater then or equal to right side value
a>=b return true if a is greater then b or equal
to b
<= Compare that right side value is
greater then or equal to left side value
a<=b return true if a is Lesser then b or equal
to b
Assignment Operators
= Example
= c=a+b it will assigns a+b value
to c
+= c+=a it is equivalent to c=c+a
-= c-=a it is equivalent to c=c-a
*= c*=a it is equivalent to c=c*a
/= c/=a it is equivalent to c=c/a
%= c%=a it is equivalent to c=c%a
**= c**=a it is equivalent to c=c**a
//= c//=a it is equivalent to c=c//a
Bitwise Operators
Operator Example
& Binary AND 1 & 0 = 0
| Binary OR 1 | 0 = 0
^ Binary XOR 1 ^ 0 = 1
~ Binary Ones
complement
~001=1010
>> Binary Right Shift a=2;
2>>1 =1;
<< Binary Left shift a=2;
a<<1=4;
Logical Operators
Operator Example
And Logical AND (2<3 and 3>2) return true
or Logical OR (2<3 or 3>2) return false
Not Logical NOT(2>3) return True
Membership Operators
Operator Example
In Return true if it finds a variable in
the specified sequence and false if
not finds
2 in (2,3,5,6) return
true
not in Return true if it finds a variable in
the specified sequence and false if
not finds
2 not in (2,3,5,6)
return false
Identity Operators
Operator Example
Is Return true if the variables on
either
side of the operator point to the
same object and false otherwise
x is y return True if id(x) == d(y)
Is not Return false if the variables on the
either side of the operator point
to
the same object and true
otherwise
X is not y return true if id(x)!=id(y)
Operators Precedence
S. No. Operator Description (1. Has max prescience and7. has
lowest prescience )
1 peranthsis
//(floor division)
** Exponentiation
%(Modulo),
2 ~ (complement)
3 (Multiply), /(Division
4 + (Addition) ,-- (subtraction)
5 >>,<< (Right and left bitwise shift)
6 & (Bitwise ‘AND’)
7 ^ (Bitwise XOR), | (regular ‘OR’)
Operators Precedence Continue…
8. <= (greater then), <(less then),> (greater then), >= (greater
then)
9. <>(not equal to), == (equality operator), != (not equal to)
10. =(equal to), %=, /=, //=, --=, +=, *=, **= (Assignment
Operator)
11. is(is operator), is not(is not operator )
12. in(in Membership operator) not in(not in Membership
operator)
13. not (logical not) or(logical or), and(logical and)
Python Type Conversion and Type Casting
The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type
conversion. Python has two types of type conversion.
1.Implicit Type Conversion
2.Explicit Type Conversion
Key Points to Remember:
 In python type Conversion is the conversion of object from one data type to another data type.
 Implicit Type Conversion is automatically performed by the Python interpreter.
 Python avoids the loss of data in Implicit Type Conversion.
 Explicit Type Conversion is also called Type Casting, the data types of object are converted using predefined function
by user.
 In Type Casting loss of data may occur as we enforce the object to specific data type.
Condition statements
Three type of conditional statements
1. if
2. if , else (elif)
3. nested if else
If statment
if condition is true
if condition is false
Conditio
n
Code in
condition
If else statement
if condition is true
if condition is false
else code
Condition
Code in
condition
Code
Continue….
Syntax:
if expression:
statement(s)
else:
statement(s)
Python - Loops
Loop allow us to execute the set of statement for multiple times.
In python three types of loops are define
1. for
2. while
3. nested loop
4. for else
5. while else
Continue….
It has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax:
for i in sequence:
statements(s)
While Loop
A while loop statement in Python programming language repeatedly executes a target statement as long as a given
condition is true.
Syntax:
while expression:
statement(s)
Loop control statement
1.Break
2.Continue
3.pass
Standard Data Types
Python has five standard data types −
• Numbers
• String
• List
• Tuple
• Dictionary
Numbers in python
Number data types store numeric values. They are immutable data
types, means that changing the value of a number data type results
in a newly allocated object.
var1 = 1
var2 = 10
Python supports Three different numerical types −
int (signed integers)
float (floating point real values)
complex (complex numbers)
Mathematical Function
Function Description
abs() Return absolute value of x
exp() exp(x)=(e)power(x)
Floor() floor(x) :it Return floor value of x
Log() log(x) : it return logarithmic value of x
Max() max(x1,x2,x3…,xn) : it return max element in a list
Min() min(x1,x2,……xn): it return min element in a list
Pow() pow(x,y) : it return x**y
Ceil() Return ceiling value
Mathematical constraints
Sr.
No.
Constants & Description Example
1 Pi The mathematical constant
pi.
i=numpy.pi
Output :
i=3.141592653589793
2 e The mathematical constant
e.
i=numpy.e
Output :
i=2.718281828459045
Strings
Definition:-String are nothing but set of character.
Ex.
• var1 = ‘Hello scimox'
• var2 = "Python Programming“
• var3=“””hello my name is
mukul kirti verma”””
Escape Characters
f to clear screen
n for new line
r for return
t for tab
String Methods
Method
count returns occurrences of substring in string
isupper returns if all characters are uppercase characters
join Returns a Concatenated String
index Returns Index of Substring
isalnum Checks Alphanumeric Character
isdecimal Checks Decimal Characters
Isdigit Checks Digit Characters
isprintable Checks Printable Character
String Methods
Method Description
isspace Checks Whitespace Characters
swapcase swap uppercase characters to lowercase; vice versa
String Methods
Method Description
rindex Returns Highest Index of Substring
splitlines Splits String at Line Boundaries
rsplit Splits String From Right
find Find element in string
isspace Checks Whitespace Characters
swapcase swap uppercase characters to lowercase; vice versa
islower Checks if all Alphabets in a String are Lowercase
isnumeric Check whether all element of string in are numeric
String Special Operators
Operator Description
+ For Concatenation
* Repetition
[] Slice
[ : ] Range Slice
in Membership
not in Membership
r/R Raw String
Python Lists
The list can be written as a collection of comma-separated values (items) between square brackets. Values can be any type of.
Operation
1. Insert
2. Update
3. Delete
Eg.
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"]
Some other Operation on list
Expression Result
list1+list12 It will concatenate list1 and list2
len(list1) It will return length of list1
(‘ok',) * 4 It will return list with 4 element
with value ‘ok’
x in (x,y,z) It will check membership of x in list
max(list1) It will return max element in list
min(list1) It will return min element in list
Tuple In Python
A tuple is a sequence of immutable Python objects. Tuples elements cannot be changed
Creating a tuple is as simple as putting different comma-separated values in and put in parenthese.
Ex.
Tuple1=(1,2,3,4,5)
Tuple1 = (‘abc', ‘xyz', 1, 3.0);
Tuple1 = "a", "b", "c", "d";
Tuples Operations
Expression Result
tup1+tup2 It will concatenate tup1 and tup2
len(tup1) It will return length of tup1
(‘ok',) * 4 It will return tuple with 4 element
with value ‘ok’
x in (x,y,z) It will check membership of x in
tuple
max(tup1) It will return max element in tuple
min(tup1) It will return min element in tuple
count Count element In tuple
index Return index of an element in tuple
Dictionary In Python
In python, dictionary is similar to hash or maps in c++. It consists key and value pairs. The value can be accessed by unique
key in the dictionary. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any
type, but the keys must be of an immutable data type such as strings, numbers, or tuples.values can be any data type.
1. Insert
2. Update
3. Delete
Built-in Functions & Methods
len(dict) Gives the total length of the dictionary.
str(dict) it would convert dictionary in string.
type() it would return the type of element of a key passed.
Function in python
A function is a block of code which is run only when, it is called.
Creating or defining a Function;
def functionname( parameters ):
[expression]
Ex.
def printme(str):
print(str)
printme(“hi”)
Output:
‘hi’
Calling a Function
you can execute function code by calling it from
another function or directly from the Python prompt.
def printme( str ):
print str
return;
printme(“hi")# Output: ‘hi’
printme(“hello") #Output: ‘hello’
Function Arguments
A function can be call by using the following
types of formal arguments −
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
return Statement
The statement return statement quit a function, and optionally passing back an expression to its caller. A return statement with no arguments
returns none.
Ex.
def sum( arg1, arg2 ):
total = arg1 + arg2
print (sum( 5, 5 ));
print (sum)
Output:
10
10
Scope of Variables
There are two basic scopes of variables in python
1. Global variables
2. Local variables
Ex.
total = 0 This is global variable.
def sum( arg1, arg2 ):
total = arg1 + arg2
print( total )
return total
sum( 10, 20 )
print ( total )
Python GUI with Tkinter
Introduction to tkinter:
The tkinter package (“Tk interface”) is the standard Python interface to the Tk GUI toolkit. Both Tk and tkinter are available on
most Unix platforms, as well as on Windows systems. (Tk itself is not part of Python; it is maintained at ActiveState.)
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps −
Import the Tkinter module.
Create the GUI application main window.
Add one or more of the above-mentioned widgets to the GUI application.
Enter the main event loop to take action against each event triggered by the user.
Simple Form
#!/usr/bin/python
import Tkinter top = Tkinter.Tk()
# Code to add widgets will go here...
top.mainloop()
Tkinter Label
This widget implements a display box where you can place text or images. The text displayed by this widget can be updated
at any time you want.It is also possible to underline part of the text (like to identify a keyboard shortcut) and span the text
across multiple lines.
Ex:
from Tkinter import *
root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack() root.mainloop()
Tkinter Entry
The Entry widget is used to accept single-line text strings from a user.
If you want to display multiple lines of text that can be edited, then you should use the Text widget.
If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget.
Ex:
• from Tkinter import *
• top = Tk()
• L1 = Label(top, text="User Name")
• L1.pack( side = LEFT)
• E1 = Entry(top, bd =5)
• E1.pack(side = RIGHT)
• top.mainloop()
Tkinter Button
The Button widget is used to add buttons in a Python application. These buttons can display text or images that convey the
purpose of the buttons. You can attach a function or a method to a button which is called automatically when you click the
button.
Example:
• import Tkinter
• import tkMessageBox
• top = Tkinter.Tk()
• def helloCallBack():
• tkMessageBox.showinfo( "Hello Python", "Hello World")
• B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
• B.pack() top.mainloop()
Thank You

More Related Content

What's hot

python presentation
python presentationpython presentation
python presentation
VaibhavMawal
 
Python by Rj
Python by RjPython by Rj
Python data type
Python data typePython data type
Python data type
nuripatidar
 
1.python interpreter and interactive mode
1.python interpreter and interactive mode1.python interpreter and interactive mode
1.python interpreter and interactive mode
ManjuA8
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
amiable_indian
 
Python
PythonPython
Python
Aashish Jain
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Srinivas Narasegouda
 
Python basics
Python basicsPython basics
Begin with Python
Begin with PythonBegin with Python
Begin with Python
Narong Intiruk
 
Python ppt
Python pptPython ppt
Python ppt
Rohit Verma
 
Python basics
Python basicsPython basics
Python basics
Hoang Nguyen
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Ayshwarya Baburam
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Conditionalstatement
ConditionalstatementConditionalstatement
Conditionalstatement
RaginiJain21
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
primeteacher32
 
Operators in python
Operators in pythonOperators in python
Operators in python
eShikshak
 
Final presentation on python
Final presentation on pythonFinal presentation on python
Final presentation on python
RaginiJain21
 
Benefits & features of python |Advantages & disadvantages of python
Benefits & features of python |Advantages & disadvantages of pythonBenefits & features of python |Advantages & disadvantages of python
Benefits & features of python |Advantages & disadvantages of python
paradisetechsoftsolutions
 
Python programming
Python  programmingPython  programming
Python programming
Ashwin Kumar Ramasamy
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
KrishnaMildain
 

What's hot (20)

python presentation
python presentationpython presentation
python presentation
 
Python by Rj
Python by RjPython by Rj
Python by Rj
 
Python data type
Python data typePython data type
Python data type
 
1.python interpreter and interactive mode
1.python interpreter and interactive mode1.python interpreter and interactive mode
1.python interpreter and interactive mode
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python
PythonPython
Python
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python basics
Python basicsPython basics
Python basics
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
Python ppt
Python pptPython ppt
Python ppt
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Conditionalstatement
ConditionalstatementConditionalstatement
Conditionalstatement
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Operators in python
Operators in pythonOperators in python
Operators in python
 
Final presentation on python
Final presentation on pythonFinal presentation on python
Final presentation on python
 
Benefits & features of python |Advantages & disadvantages of python
Benefits & features of python |Advantages & disadvantages of pythonBenefits & features of python |Advantages & disadvantages of python
Benefits & features of python |Advantages & disadvantages of python
 
Python programming
Python  programmingPython  programming
Python programming
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
 

Similar to Welcome to python workshop

python introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxpython introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptx
ChandraPrakash715640
 
Introduction of Python
Introduction of PythonIntroduction of Python
Introduction of Python
ZENUS INFOTECH INDIA PVT. LTD.
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. tx
vishwanathgoudapatil1
 
basics of python programming5.pdf
basics of python programming5.pdfbasics of python programming5.pdf
basics of python programming5.pdf
Pushkaran3
 
PPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptxPPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptx
tcsonline1222
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
deepak teja
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
Mohammed Sikander
 
Python
PythonPython
Introduction to python programming ( part-1)
Introduction to python programming  ( part-1)Introduction to python programming  ( part-1)
Introduction to python programming ( part-1)
Ziyauddin Shaik
 
1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdf
MaheshGour5
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptx
Yusuf Ayuba
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
HNDE Labuduwa Galle
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
RojaPriya
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
IruolagbePius
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
natnaelmamuye
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdf
Sreedhar Chowdam
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
kavinilavuG
 
Python basics
Python basicsPython basics
Python basics
Manisha Gholve
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
KosmikTech1
 

Similar to Welcome to python workshop (20)

python introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxpython introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptx
 
Introduction of Python
Introduction of PythonIntroduction of Python
Introduction of Python
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. tx
 
basics of python programming5.pdf
basics of python programming5.pdfbasics of python programming5.pdf
basics of python programming5.pdf
 
PPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptxPPt Revision of the basics of python1.pptx
PPt Revision of the basics of python1.pptx
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Python
PythonPython
Python
 
Introduction to python programming ( part-1)
Introduction to python programming  ( part-1)Introduction to python programming  ( part-1)
Introduction to python programming ( part-1)
 
1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdf
 
modul-python-all.pptx
modul-python-all.pptxmodul-python-all.pptx
modul-python-all.pptx
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdf
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Python basics
Python basicsPython basics
Python basics
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
 

Recently uploaded

ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 

Recently uploaded (20)

ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 

Welcome to python workshop

  • 1. Welcome to Python workshop By – Mukul Kirti Verma
  • 3. Why to Learn Python? Python is a MUST for students and working professionals to become a great Software Engineer specially when they are working in Web Development Domain. I will list down some of the key advantages of learning Python: Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP. Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter directly to write your programs. Python is Object-Oriented − Python supports Object-Oriented style or technique of programming that encapsulates code within objects. Python is a Beginner's Language − Python is a great language for the beginner-level programmers and supports the development of a wide range of applications from simple text processing to WWW browsers to games.
  • 5. Area where python is used  Web development  Software development  Machine Learning,  IOT  Data analysis  App Development  Game Development
  • 6. History Python is developed by Guido van Rossum in 1989 at the National Research Institute for Mathematics and Computer Science in the Netherlands it was the successor to ABC and capable of exception handling and interfacing with the Amoeba operating system Python is derived from: Modula-3, C, C++ Unix shell Other scripting languages. Python is available under the GNU General Public License (GPL). The GNU General Public License is a free, copyleft license for software and other kinds of works.
  • 7. Features 1. Easy-to-learn and understand 2.. A broad standard library 3.Open Source 4. Interactive Mode 5. Portable (Platform in dependent) 6. Extendable 7. Databases 8. GUI Programming 9. Object Oriented Programming. 10. It can be used as a scripting language
  • 8. Features 9. Object Oriented Programming. 10. It can be used as a scripting language 11. It provides very high-level dynamic data types and supports dynamic type checking. 12.It supports automatic garbage collector. 13. Less line of code Python uses two strategies for memory Management: Reference counting: Garbage collection:
  • 9. Python is available Unix, Linux Win 9x/NT/2000 Macintosh (Intel, PPC, 68K) OS/2 DOS (multiple versions) Palm OS Nokia mobile phones(Symbian)
  • 10. Python Installation 1. Go to www.python.org 2. Go to Download menu 3. Click on windows menu 4. Download Python (what ever version you want. 5. Double click on downloaded Python.exe file and install it
  • 11. Set environment variable  Right click on My computer  Click on Properties  Then click on advance system setting In left hand side of the windows screen.  Then click on Set Environment variables  Now click on first New button and Add following
  • 12. Set environment variable 1. Select “path” variable in system variables 2. Click on edit button 3. Add following path in the path variable C:Users[Your_Current_User_Name]AppDataLocalProgramsPythonPython36; 4. Then click on ok Button. 5. Now open command prompt and type python If python shall is running then environment variable is set properly.
  • 13. Python Basic syntax  Python Identifiers  Reserved Words  Comments in Python  Input output In Python  Variable Types  Delete variable in python
  • 14. 1. Python Identifiers A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with:  Python does not allow A letter A to Z or a to z  An underscore (_) followed by zero more letters,  Underscores and digits (0 to 9).  @, $, and % within identifiers.  Python is a case sensitive programming language.  White specs not in b/w the catheters  E.g. My Name=“mukul”
  • 15. Reserved Words and from while assert finally yield break for with class from try continue global return def If Raise elif Import print else In pass is Except or del lambda not
  • 16. 2. Multi-Line Statements Statements in Python end with a new line. Even though, allow the use of the line continuation character () to denote that the line should continue. For example − • total = item_one + • item_two + • item_three
  • 17. 3. Comments in Python A hash sign (#) is used to define a comment in python .Python compile ignore the line, which are started from # 1. Single line comment Eg. # Python is a awesome language. 2. Multiline comment Eg. “”” Python is a awesome language isn’t it”””
  • 18. 4. Input output In Python Input: User can give the input to python program by input keyword Ex. i=input() #in python 3.6 Ex. i=raw_input () # in python 2.7 Output: Print keyword is used for print something on monitor Ex. print(“Python is a awesome language”)# in python version 3.6 Print “Python is a awesome language” # in python version 2.7
  • 19. 5. Variable Declaration Variables reserved the memory locations to store values. Assignee value to variable counter = 500 # An integer assignment miles = 6000.0 # A floating point name = “Mukul Kirti Verma” # A string Note:- 1.In python no need to define main(). 2.In python no need to define data type for variables.
  • 20. 6. Multiple Assignment  single value to several variables a = b = c = 1  Multiple objects to multiple variables a, b, c = 1,2,"john"
  • 21. Delete variable in python To delete the reference to a number object by using the del statement. Syntax of the del statement is − del var1,var2,var3,…..,varN Ex x,y,z=6,7,8 del x,y,z
  • 22. Python Data types 1. Int 2. Float 3. Complex 4. Boolean 5. String 6. List 7. Tuple 8. Dictionary
  • 23. Types of Operator Python supports the following types of operators: 1.Arithmetic Operators 2.Comparison (Relational) Operators 3.Assignment Operators 4.Logical Operators 5.Bitwise Operators 6.Membership Operators 7.Identity Operators
  • 24. Arithmetic Operators Operator Example + Addition 2+3=5 -- Subtraction 3-2=1 * Multiplication 2*3=6 / Division 8/2=4 % Modulus (it returns remainder) 3%2=1 ** Exponent (Performs exponential ) 2**3=8 // Floor Division 5//2=2
  • 25. Comparison Operators Operator Example == compare two values that they are equal or not (a==d) return True if they are equal ,return False if they are not equal != compare two values that they are equal or not (a==d) return False if they are equal ,return True if they are not equal <> Similar to != Similar to != > Compare that left side value is greater then the right side value a>b return true if a is greater then b < Compare that right side value is greater then left side value a<b return true if b is greater then b >= Compare that left side value is greater then or equal to right side value a>=b return true if a is greater then b or equal to b <= Compare that right side value is greater then or equal to left side value a<=b return true if a is Lesser then b or equal to b
  • 26. Assignment Operators = Example = c=a+b it will assigns a+b value to c += c+=a it is equivalent to c=c+a -= c-=a it is equivalent to c=c-a *= c*=a it is equivalent to c=c*a /= c/=a it is equivalent to c=c/a %= c%=a it is equivalent to c=c%a **= c**=a it is equivalent to c=c**a //= c//=a it is equivalent to c=c//a
  • 27. Bitwise Operators Operator Example & Binary AND 1 & 0 = 0 | Binary OR 1 | 0 = 0 ^ Binary XOR 1 ^ 0 = 1 ~ Binary Ones complement ~001=1010 >> Binary Right Shift a=2; 2>>1 =1; << Binary Left shift a=2; a<<1=4;
  • 28. Logical Operators Operator Example And Logical AND (2<3 and 3>2) return true or Logical OR (2<3 or 3>2) return false Not Logical NOT(2>3) return True
  • 29. Membership Operators Operator Example In Return true if it finds a variable in the specified sequence and false if not finds 2 in (2,3,5,6) return true not in Return true if it finds a variable in the specified sequence and false if not finds 2 not in (2,3,5,6) return false
  • 30. Identity Operators Operator Example Is Return true if the variables on either side of the operator point to the same object and false otherwise x is y return True if id(x) == d(y) Is not Return false if the variables on the either side of the operator point to the same object and true otherwise X is not y return true if id(x)!=id(y)
  • 31. Operators Precedence S. No. Operator Description (1. Has max prescience and7. has lowest prescience ) 1 peranthsis //(floor division) ** Exponentiation %(Modulo), 2 ~ (complement) 3 (Multiply), /(Division 4 + (Addition) ,-- (subtraction) 5 >>,<< (Right and left bitwise shift) 6 & (Bitwise ‘AND’) 7 ^ (Bitwise XOR), | (regular ‘OR’)
  • 32. Operators Precedence Continue… 8. <= (greater then), <(less then),> (greater then), >= (greater then) 9. <>(not equal to), == (equality operator), != (not equal to) 10. =(equal to), %=, /=, //=, --=, +=, *=, **= (Assignment Operator) 11. is(is operator), is not(is not operator ) 12. in(in Membership operator) not in(not in Membership operator) 13. not (logical not) or(logical or), and(logical and)
  • 33. Python Type Conversion and Type Casting The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion. Python has two types of type conversion. 1.Implicit Type Conversion 2.Explicit Type Conversion
  • 34. Key Points to Remember:  In python type Conversion is the conversion of object from one data type to another data type.  Implicit Type Conversion is automatically performed by the Python interpreter.  Python avoids the loss of data in Implicit Type Conversion.  Explicit Type Conversion is also called Type Casting, the data types of object are converted using predefined function by user.  In Type Casting loss of data may occur as we enforce the object to specific data type.
  • 35. Condition statements Three type of conditional statements 1. if 2. if , else (elif) 3. nested if else
  • 36. If statment if condition is true if condition is false Conditio n Code in condition
  • 37. If else statement if condition is true if condition is false else code Condition Code in condition Code
  • 39. Python - Loops Loop allow us to execute the set of statement for multiple times. In python three types of loops are define 1. for 2. while 3. nested loop 4. for else 5. while else
  • 40. Continue…. It has the ability to iterate over the items of any sequence, such as a list or a string. Syntax: for i in sequence: statements(s)
  • 41. While Loop A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. Syntax: while expression: statement(s)
  • 43. Standard Data Types Python has five standard data types − • Numbers • String • List • Tuple • Dictionary
  • 44. Numbers in python Number data types store numeric values. They are immutable data types, means that changing the value of a number data type results in a newly allocated object. var1 = 1 var2 = 10 Python supports Three different numerical types − int (signed integers) float (floating point real values) complex (complex numbers)
  • 45. Mathematical Function Function Description abs() Return absolute value of x exp() exp(x)=(e)power(x) Floor() floor(x) :it Return floor value of x Log() log(x) : it return logarithmic value of x Max() max(x1,x2,x3…,xn) : it return max element in a list Min() min(x1,x2,……xn): it return min element in a list Pow() pow(x,y) : it return x**y Ceil() Return ceiling value
  • 46. Mathematical constraints Sr. No. Constants & Description Example 1 Pi The mathematical constant pi. i=numpy.pi Output : i=3.141592653589793 2 e The mathematical constant e. i=numpy.e Output : i=2.718281828459045
  • 47. Strings Definition:-String are nothing but set of character. Ex. • var1 = ‘Hello scimox' • var2 = "Python Programming“ • var3=“””hello my name is mukul kirti verma”””
  • 48. Escape Characters f to clear screen n for new line r for return t for tab
  • 49. String Methods Method count returns occurrences of substring in string isupper returns if all characters are uppercase characters join Returns a Concatenated String index Returns Index of Substring isalnum Checks Alphanumeric Character isdecimal Checks Decimal Characters Isdigit Checks Digit Characters isprintable Checks Printable Character
  • 50. String Methods Method Description isspace Checks Whitespace Characters swapcase swap uppercase characters to lowercase; vice versa
  • 51. String Methods Method Description rindex Returns Highest Index of Substring splitlines Splits String at Line Boundaries rsplit Splits String From Right find Find element in string isspace Checks Whitespace Characters swapcase swap uppercase characters to lowercase; vice versa islower Checks if all Alphabets in a String are Lowercase isnumeric Check whether all element of string in are numeric
  • 52. String Special Operators Operator Description + For Concatenation * Repetition [] Slice [ : ] Range Slice in Membership not in Membership r/R Raw String
  • 53. Python Lists The list can be written as a collection of comma-separated values (items) between square brackets. Values can be any type of. Operation 1. Insert 2. Update 3. Delete Eg. list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"]
  • 54. Some other Operation on list Expression Result list1+list12 It will concatenate list1 and list2 len(list1) It will return length of list1 (‘ok',) * 4 It will return list with 4 element with value ‘ok’ x in (x,y,z) It will check membership of x in list max(list1) It will return max element in list min(list1) It will return min element in list
  • 55. Tuple In Python A tuple is a sequence of immutable Python objects. Tuples elements cannot be changed Creating a tuple is as simple as putting different comma-separated values in and put in parenthese. Ex. Tuple1=(1,2,3,4,5) Tuple1 = (‘abc', ‘xyz', 1, 3.0); Tuple1 = "a", "b", "c", "d";
  • 56. Tuples Operations Expression Result tup1+tup2 It will concatenate tup1 and tup2 len(tup1) It will return length of tup1 (‘ok',) * 4 It will return tuple with 4 element with value ‘ok’ x in (x,y,z) It will check membership of x in tuple max(tup1) It will return max element in tuple min(tup1) It will return min element in tuple count Count element In tuple index Return index of an element in tuple
  • 57. Dictionary In Python In python, dictionary is similar to hash or maps in c++. It consists key and value pairs. The value can be accessed by unique key in the dictionary. Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.values can be any data type. 1. Insert 2. Update 3. Delete
  • 58. Built-in Functions & Methods len(dict) Gives the total length of the dictionary. str(dict) it would convert dictionary in string. type() it would return the type of element of a key passed.
  • 59. Function in python A function is a block of code which is run only when, it is called. Creating or defining a Function; def functionname( parameters ): [expression] Ex. def printme(str): print(str) printme(“hi”) Output: ‘hi’
  • 60. Calling a Function you can execute function code by calling it from another function or directly from the Python prompt. def printme( str ): print str return; printme(“hi")# Output: ‘hi’ printme(“hello") #Output: ‘hello’
  • 61. Function Arguments A function can be call by using the following types of formal arguments − 1. Required arguments 2. Keyword arguments 3. Default arguments 4. Variable-length arguments
  • 62. return Statement The statement return statement quit a function, and optionally passing back an expression to its caller. A return statement with no arguments returns none. Ex. def sum( arg1, arg2 ): total = arg1 + arg2 print (sum( 5, 5 )); print (sum) Output: 10 10
  • 63. Scope of Variables There are two basic scopes of variables in python 1. Global variables 2. Local variables Ex. total = 0 This is global variable. def sum( arg1, arg2 ): total = arg1 + arg2 print( total ) return total sum( 10, 20 ) print ( total )
  • 64. Python GUI with Tkinter Introduction to tkinter: The tkinter package (“Tk interface”) is the standard Python interface to the Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, as well as on Windows systems. (Tk itself is not part of Python; it is maintained at ActiveState.) Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps − Import the Tkinter module. Create the GUI application main window. Add one or more of the above-mentioned widgets to the GUI application. Enter the main event loop to take action against each event triggered by the user.
  • 65. Simple Form #!/usr/bin/python import Tkinter top = Tkinter.Tk() # Code to add widgets will go here... top.mainloop()
  • 66. Tkinter Label This widget implements a display box where you can place text or images. The text displayed by this widget can be updated at any time you want.It is also possible to underline part of the text (like to identify a keyboard shortcut) and span the text across multiple lines. Ex: from Tkinter import * root = Tk() var = StringVar() label = Label( root, textvariable=var, relief=RAISED ) var.set("Hey!? How are you doing?") label.pack() root.mainloop()
  • 67. Tkinter Entry The Entry widget is used to accept single-line text strings from a user. If you want to display multiple lines of text that can be edited, then you should use the Text widget. If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget. Ex: • from Tkinter import * • top = Tk() • L1 = Label(top, text="User Name") • L1.pack( side = LEFT) • E1 = Entry(top, bd =5) • E1.pack(side = RIGHT) • top.mainloop()
  • 68. Tkinter Button The Button widget is used to add buttons in a Python application. These buttons can display text or images that convey the purpose of the buttons. You can attach a function or a method to a button which is called automatically when you click the button. Example: • import Tkinter • import tkMessageBox • top = Tkinter.Tk() • def helloCallBack(): • tkMessageBox.showinfo( "Hello Python", "Hello World") • B = Tkinter.Button(top, text ="Hello", command = helloCallBack) • B.pack() top.mainloop()

Editor's Notes

  1. In Slide Show mode, select the arrows to visit links.