SlideShare a Scribd company logo
1 of 69
By Kevin Harris
An Introduction to Python
What is Python?
• Python is a portable, interpreted, object-
oriented scripting language created by
Guido van Rossum.
• Its development started at the National
Research Institute for Mathematics and
Computer Science in the Netherlands , and
continues under the ownership of the
Python Software Foundation.
• Even though its name is commonly
associated with the snake, it is actually
named after the British comedy troupe,
Monty Python’s Flying Circus.
Why learn a scripting language?
• Easier to learn than more traditional
compiled languages like C/C++
• Allows concepts to be prototyped
faster
• Ideal for administrative tasks which
can benefit from automation
• Typically cross platform
Why Python?
So, why use Python over other
scripting languages?
• Well tested and widely used
• Great documentation
• Strong community support
• Widely Cross-platform
• Open sourced
• Can be freely used and distributed, even
for commercial purposes.
How do I install Python?
• Simple… download it from
www.python.org and install it.
• Most Linux distributions already come
with it, but it may need updating.
• Current version, as of this
presentation, is 2.4.2 Click here to
download this version for Windows.
How do I edit Python?
• IDLE is a free GUI based text editor which
ships with Python.
• You could just write your scripts with
Notepad, but IDLE has many helpful
features like keyword highlighting.
• Click your “Start” button and Find “Python
2.4” on your “All Programs” menu. Then
select and run “IDLE (Python GUI)”.
• You can also right-click on any python
script (.py) and select “Edit with IDLE” to
open it.
IDLE in Action
“Hello World!”
• The “Hello World!” example is a tradition
amongst programmers, so lets start there…
• Run IDLE and type in the following
print “Hello World!”
• Save your work and hit F5 to run it.
• The script simply prints the string, “Hello
World!” to the console.
Run Sample Script…
• Load “hello_world.py” into IDLE and hit F5
to run it.
• NOTE: Scripts can also be executed by
simply double-clicking them, Unfortunately,
they often run too quickly to read the output
so you’ll need to force a pause. I like to
use a function called raw_input to pause
the script before it closes the console. The
next script “hello_world_with_pause.py”,
demonstrates this little hack.
The print function
• The print function simply outputs a string value to
our script’s console.
print “Hello World!”
• It’s very useful for communicating with users or
outputting important information.
print “Game Over!”
• We get this function for free from Python.
• Later, we’ll learn to write our own functions.
Adding Comments
• Comments allow us to add useful information to
our scripts, which the Python interpreter will
ignore completely.
• Each line for a comment must begin with the
number sign ‘#’.
# This is a programming tradition…
print “Hello World!”
• Do yourself a favor and use them!
Quoting Strings
• Character strings are denoted using quotes.
• You can use double quotes…
print “Hello World!” # Fine.
• Or, you can use single quotes…
print ‘Hello World!’ # Also fine.
• It doesn’t matter as long as you don’t mix them
print “Hello World!’ # Syntax Error!
Triple Quotes
• You can even use triple quotes, which
make quoting multi-line strings easier.
print “““
This is line one.
This is line two.
This is line three.
Etc…
”””
Run Sample Script…
• Load “triple_quotes.py” into IDLE and
hit F5 to run it.
Strings and Control Characters
• There are several control characters which allow
us to modify or change the way character strings
get printed by the print function.
• They’re composed of a backslash followed by a
character. Here are a few of the more important
ones:
n : New line
t : Tabs
 : Backslash
' : Single Quote
" : Double Quote
Run Sample Script…
• Load “control_characters.py” into
IDLE and hit F5 to run it.
Variables
• Like all programming languages, Python variables
are similar to variables in Algebra.
• They act as place holders or symbolic
representations for a value, which may or may not
change over time.
• Here are six of the most important variable types
in Python:
int Plain Integers ( 25 )
long Long Integers ( 4294967296 )
float Floating-point Numbers
( 3.14159265358979 )
bool Booleans ( True, False )
str Strings ( “Hello World!” )
list Sequenced List ( [25, 50, 75, 100]
)
Type-less Variables
• Even though it supports variable types,
Python is actually type-less, meaning you
do not have to specify the variable’s type to
use it.
• You can use a variable as a character
string one moment and then overwrite its
value with a integer the next.
• This makes it easier to learn and use the
language but being type-less opens the
door to some hard to find bugs if you’re not
careful.
• If you’re uncertain of a variable’s type, use
the type function to verify its type.
Rules for Naming Variables
• You can use letters, digits, and
underscores when naming your variables.
• But, you cannot start with a digit.
var = 0 # Fine.
var1 = 0 # Fine.
var_1= 0 # Fine.
_var = 0 # Fine.
1var = 0 # Syntax Error!
Rules for Naming Variables
• Also, you can’t name your variables
after any of Python’s reserved
keywords.
and, del, for, is, raise, assert, elif,
from, lambda, return, break, else,
global, not, try, class, except, if, or,
while, continue, exec, import, pass,
yield, def, finally, in, print
Run Sample Script…
• Load “variable_types.py” into IDLE and hit
F5 to run it.
• NOTE: Be careful when using Python
variables for floating-point numbers (i.e.
3.14) Floats have limited precision, which
changes from platform to platform. This
basically means there is a limit on how big
or small the number can be. Run the script
and note how "pi" gets chopped off and
rounded up.
Numerical Precision
• Integers
• Generally 32 signed bits of precision
• [2,147,483,647 .. –2,147,483,648]
• or basically (-232
, 232
)
• Example: 25
• Long Integers
• Unlimited precision or size
• Format: <number>L
• Example: 4294967296L
• Floating-point
• Platform dependant “double” precision
• Example: 3.141592653589793
Type Conversion
• The special constructor functions int, long, float, complex,
and bool can be used to produce numbers of a specific type.
• For example, if you have a variable that is being used as a
float, but you want to use it like an integer do this:
myFloat = 25.12
myInt = 25
print myInt + int( myFloat )
• With out the explicit conversion, Python will automatically
upgrade your addition to floating-point addition, which you
may not want especially if your intention was to drop the
decimal places.
Type Conversion
• There is also a special constructor function called
str that converts numerical types into strings.
myInt = 25
myString = "The value of 'myInt' is "
print myString + str( myInt )
• You will use this function a lot when debugging!
• Note how the addition operator was used to join
the two strings together as one.
Run Sample Script…
• Load “type_conversion.py” into IDLE
and hit F5 to run it.
Arithmetic Operators
• Arithmetic Operators allow us to perform
mathematical operations on two variables or
values.
• Each operator returns the result of the specified
operation.
+ Addition
- Subtraction
* Multiplication
/ Float Division
** Exponent
abs Absolute Value
Run Sample Script…
• Load “arithmetic_operators.py” into
IDLE and hit F5 to run it.
Comparison Operators
• Comparison Operators return a True or
False value for the two variables or values
being compared.
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Is equal to
!= Is not equal to
Run Sample Script…
• Load “comparison_operators.py” into
IDLE and hit F5 to run it.
Boolean Operators
• Python also supports three Boolean Operators,
and, or, and not, which allow us to make use of
Boolean Logic in our scripts.
• Below are the Truth Tables for and, or, and not.
Boolean Operators
Suppose that… var1 = 10.
• The and operator will return True if and only if both
comparisons return True.
print var1 == 10 and var1 < 5 (Prints False)
• The or operator will return True if either of the comparisons
return True.
print var1 == 20 or var1 > 5 (Prints True)
• And the not operator simply negates or inverts the
comparison’s result.
print not var1 == 10 (Prints False)
Run Sample Script…
• Load “boolean_operators.py” into
IDLE and hit F5 to run it.
Special String Operators
• It may seem odd but Python even supports a few operators
for strings.
• Two strings can be joined (concatenation) using the +
operator.
print “Game ” + “Over!”
Outputs “Game Over!” to the console.
• A string can be repeated (repetition) by using the * operator.
print “Bang! ” * 3
Outputs “Bang! Bang! Bang! ” to the console.
Run Sample Script…
• Load “string_operators.py” into IDLE
and hit F5 to run it.
Flow Control
• Flow Control allows a program or
script to alter its flow of execution
based on some condition or test.
• The most important keywords for
performing Flow Control in Python are
if, else, elif, for, and while.
If Statement
• The most basic form of Flow Control is the if
statement.
# If the player’s health is less than or equal to 0 - kill
him!
if health <= 0:
print “You’re dead!”
• Note how the action to be taken by the if
statement is indented or tabbed over. This is not a
style issue – it’s required.
• Also, note how the if statement ends with a semi-
colon.
Run Sample Script…
• Load “if_statement.py” into IDLE and
hit F5 to run it.
If-else Statement
• The if-else statement allows us to pick one of two
possible actions instead of a all-or-nothing choice.
health = 75
if health <= 0:
print “You're dead!”
else:
print “You're alive!”
• Again, note how the if and else keywords and their
actions are indented. It’s very important to get this
right!
Run Sample Script…
• Load “if_else_statement.py” into IDLE
and hit F5 to run it.
If-elif-else Statement
• The if-elif-else statement allows us to pick one of
several possible actions by chaining two or more if
statements together.
health = 24
if health <= 0:
print "You're dead!"
elif health < 25:
print "You're alive - but badly wounded!"
else:
print "You're alive!"
Run Sample Script…
• Load “if_elif_else_statement.py” into
IDLE and hit F5 to run it.
while Statement
• The while statement allows us to continuously repeat an action until
some condition is satisfied.
numRocketsToFire = 3
rocketCount = 0
while rocketCount < numRocketsToFire:
# Increase the rocket counter by one
rocketCount = rocketCount + 1
print “Firing rocket #” + str( rocketCount )
• This while statement will continue to ‘loop’ and print out a “Firing
rocket” message until the variable “rocketCount” reaches the
current value of “numRocketsToFire”, which is 3.
Run Sample Script…
• Load “while_statement.py” into IDLE
and hit F5 to run it.
for Statement
• The for statement allows us to repeat an action based on the
iteration of a Sequenced List.
weapons = [ “Pistol”, “Rifle”, “Grenade”, “Rocket Launcher” ]
print “-- Weapon Inventory --”
for x in weapons:
print x
• The for statement will loop once for every item in the list.
• Note how we use the temporary variable ‘x’ to represent the
current item being worked with.
Run Sample Script…
• Load “for_statement.py” into IDLE and
hit F5 to run it.
break Keyword
• The break keyword can be used to escape from while and for
loops early.
numbers = [100, 25, 125, 50, 150, 75, 175]
for x in numbers:
print x
# As soon as we find 50 - stop the search!
if x == 50:
print "Found It!"
break;
• Instead of examining every list entry in “numbers”, The for
loop above will be terminated as soon as the value 50 is
found.
Run Sample Script…
• Load “for_break_statement.py” into
IDLE and hit F5 to run it.
continue Keyword
• The continue keyword can be used to short-circuit or bypass
parts of a while or for loop.
numbers = [100, 25, 125, 50, 150, 75, 175]
for x in numbers:
# Skip all triple digit numbers
if x >= 100:
continue;
print x
• The for loop above only wants to print double digit numbers.
It will simply continue on to the next iteration of the for loop
if x is found to be a triple digit number.
Run Sample Script…
• Load “for_continue_statement.py” into
IDLE and hit F5 to run it.
Functions
• A function allows several Python
statements to be grouped together so
they can be called or executed
repeatedly from somewhere else in
the script.
• We use the def keyword to define a
new function.
Defining functions
• Below, we define a new function called
“printGameOver”, which simply prints out, “Game
Over!”.
def printGameOver():
print “Game Over!”
• Again, note how indenting is used to denote the
function’s body and how a semi-colon is used to
terminate the function’s definition.
Run Sample Script…
• Load “function.py” into IDLE and hit
F5 to run it.
Function arguments
• Often functions are required to
perform some task based on
information passed in by the user.
• These bits of Information are passed
in using function arguments.
• Function arguments are defined within
the parentheses “()”, which are placed
at the end of the function’s name.
Function arguments
• Our new version of printGameOver, can now print
out customizable, “Game Over!”, messages by
using our new argument called “playersName”.
def printGameOver( playersName ):
print “Game Over... ” + playersName + “!”
• Now, when we call our function we can specify
which player is being killed off.
Run Sample Script…
• Load “function_arguments.py” into
IDLE and hit F5 to run it.
Default Argument Values
• Once you add arguments to your
function, it will be illegal to call that
function with out passing the required
arguments.
• The only way around this it is to
specify a default argument value.
Default Argument Values
• Below, the argument called “playersName”
has been assigned the default value of,
“Guest”.
def printGameOver( playersName=“Guest” ):
print “Game Over... ” + playersName + “!”
• If we call the function and pass nothing, the
string value of “Guest” will be used
automatically.
Run Sample Script…
• Load “default_argument_values.py”
into IDLE and hit F5 to run it.
Multiple Function arguments
• If we want, we can define as many arguments as we like.
def printGameOver( playersName, totalKills ):
print “Game Over... ” + playersName + “!”
print “Total Kills: ” + str( totalKills ) + “n”
• Of course, we must make sure that we pass the arguments in
the correct order or Python will get confused.
printGameOver( "camper_boy", 15 ) # Correct!
printGameOver( 12, "killaHurtz" ) # Syntax Error!
Run Sample Script…
• Load “multiple_arguments.py” into
IDLE and hit F5 to run it.
Keyword arguments
• If you really want to change the order of how the arguments
get passed, you can use keyword arguments.
def printGameOver( playersName, totalKills ):
print “Game Over... ” + playersName + “!”
print “Total Kills: ” + str( totalKills ) + “n”
printGameOver( totalKills=12, playersName=“killaHurtz” )
• Note how we use the argument’s name as a keyword when
calling the function.
Run Sample Script…
• Load “keyword_arguments.py” into
IDLE and hit F5 to run it.
Function Return Values
• A function can also output or return a value based on its
work.
• The function below calculates and returns the average of a
list of numbers.
def average( numberList ):
numCount = 0
runningTotal = 0
for n in numberList:
numCount = numCount + 1
runningTotal = runningTotal + n
return runningTotal / numCount
• Note how the list’s average is returned using the return
keyword.
Assigning the return value
• Here’s how the return value of our average function would be
used…
myNumbers = [5.0, 7.0, 8.0, 2.0]
theAverage = average( myNumbers )
print "The average of the list is " + str( theAverage ) + "."
• Note how we assign the return value of average to our
variable called “theAverage”.
Run Sample Script…
• Load “function_return_value.py” into
IDLE and hit F5 to run it.
Multiple Return Values
• A function can also output more than one value during the return.
• This version of average not only returns the average of the list
passed in but it also returns a counter which tells us how many
numbers were in the list that was averaged.
def average( numberList ):
numCount = 0
runningTotal = 0
for n in numberList:
numCount = numCount + 1
runningTotal = runningTotal + n
return runningTotal / numCount, numCount
• Note how the return keyword now returns two values which are
separated by a comma.
Assigning the return values
• Here’s how the multiple return value of our average function
could be used…
myNumbers = [5.0, 7.0, 8.0, 2.0]
theAverage, numberCount = average( myNumbers )
print "The average of the list is " + str( theAverage ) + "."
print "The list contained " + str( numberCount ) + " numbers.“
• Note how we assign the return values of average to our
variables “theAverage” and “numberCount”.
Run Sample Script…
• Load “multiple_return_values.py” into
IDLE and hit F5 to run it.
Conclusion
• This concludes your introduction to
Python.
• You now know enough of the basics
to write useful Python scripts and to
teach yourself some of the more
advanced features of Python.
• To learn more, consult the
documentation that ships with Python
or visit the online documentation.

More Related Content

What's hot

What's hot (20)

Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)
 
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
 
Python Tutorial for Beginner
Python Tutorial for BeginnerPython Tutorial for Beginner
Python Tutorial for Beginner
 
Perl Modules
Perl ModulesPerl Modules
Perl Modules
 
Python ppt
Python pptPython ppt
Python ppt
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Python made easy
Python made easy Python made easy
Python made easy
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Get started python programming part 1
Get started python programming   part 1Get started python programming   part 1
Get started python programming part 1
 
Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming Language
 
Python programming
Python programmingPython programming
Python programming
 
Python教程 / Python tutorial
Python教程 / Python tutorialPython教程 / Python tutorial
Python教程 / Python tutorial
 

Viewers also liked

Copy Of Blood Quiz
Copy Of Blood QuizCopy Of Blood Quiz
Copy Of Blood Quiz
griggans
 
TEDx talk: How digital ecosystem changes learning
TEDx talk: How digital ecosystem changes learningTEDx talk: How digital ecosystem changes learning
TEDx talk: How digital ecosystem changes learning
Kai Pata
 
Year Video Take One
Year Video Take OneYear Video Take One
Year Video Take One
rddietrich
 
CRM & HE
CRM & HECRM & HE
CRM & HE
scottw
 
Articles Intro
Articles IntroArticles Intro
Articles Intro
History360
 

Viewers also liked (20)

Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
 
Copy Of Blood Quiz
Copy Of Blood QuizCopy Of Blood Quiz
Copy Of Blood Quiz
 
TEDx talk: How digital ecosystem changes learning
TEDx talk: How digital ecosystem changes learningTEDx talk: How digital ecosystem changes learning
TEDx talk: How digital ecosystem changes learning
 
Guitar Hero Transition in East Lothian
Guitar Hero Transition in East LothianGuitar Hero Transition in East Lothian
Guitar Hero Transition in East Lothian
 
tyrikokkuvote
tyrikokkuvotetyrikokkuvote
tyrikokkuvote
 
Yeast8
Yeast8Yeast8
Yeast8
 
Year Video Take One
Year Video Take OneYear Video Take One
Year Video Take One
 
Tutorialwong
TutorialwongTutorialwong
Tutorialwong
 
Waisetsu hitorimondo
Waisetsu hitorimondoWaisetsu hitorimondo
Waisetsu hitorimondo
 
Online Impact Oct 12 2009
Online Impact Oct 12 2009Online Impact Oct 12 2009
Online Impact Oct 12 2009
 
CRM & HE
CRM & HECRM & HE
CRM & HE
 
Coping With The Changing Web
Coping With The Changing WebCoping With The Changing Web
Coping With The Changing Web
 
Presentation to AIESEC gathering
Presentation to AIESEC gatheringPresentation to AIESEC gathering
Presentation to AIESEC gathering
 
Kongres PR Rzeszow 2009
Kongres PR Rzeszow 2009Kongres PR Rzeszow 2009
Kongres PR Rzeszow 2009
 
2010 Biosphere or 'What's this got to do with the price of fish?'
2010 Biosphere or 'What's this got to do with the price of fish?'2010 Biosphere or 'What's this got to do with the price of fish?'
2010 Biosphere or 'What's this got to do with the price of fish?'
 
Personal Learning Networks - Scotland Education Summer School
Personal Learning Networks - Scotland Education Summer SchoolPersonal Learning Networks - Scotland Education Summer School
Personal Learning Networks - Scotland Education Summer School
 
elec101general_info
elec101general_infoelec101general_info
elec101general_info
 
Articles Intro
Articles IntroArticles Intro
Articles Intro
 
What are we educating for? - digital education tools for 2010s
What are we educating for? - digital education tools for 2010sWhat are we educating for? - digital education tools for 2010s
What are we educating for? - digital education tools for 2010s
 
ESMP Update
ESMP UpdateESMP Update
ESMP Update
 

Similar to Python - Introduction

Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
Chetan Giridhar
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Michpice
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxQ-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
nyomans1
 

Similar to Python - Introduction (20)

Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdfQ-Step_WS_02102019_Practical_introduction_to_Python.pdf
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
 
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptxQ-Step_WS_02102019_Practical_introduction_to_Python.pptx
Q-Step_WS_02102019_Practical_introduction_to_Python.pptx
 
Q-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptxQ-SPractical_introduction_to_Python.pptx
Q-SPractical_introduction_to_Python.pptx
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 
Python Demo.pptx
Python Demo.pptxPython Demo.pptx
Python Demo.pptx
 
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdfPy-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
 
Python intro
Python introPython intro
Python intro
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
Class_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdfClass_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdf
 
4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptx4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptx
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
Fundamentals of python
Fundamentals of pythonFundamentals of python
Fundamentals of python
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security Professionals
 
Python Programming.pdf
Python Programming.pdfPython Programming.pdf
Python Programming.pdf
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 

Python - Introduction

  • 1. By Kevin Harris An Introduction to Python
  • 2. What is Python? • Python is a portable, interpreted, object- oriented scripting language created by Guido van Rossum. • Its development started at the National Research Institute for Mathematics and Computer Science in the Netherlands , and continues under the ownership of the Python Software Foundation. • Even though its name is commonly associated with the snake, it is actually named after the British comedy troupe, Monty Python’s Flying Circus.
  • 3. Why learn a scripting language? • Easier to learn than more traditional compiled languages like C/C++ • Allows concepts to be prototyped faster • Ideal for administrative tasks which can benefit from automation • Typically cross platform
  • 4. Why Python? So, why use Python over other scripting languages? • Well tested and widely used • Great documentation • Strong community support • Widely Cross-platform • Open sourced • Can be freely used and distributed, even for commercial purposes.
  • 5. How do I install Python? • Simple… download it from www.python.org and install it. • Most Linux distributions already come with it, but it may need updating. • Current version, as of this presentation, is 2.4.2 Click here to download this version for Windows.
  • 6. How do I edit Python? • IDLE is a free GUI based text editor which ships with Python. • You could just write your scripts with Notepad, but IDLE has many helpful features like keyword highlighting. • Click your “Start” button and Find “Python 2.4” on your “All Programs” menu. Then select and run “IDLE (Python GUI)”. • You can also right-click on any python script (.py) and select “Edit with IDLE” to open it.
  • 8. “Hello World!” • The “Hello World!” example is a tradition amongst programmers, so lets start there… • Run IDLE and type in the following print “Hello World!” • Save your work and hit F5 to run it. • The script simply prints the string, “Hello World!” to the console.
  • 9. Run Sample Script… • Load “hello_world.py” into IDLE and hit F5 to run it. • NOTE: Scripts can also be executed by simply double-clicking them, Unfortunately, they often run too quickly to read the output so you’ll need to force a pause. I like to use a function called raw_input to pause the script before it closes the console. The next script “hello_world_with_pause.py”, demonstrates this little hack.
  • 10. The print function • The print function simply outputs a string value to our script’s console. print “Hello World!” • It’s very useful for communicating with users or outputting important information. print “Game Over!” • We get this function for free from Python. • Later, we’ll learn to write our own functions.
  • 11. Adding Comments • Comments allow us to add useful information to our scripts, which the Python interpreter will ignore completely. • Each line for a comment must begin with the number sign ‘#’. # This is a programming tradition… print “Hello World!” • Do yourself a favor and use them!
  • 12. Quoting Strings • Character strings are denoted using quotes. • You can use double quotes… print “Hello World!” # Fine. • Or, you can use single quotes… print ‘Hello World!’ # Also fine. • It doesn’t matter as long as you don’t mix them print “Hello World!’ # Syntax Error!
  • 13. Triple Quotes • You can even use triple quotes, which make quoting multi-line strings easier. print “““ This is line one. This is line two. This is line three. Etc… ”””
  • 14. Run Sample Script… • Load “triple_quotes.py” into IDLE and hit F5 to run it.
  • 15. Strings and Control Characters • There are several control characters which allow us to modify or change the way character strings get printed by the print function. • They’re composed of a backslash followed by a character. Here are a few of the more important ones: n : New line t : Tabs : Backslash ' : Single Quote " : Double Quote
  • 16. Run Sample Script… • Load “control_characters.py” into IDLE and hit F5 to run it.
  • 17. Variables • Like all programming languages, Python variables are similar to variables in Algebra. • They act as place holders or symbolic representations for a value, which may or may not change over time. • Here are six of the most important variable types in Python: int Plain Integers ( 25 ) long Long Integers ( 4294967296 ) float Floating-point Numbers ( 3.14159265358979 ) bool Booleans ( True, False ) str Strings ( “Hello World!” ) list Sequenced List ( [25, 50, 75, 100] )
  • 18. Type-less Variables • Even though it supports variable types, Python is actually type-less, meaning you do not have to specify the variable’s type to use it. • You can use a variable as a character string one moment and then overwrite its value with a integer the next. • This makes it easier to learn and use the language but being type-less opens the door to some hard to find bugs if you’re not careful. • If you’re uncertain of a variable’s type, use the type function to verify its type.
  • 19. Rules for Naming Variables • You can use letters, digits, and underscores when naming your variables. • But, you cannot start with a digit. var = 0 # Fine. var1 = 0 # Fine. var_1= 0 # Fine. _var = 0 # Fine. 1var = 0 # Syntax Error!
  • 20. Rules for Naming Variables • Also, you can’t name your variables after any of Python’s reserved keywords. and, del, for, is, raise, assert, elif, from, lambda, return, break, else, global, not, try, class, except, if, or, while, continue, exec, import, pass, yield, def, finally, in, print
  • 21. Run Sample Script… • Load “variable_types.py” into IDLE and hit F5 to run it. • NOTE: Be careful when using Python variables for floating-point numbers (i.e. 3.14) Floats have limited precision, which changes from platform to platform. This basically means there is a limit on how big or small the number can be. Run the script and note how "pi" gets chopped off and rounded up.
  • 22. Numerical Precision • Integers • Generally 32 signed bits of precision • [2,147,483,647 .. –2,147,483,648] • or basically (-232 , 232 ) • Example: 25 • Long Integers • Unlimited precision or size • Format: <number>L • Example: 4294967296L • Floating-point • Platform dependant “double” precision • Example: 3.141592653589793
  • 23. Type Conversion • The special constructor functions int, long, float, complex, and bool can be used to produce numbers of a specific type. • For example, if you have a variable that is being used as a float, but you want to use it like an integer do this: myFloat = 25.12 myInt = 25 print myInt + int( myFloat ) • With out the explicit conversion, Python will automatically upgrade your addition to floating-point addition, which you may not want especially if your intention was to drop the decimal places.
  • 24. Type Conversion • There is also a special constructor function called str that converts numerical types into strings. myInt = 25 myString = "The value of 'myInt' is " print myString + str( myInt ) • You will use this function a lot when debugging! • Note how the addition operator was used to join the two strings together as one.
  • 25. Run Sample Script… • Load “type_conversion.py” into IDLE and hit F5 to run it.
  • 26. Arithmetic Operators • Arithmetic Operators allow us to perform mathematical operations on two variables or values. • Each operator returns the result of the specified operation. + Addition - Subtraction * Multiplication / Float Division ** Exponent abs Absolute Value
  • 27. Run Sample Script… • Load “arithmetic_operators.py” into IDLE and hit F5 to run it.
  • 28. Comparison Operators • Comparison Operators return a True or False value for the two variables or values being compared. < Less than <= Less than or equal to > Greater than >= Greater than or equal to == Is equal to != Is not equal to
  • 29. Run Sample Script… • Load “comparison_operators.py” into IDLE and hit F5 to run it.
  • 30. Boolean Operators • Python also supports three Boolean Operators, and, or, and not, which allow us to make use of Boolean Logic in our scripts. • Below are the Truth Tables for and, or, and not.
  • 31. Boolean Operators Suppose that… var1 = 10. • The and operator will return True if and only if both comparisons return True. print var1 == 10 and var1 < 5 (Prints False) • The or operator will return True if either of the comparisons return True. print var1 == 20 or var1 > 5 (Prints True) • And the not operator simply negates or inverts the comparison’s result. print not var1 == 10 (Prints False)
  • 32. Run Sample Script… • Load “boolean_operators.py” into IDLE and hit F5 to run it.
  • 33. Special String Operators • It may seem odd but Python even supports a few operators for strings. • Two strings can be joined (concatenation) using the + operator. print “Game ” + “Over!” Outputs “Game Over!” to the console. • A string can be repeated (repetition) by using the * operator. print “Bang! ” * 3 Outputs “Bang! Bang! Bang! ” to the console.
  • 34. Run Sample Script… • Load “string_operators.py” into IDLE and hit F5 to run it.
  • 35. Flow Control • Flow Control allows a program or script to alter its flow of execution based on some condition or test. • The most important keywords for performing Flow Control in Python are if, else, elif, for, and while.
  • 36. If Statement • The most basic form of Flow Control is the if statement. # If the player’s health is less than or equal to 0 - kill him! if health <= 0: print “You’re dead!” • Note how the action to be taken by the if statement is indented or tabbed over. This is not a style issue – it’s required. • Also, note how the if statement ends with a semi- colon.
  • 37. Run Sample Script… • Load “if_statement.py” into IDLE and hit F5 to run it.
  • 38. If-else Statement • The if-else statement allows us to pick one of two possible actions instead of a all-or-nothing choice. health = 75 if health <= 0: print “You're dead!” else: print “You're alive!” • Again, note how the if and else keywords and their actions are indented. It’s very important to get this right!
  • 39. Run Sample Script… • Load “if_else_statement.py” into IDLE and hit F5 to run it.
  • 40. If-elif-else Statement • The if-elif-else statement allows us to pick one of several possible actions by chaining two or more if statements together. health = 24 if health <= 0: print "You're dead!" elif health < 25: print "You're alive - but badly wounded!" else: print "You're alive!"
  • 41. Run Sample Script… • Load “if_elif_else_statement.py” into IDLE and hit F5 to run it.
  • 42. while Statement • The while statement allows us to continuously repeat an action until some condition is satisfied. numRocketsToFire = 3 rocketCount = 0 while rocketCount < numRocketsToFire: # Increase the rocket counter by one rocketCount = rocketCount + 1 print “Firing rocket #” + str( rocketCount ) • This while statement will continue to ‘loop’ and print out a “Firing rocket” message until the variable “rocketCount” reaches the current value of “numRocketsToFire”, which is 3.
  • 43. Run Sample Script… • Load “while_statement.py” into IDLE and hit F5 to run it.
  • 44. for Statement • The for statement allows us to repeat an action based on the iteration of a Sequenced List. weapons = [ “Pistol”, “Rifle”, “Grenade”, “Rocket Launcher” ] print “-- Weapon Inventory --” for x in weapons: print x • The for statement will loop once for every item in the list. • Note how we use the temporary variable ‘x’ to represent the current item being worked with.
  • 45. Run Sample Script… • Load “for_statement.py” into IDLE and hit F5 to run it.
  • 46. break Keyword • The break keyword can be used to escape from while and for loops early. numbers = [100, 25, 125, 50, 150, 75, 175] for x in numbers: print x # As soon as we find 50 - stop the search! if x == 50: print "Found It!" break; • Instead of examining every list entry in “numbers”, The for loop above will be terminated as soon as the value 50 is found.
  • 47. Run Sample Script… • Load “for_break_statement.py” into IDLE and hit F5 to run it.
  • 48. continue Keyword • The continue keyword can be used to short-circuit or bypass parts of a while or for loop. numbers = [100, 25, 125, 50, 150, 75, 175] for x in numbers: # Skip all triple digit numbers if x >= 100: continue; print x • The for loop above only wants to print double digit numbers. It will simply continue on to the next iteration of the for loop if x is found to be a triple digit number.
  • 49. Run Sample Script… • Load “for_continue_statement.py” into IDLE and hit F5 to run it.
  • 50. Functions • A function allows several Python statements to be grouped together so they can be called or executed repeatedly from somewhere else in the script. • We use the def keyword to define a new function.
  • 51. Defining functions • Below, we define a new function called “printGameOver”, which simply prints out, “Game Over!”. def printGameOver(): print “Game Over!” • Again, note how indenting is used to denote the function’s body and how a semi-colon is used to terminate the function’s definition.
  • 52. Run Sample Script… • Load “function.py” into IDLE and hit F5 to run it.
  • 53. Function arguments • Often functions are required to perform some task based on information passed in by the user. • These bits of Information are passed in using function arguments. • Function arguments are defined within the parentheses “()”, which are placed at the end of the function’s name.
  • 54. Function arguments • Our new version of printGameOver, can now print out customizable, “Game Over!”, messages by using our new argument called “playersName”. def printGameOver( playersName ): print “Game Over... ” + playersName + “!” • Now, when we call our function we can specify which player is being killed off.
  • 55. Run Sample Script… • Load “function_arguments.py” into IDLE and hit F5 to run it.
  • 56. Default Argument Values • Once you add arguments to your function, it will be illegal to call that function with out passing the required arguments. • The only way around this it is to specify a default argument value.
  • 57. Default Argument Values • Below, the argument called “playersName” has been assigned the default value of, “Guest”. def printGameOver( playersName=“Guest” ): print “Game Over... ” + playersName + “!” • If we call the function and pass nothing, the string value of “Guest” will be used automatically.
  • 58. Run Sample Script… • Load “default_argument_values.py” into IDLE and hit F5 to run it.
  • 59. Multiple Function arguments • If we want, we can define as many arguments as we like. def printGameOver( playersName, totalKills ): print “Game Over... ” + playersName + “!” print “Total Kills: ” + str( totalKills ) + “n” • Of course, we must make sure that we pass the arguments in the correct order or Python will get confused. printGameOver( "camper_boy", 15 ) # Correct! printGameOver( 12, "killaHurtz" ) # Syntax Error!
  • 60. Run Sample Script… • Load “multiple_arguments.py” into IDLE and hit F5 to run it.
  • 61. Keyword arguments • If you really want to change the order of how the arguments get passed, you can use keyword arguments. def printGameOver( playersName, totalKills ): print “Game Over... ” + playersName + “!” print “Total Kills: ” + str( totalKills ) + “n” printGameOver( totalKills=12, playersName=“killaHurtz” ) • Note how we use the argument’s name as a keyword when calling the function.
  • 62. Run Sample Script… • Load “keyword_arguments.py” into IDLE and hit F5 to run it.
  • 63. Function Return Values • A function can also output or return a value based on its work. • The function below calculates and returns the average of a list of numbers. def average( numberList ): numCount = 0 runningTotal = 0 for n in numberList: numCount = numCount + 1 runningTotal = runningTotal + n return runningTotal / numCount • Note how the list’s average is returned using the return keyword.
  • 64. Assigning the return value • Here’s how the return value of our average function would be used… myNumbers = [5.0, 7.0, 8.0, 2.0] theAverage = average( myNumbers ) print "The average of the list is " + str( theAverage ) + "." • Note how we assign the return value of average to our variable called “theAverage”.
  • 65. Run Sample Script… • Load “function_return_value.py” into IDLE and hit F5 to run it.
  • 66. Multiple Return Values • A function can also output more than one value during the return. • This version of average not only returns the average of the list passed in but it also returns a counter which tells us how many numbers were in the list that was averaged. def average( numberList ): numCount = 0 runningTotal = 0 for n in numberList: numCount = numCount + 1 runningTotal = runningTotal + n return runningTotal / numCount, numCount • Note how the return keyword now returns two values which are separated by a comma.
  • 67. Assigning the return values • Here’s how the multiple return value of our average function could be used… myNumbers = [5.0, 7.0, 8.0, 2.0] theAverage, numberCount = average( myNumbers ) print "The average of the list is " + str( theAverage ) + "." print "The list contained " + str( numberCount ) + " numbers.“ • Note how we assign the return values of average to our variables “theAverage” and “numberCount”.
  • 68. Run Sample Script… • Load “multiple_return_values.py” into IDLE and hit F5 to run it.
  • 69. Conclusion • This concludes your introduction to Python. • You now know enough of the basics to write useful Python scripts and to teach yourself some of the more advanced features of Python. • To learn more, consult the documentation that ships with Python or visit the online documentation.