Movatterモバイル変換


[0]ホーム

URL:


stn_tkiller, profile picture
Uploaded bystn_tkiller
2,478 views

Python - Introduction

This document provides an introduction and overview of the Python programming language. It discusses what Python is, why to learn a scripting language and why Python specifically. It covers how to install Python and how to edit Python code using IDLE. The rest of the document demonstrates various Python concepts like variables, data types, operators, flow control statements, functions and more through sample code examples. Each code example is accompanied by instructions to run the sample script in IDLE.

Embed presentation

By Kevin HarrisAn Introduction to Python
What is Python?• Python is a portable, interpreted, object-oriented scripting language created byGuido van Rossum.• Its development started at the NationalResearch Institute for Mathematics andComputer Science in the Netherlands , andcontinues under the ownership of thePython Software Foundation.• Even though its name is commonlyassociated with the snake, it is actuallynamed after the British comedy troupe,Monty Python’s Flying Circus.
Why learn a scripting language?• Easier to learn than more traditionalcompiled languages like C/C++• Allows concepts to be prototypedfaster• Ideal for administrative tasks whichcan benefit from automation• Typically cross platform
Why Python?So, why use Python over otherscripting languages?• Well tested and widely used• Great documentation• Strong community support• Widely Cross-platform• Open sourced• Can be freely used and distributed, evenfor commercial purposes.
How do I install Python?• Simple… download it fromwww.python.org and install it.• Most Linux distributions already comewith it, but it may need updating.• Current version, as of thispresentation, is 2.4.2 Click here todownload this version for Windows.
How do I edit Python?• IDLE is a free GUI based text editor whichships with Python.• You could just write your scripts withNotepad, but IDLE has many helpfulfeatures like keyword highlighting.• Click your “Start” button and Find “Python2.4” on your “All Programs” menu. Thenselect and run “IDLE (Python GUI)”.• You can also right-click on any pythonscript (.py) and select “Edit with IDLE” toopen it.
IDLE in Action
“Hello World!”• The “Hello World!” example is a traditionamongst programmers, so lets start there…• Run IDLE and type in the followingprint “Hello World!”• Save your work and hit F5 to run it.• The script simply prints the string, “HelloWorld!” to the console.
Run Sample Script…• Load “hello_world.py” into IDLE and hit F5to run it.• NOTE: Scripts can also be executed bysimply double-clicking them, Unfortunately,they often run too quickly to read the outputso you’ll need to force a pause. I like touse a function called raw_input to pausethe script before it closes the console. Thenext script “hello_world_with_pause.py”,demonstrates this little hack.
The print function• The print function simply outputs a string value toour script’s console.print “Hello World!”• It’s very useful for communicating with users oroutputting 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 toour scripts, which the Python interpreter willignore completely.• Each line for a comment must begin with thenumber 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 themprint “Hello World!’ # Syntax Error!
Triple Quotes• You can even use triple quotes, whichmake 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 andhit F5 to run it.
Strings and Control Characters• There are several control characters which allowus to modify or change the way character stringsget printed by the print function.• They’re composed of a backslash followed by acharacter. Here are a few of the more importantones:n : New linet : Tabs : Backslash' : Single Quote" : Double Quote
Run Sample Script…• Load “control_characters.py” intoIDLE and hit F5 to run it.
Variables• Like all programming languages, Python variablesare similar to variables in Algebra.• They act as place holders or symbolicrepresentations for a value, which may or may notchange over time.• Here are six of the most important variable typesin 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 youdo not have to specify the variable’s type touse it.• You can use a variable as a characterstring one moment and then overwrite itsvalue with a integer the next.• This makes it easier to learn and use thelanguage but being type-less opens thedoor to some hard to find bugs if you’re notcareful.• If you’re uncertain of a variable’s type, usethe type function to verify its type.
Rules for Naming Variables• You can use letters, digits, andunderscores 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 variablesafter any of Python’s reservedkeywords.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 hitF5 to run it.• NOTE: Be careful when using Pythonvariables for floating-point numbers (i.e.3.14) Floats have limited precision, whichchanges from platform to platform. Thisbasically means there is a limit on how bigor small the number can be. Run the scriptand note how "pi" gets chopped off androunded 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 afloat, but you want to use it like an integer do this:myFloat = 25.12myInt = 25print myInt + int( myFloat )• With out the explicit conversion, Python will automaticallyupgrade your addition to floating-point addition, which youmay not want especially if your intention was to drop thedecimal places.
Type Conversion• There is also a special constructor function calledstr that converts numerical types into strings.myInt = 25myString = "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 jointhe two strings together as one.
Run Sample Script…• Load “type_conversion.py” into IDLEand hit F5 to run it.
Arithmetic Operators• Arithmetic Operators allow us to performmathematical operations on two variables orvalues.• Each operator returns the result of the specifiedoperation.+ Addition- Subtraction* Multiplication/ Float Division** Exponentabs Absolute Value
Run Sample Script…• Load “arithmetic_operators.py” intoIDLE and hit F5 to run it.
Comparison Operators• Comparison Operators return a True orFalse value for the two variables or valuesbeing 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” intoIDLE and hit F5 to run it.
Boolean Operators• Python also supports three Boolean Operators,and, or, and not, which allow us to make use ofBoolean Logic in our scripts.• Below are the Truth Tables for and, or, and not.
Boolean OperatorsSuppose that… var1 = 10.• The and operator will return True if and only if bothcomparisons return True.print var1 == 10 and var1 < 5 (Prints False)• The or operator will return True if either of the comparisonsreturn True.print var1 == 20 or var1 > 5 (Prints True)• And the not operator simply negates or inverts thecomparison’s result.print not var1 == 10 (Prints False)
Run Sample Script…• Load “boolean_operators.py” intoIDLE and hit F5 to run it.
Special String Operators• It may seem odd but Python even supports a few operatorsfor 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! ” * 3Outputs “Bang! Bang! Bang! ” to the console.
Run Sample Script…• Load “string_operators.py” into IDLEand hit F5 to run it.
Flow Control• Flow Control allows a program orscript to alter its flow of executionbased on some condition or test.• The most important keywords forperforming Flow Control in Python areif, else, elif, for, and while.
If Statement• The most basic form of Flow Control is the ifstatement.# If the player’s health is less than or equal to 0 - killhim!if health <= 0:print “You’re dead!”• Note how the action to be taken by the ifstatement is indented or tabbed over. This is not astyle issue – it’s required.• Also, note how the if statement ends with a semi-colon.
Run Sample Script…• Load “if_statement.py” into IDLE andhit F5 to run it.
If-else Statement• The if-else statement allows us to pick one of twopossible actions instead of a all-or-nothing choice.health = 75if health <= 0:print “You're dead!”else:print “You're alive!”• Again, note how the if and else keywords and theiractions are indented. It’s very important to get thisright!
Run Sample Script…• Load “if_else_statement.py” into IDLEand hit F5 to run it.
If-elif-else Statement• The if-elif-else statement allows us to pick one ofseveral possible actions by chaining two or more ifstatements together.health = 24if 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” intoIDLE and hit F5 to run it.
while Statement• The while statement allows us to continuously repeat an action untilsome condition is satisfied.numRocketsToFire = 3rocketCount = 0while rocketCount < numRocketsToFire:# Increase the rocket counter by onerocketCount = rocketCount + 1print “Firing rocket #” + str( rocketCount )• This while statement will continue to ‘loop’ and print out a “Firingrocket” message until the variable “rocketCount” reaches thecurrent value of “numRocketsToFire”, which is 3.
Run Sample Script…• Load “while_statement.py” into IDLEand hit F5 to run it.
for Statement• The for statement allows us to repeat an action based on theiteration 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 thecurrent item being worked with.
Run Sample Script…• Load “for_statement.py” into IDLE andhit F5 to run it.
break Keyword• The break keyword can be used to escape from while and forloops 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 forloop above will be terminated as soon as the value 50 isfound.
Run Sample Script…• Load “for_break_statement.py” intoIDLE and hit F5 to run it.
continue Keyword• The continue keyword can be used to short-circuit or bypassparts of a while or for loop.numbers = [100, 25, 125, 50, 150, 75, 175]for x in numbers:# Skip all triple digit numbersif 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 loopif x is found to be a triple digit number.
Run Sample Script…• Load “for_continue_statement.py” intoIDLE and hit F5 to run it.
Functions• A function allows several Pythonstatements to be grouped together sothey can be called or executedrepeatedly from somewhere else inthe script.• We use the def keyword to define anew function.
Defining functions• Below, we define a new function called“printGameOver”, which simply prints out, “GameOver!”.def printGameOver():print “Game Over!”• Again, note how indenting is used to denote thefunction’s body and how a semi-colon is used toterminate the function’s definition.
Run Sample Script…• Load “function.py” into IDLE and hitF5 to run it.
Function arguments• Often functions are required toperform some task based oninformation passed in by the user.• These bits of Information are passedin using function arguments.• Function arguments are defined withinthe parentheses “()”, which are placedat the end of the function’s name.
Function arguments• Our new version of printGameOver, can now printout customizable, “Game Over!”, messages byusing our new argument called “playersName”.def printGameOver( playersName ):print “Game Over... ” + playersName + “!”• Now, when we call our function we can specifywhich player is being killed off.
Run Sample Script…• Load “function_arguments.py” intoIDLE and hit F5 to run it.
Default Argument Values• Once you add arguments to yourfunction, it will be illegal to call thatfunction with out passing the requiredarguments.• The only way around this it is tospecify 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, thestring value of “Guest” will be usedautomatically.
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 inthe correct order or Python will get confused.printGameOver( "camper_boy", 15 ) # Correct!printGameOver( 12, "killaHurtz" ) # Syntax Error!
Run Sample Script…• Load “multiple_arguments.py” intoIDLE and hit F5 to run it.
Keyword arguments• If you really want to change the order of how the argumentsget 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 whencalling the function.
Run Sample Script…• Load “keyword_arguments.py” intoIDLE and hit F5 to run it.
Function Return Values• A function can also output or return a value based on itswork.• The function below calculates and returns the average of alist of numbers.def average( numberList ):numCount = 0runningTotal = 0for n in numberList:numCount = numCount + 1runningTotal = runningTotal + nreturn runningTotal / numCount• Note how the list’s average is returned using the returnkeyword.
Assigning the return value• Here’s how the return value of our average function would beused…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 ourvariable called “theAverage”.
Run Sample Script…• Load “function_return_value.py” intoIDLE 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 listpassed in but it also returns a counter which tells us how manynumbers were in the list that was averaged.def average( numberList ):numCount = 0runningTotal = 0for n in numberList:numCount = numCount + 1runningTotal = runningTotal + nreturn runningTotal / numCount, numCount• Note how the return keyword now returns two values which areseparated by a comma.
Assigning the return values• Here’s how the multiple return value of our average functioncould 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 ourvariables “theAverage” and “numberCount”.
Run Sample Script…• Load “multiple_return_values.py” intoIDLE and hit F5 to run it.
Conclusion• This concludes your introduction toPython.• You now know enough of the basicsto write useful Python scripts and toteach yourself some of the moreadvanced features of Python.• To learn more, consult thedocumentation that ships with Pythonor visit the online documentation.

Recommended

PDF
Basic Concepts in Python
PPTX
Python basics
PPTX
Learn python – for beginners
PDF
Python Workshop
PPT
Python ppt
DOCX
PYTHON NOTES
byNi
 
PDF
Python Tutorial
PDF
Chapter 0 Python Overview (Python Programming Lecture)
PDF
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
PPTX
Python Tutorial for Beginner
PPT
Perl Modules
PPT
Python ppt
PPTX
Python programming introduction
PPTX
Python Basics
PPT
Introduction to Python
PDF
Python made easy
PPTX
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
PDF
Introduction to python programming
PPTX
Introduction to Python Programming
PPTX
Introduction to python
PDF
Python - the basics
PDF
Python tutorial
PDF
Get started python programming part 1
PPTX
Python Tutorial Part 2
PPT
Python Programming Language
 
PDF
Python programming
PDF
Python教程 / Python tutorial
 
PDF
Python - An Introduction
PPT
Copy Of Blood Quiz

More Related Content

PDF
Basic Concepts in Python
PPTX
Python basics
PPTX
Learn python – for beginners
PDF
Python Workshop
PPT
Python ppt
DOCX
PYTHON NOTES
byNi
 
PDF
Python Tutorial
Basic Concepts in Python
Python basics
Learn python – for beginners
Python Workshop
Python ppt
PYTHON NOTES
byNi
 
Python Tutorial

What's hot

PDF
Chapter 0 Python Overview (Python Programming Lecture)
PDF
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
PPTX
Python Tutorial for Beginner
PPT
Perl Modules
PPT
Python ppt
PPTX
Python programming introduction
PPTX
Python Basics
PPT
Introduction to Python
PDF
Python made easy
PPTX
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
PDF
Introduction to python programming
PPTX
Introduction to Python Programming
PPTX
Introduction to python
PDF
Python - the basics
PDF
Python tutorial
PDF
Get started python programming part 1
PPTX
Python Tutorial Part 2
PPT
Python Programming Language
 
PDF
Python programming
PDF
Python教程 / Python tutorial
 
Chapter 0 Python Overview (Python Programming Lecture)
Advanced Python Tutorial | Learn Advanced Python Concepts | Python Programmin...
Python Tutorial for Beginner
Perl Modules
Python ppt
Python programming introduction
Python Basics
Introduction to Python
Python made easy
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Introduction to python programming
Introduction to Python Programming
Introduction to python
Python - the basics
Python tutorial
Get started python programming part 1
Python Tutorial Part 2
Python Programming Language
 
Python programming
Python教程 / Python tutorial
 

Viewers also liked

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

Similar to Python - Introduction

PPTX
PYTHON PROGRAMMING.pptx
PPTX
Introduction to learn and Python Interpreter
PDF
PythonModule1.pdf school of engineering.
PPT
Introduction to Python Lesson One-Python Easy Learning
PPTX
Chapter1 python introduction syntax general
PPTX
Keep it Stupidly Simple Introduce Python
PPTX
Python Basics by Akanksha Bali
PPT
Python programming
PDF
Learnpython 151027174258-lva1-app6892
PPTX
unit1.pptx for python programming CSE department
PPTX
BASICS OF PYTHON usefull for the student who would like to learn on their own
PPT
Introduction to phython programming
PPTX
Python PPT - INTEL AI FOR YOUTH PROGRAM.
PPTX
Python ppt
PPTX
Python PPT.pptx
PPTX
Python knowledge ,......................
PDF
Notes1
 
PDF
web programming UNIT VIII python by Bhavsingh Maloth
PDF
Python workshop
PPTX
Python unit 2 is added. Has python related programming content
PYTHON PROGRAMMING.pptx
Introduction to learn and Python Interpreter
PythonModule1.pdf school of engineering.
Introduction to Python Lesson One-Python Easy Learning
Chapter1 python introduction syntax general
Keep it Stupidly Simple Introduce Python
Python Basics by Akanksha Bali
Python programming
Learnpython 151027174258-lva1-app6892
unit1.pptx for python programming CSE department
BASICS OF PYTHON usefull for the student who would like to learn on their own
Introduction to phython programming
Python PPT - INTEL AI FOR YOUTH PROGRAM.
Python ppt
Python PPT.pptx
Python knowledge ,......................
Notes1
 
web programming UNIT VIII python by Bhavsingh Maloth
Python workshop
Python unit 2 is added. Has python related programming content

Recently uploaded

PDF
Decoding the DNA: The Digital Networks Act, the Open Internet, and IP interco...
PDF
Security Forum Sessions from Houston 2025 Event
PDF
GPUS and How to Program Them by Manya Bansal
PDF
Six Shifts For 2026 (And The Next Six Years)
PDF
Data Virtualization in Action: Scaling APIs and Apps with FME
PDF
Access Control 2025: From Security Silo to Software-Defined Ecosystem
PPTX
cybercrime in Information security .pptx
PDF
Day 1 - Cloud Security Strategy and Planning ~ 2nd Sight Lab ~ Cloud Security...
PPTX
From Backup to Resilience: How MSPs Are Preparing for 2026
 
PPTX
AI in Cybersecurity: Digital Defense by Yasir Naveed Riaz
PPTX
Data Privacy and Protection: Safeguarding Information in a Connected World
PDF
Our Digital Tribe_ Cultivating Connection and Growth in Our Slack Community 🌿...
PDF
API-First Architecture in Financial Systems
PPTX
Chapter 3 Introduction to number system.pptx
PDF
Energy Storage Landscape Clean Energy Ministerial
PDF
Day 2 - Network Security ~ 2nd Sight Lab ~ Cloud Security Class ~ 2020
PDF
Internet_of_Things_IoT_for_Next_Generation_Smart_Systems_Utilizing.pdf
PPTX
DYNAMICALLY.pptx good for the teachers or students to do seminars and for tea...
PDF
Dev Dives: AI that builds with you - UiPath Autopilot for effortless RPA & AP...
PPTX
Cybersecurity Best Practices - Step by Step guidelines
Decoding the DNA: The Digital Networks Act, the Open Internet, and IP interco...
Security Forum Sessions from Houston 2025 Event
GPUS and How to Program Them by Manya Bansal
Six Shifts For 2026 (And The Next Six Years)
Data Virtualization in Action: Scaling APIs and Apps with FME
Access Control 2025: From Security Silo to Software-Defined Ecosystem
cybercrime in Information security .pptx
Day 1 - Cloud Security Strategy and Planning ~ 2nd Sight Lab ~ Cloud Security...
From Backup to Resilience: How MSPs Are Preparing for 2026
 
AI in Cybersecurity: Digital Defense by Yasir Naveed Riaz
Data Privacy and Protection: Safeguarding Information in a Connected World
Our Digital Tribe_ Cultivating Connection and Growth in Our Slack Community 🌿...
API-First Architecture in Financial Systems
Chapter 3 Introduction to number system.pptx
Energy Storage Landscape Clean Energy Ministerial
Day 2 - Network Security ~ 2nd Sight Lab ~ Cloud Security Class ~ 2020
Internet_of_Things_IoT_for_Next_Generation_Smart_Systems_Utilizing.pdf
DYNAMICALLY.pptx good for the teachers or students to do seminars and for tea...
Dev Dives: AI that builds with you - UiPath Autopilot for effortless RPA & AP...
Cybersecurity Best Practices - Step by Step guidelines

Python - Introduction

  • 1.
    By Kevin HarrisAnIntroduction to Python
  • 2.
    What is Python?•Python is a portable, interpreted, object-oriented scripting language created byGuido van Rossum.• Its development started at the NationalResearch Institute for Mathematics andComputer Science in the Netherlands , andcontinues under the ownership of thePython Software Foundation.• Even though its name is commonlyassociated with the snake, it is actuallynamed after the British comedy troupe,Monty Python’s Flying Circus.
  • 3.
    Why learn ascripting language?• Easier to learn than more traditionalcompiled languages like C/C++• Allows concepts to be prototypedfaster• Ideal for administrative tasks whichcan benefit from automation• Typically cross platform
  • 4.
    Why Python?So, whyuse Python over otherscripting languages?• Well tested and widely used• Great documentation• Strong community support• Widely Cross-platform• Open sourced• Can be freely used and distributed, evenfor commercial purposes.
  • 5.
    How do Iinstall Python?• Simple… download it fromwww.python.org and install it.• Most Linux distributions already comewith it, but it may need updating.• Current version, as of thispresentation, is 2.4.2 Click here todownload this version for Windows.
  • 6.
    How do Iedit Python?• IDLE is a free GUI based text editor whichships with Python.• You could just write your scripts withNotepad, but IDLE has many helpfulfeatures like keyword highlighting.• Click your “Start” button and Find “Python2.4” on your “All Programs” menu. Thenselect and run “IDLE (Python GUI)”.• You can also right-click on any pythonscript (.py) and select “Edit with IDLE” toopen it.
  • 7.
  • 8.
    “Hello World!”• The“Hello World!” example is a traditionamongst programmers, so lets start there…• Run IDLE and type in the followingprint “Hello World!”• Save your work and hit F5 to run it.• The script simply prints the string, “HelloWorld!” to the console.
  • 9.
    Run Sample Script…•Load “hello_world.py” into IDLE and hit F5to run it.• NOTE: Scripts can also be executed bysimply double-clicking them, Unfortunately,they often run too quickly to read the outputso you’ll need to force a pause. I like touse a function called raw_input to pausethe script before it closes the console. Thenext script “hello_world_with_pause.py”,demonstrates this little hack.
  • 10.
    The print function•The print function simply outputs a string value toour script’s console.print “Hello World!”• It’s very useful for communicating with users oroutputting 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• Commentsallow us to add useful information toour scripts, which the Python interpreter willignore completely.• Each line for a comment must begin with thenumber sign ‘#’.# This is a programming tradition…print “Hello World!”• Do yourself a favor and use them!
  • 12.
    Quoting Strings• Characterstrings 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 themprint “Hello World!’ # Syntax Error!
  • 13.
    Triple Quotes• Youcan even use triple quotes, whichmake 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 andhit F5 to run it.
  • 15.
    Strings and ControlCharacters• There are several control characters which allowus to modify or change the way character stringsget printed by the print function.• They’re composed of a backslash followed by acharacter. Here are a few of the more importantones:n : New linet : Tabs : Backslash' : Single Quote" : Double Quote
  • 16.
    Run Sample Script…•Load “control_characters.py” intoIDLE and hit F5 to run it.
  • 17.
    Variables• Like allprogramming languages, Python variablesare similar to variables in Algebra.• They act as place holders or symbolicrepresentations for a value, which may or may notchange over time.• Here are six of the most important variable typesin 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• Eventhough it supports variable types,Python is actually type-less, meaning youdo not have to specify the variable’s type touse it.• You can use a variable as a characterstring one moment and then overwrite itsvalue with a integer the next.• This makes it easier to learn and use thelanguage but being type-less opens thedoor to some hard to find bugs if you’re notcareful.• If you’re uncertain of a variable’s type, usethe type function to verify its type.
  • 19.
    Rules for NamingVariables• You can use letters, digits, andunderscores 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 NamingVariables• Also, you can’t name your variablesafter any of Python’s reservedkeywords.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 hitF5 to run it.• NOTE: Be careful when using Pythonvariables for floating-point numbers (i.e.3.14) Floats have limited precision, whichchanges from platform to platform. Thisbasically means there is a limit on how bigor small the number can be. Run the scriptand note how "pi" gets chopped off androunded 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• Thespecial 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 afloat, but you want to use it like an integer do this:myFloat = 25.12myInt = 25print myInt + int( myFloat )• With out the explicit conversion, Python will automaticallyupgrade your addition to floating-point addition, which youmay not want especially if your intention was to drop thedecimal places.
  • 24.
    Type Conversion• Thereis also a special constructor function calledstr that converts numerical types into strings.myInt = 25myString = "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 jointhe two strings together as one.
  • 25.
    Run Sample Script…•Load “type_conversion.py” into IDLEand hit F5 to run it.
  • 26.
    Arithmetic Operators• ArithmeticOperators allow us to performmathematical operations on two variables orvalues.• Each operator returns the result of the specifiedoperation.+ Addition- Subtraction* Multiplication/ Float Division** Exponentabs Absolute Value
  • 27.
    Run Sample Script…•Load “arithmetic_operators.py” intoIDLE and hit F5 to run it.
  • 28.
    Comparison Operators• ComparisonOperators return a True orFalse value for the two variables or valuesbeing 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” intoIDLE and hit F5 to run it.
  • 30.
    Boolean Operators• Pythonalso supports three Boolean Operators,and, or, and not, which allow us to make use ofBoolean Logic in our scripts.• Below are the Truth Tables for and, or, and not.
  • 31.
    Boolean OperatorsSuppose that…var1 = 10.• The and operator will return True if and only if bothcomparisons return True.print var1 == 10 and var1 < 5 (Prints False)• The or operator will return True if either of the comparisonsreturn True.print var1 == 20 or var1 > 5 (Prints True)• And the not operator simply negates or inverts thecomparison’s result.print not var1 == 10 (Prints False)
  • 32.
    Run Sample Script…•Load “boolean_operators.py” intoIDLE and hit F5 to run it.
  • 33.
    Special String Operators•It may seem odd but Python even supports a few operatorsfor 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! ” * 3Outputs “Bang! Bang! Bang! ” to the console.
  • 34.
    Run Sample Script…•Load “string_operators.py” into IDLEand hit F5 to run it.
  • 35.
    Flow Control• FlowControl allows a program orscript to alter its flow of executionbased on some condition or test.• The most important keywords forperforming Flow Control in Python areif, else, elif, for, and while.
  • 36.
    If Statement• Themost basic form of Flow Control is the ifstatement.# If the player’s health is less than or equal to 0 - killhim!if health <= 0:print “You’re dead!”• Note how the action to be taken by the ifstatement is indented or tabbed over. This is not astyle 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 andhit F5 to run it.
  • 38.
    If-else Statement• Theif-else statement allows us to pick one of twopossible actions instead of a all-or-nothing choice.health = 75if health <= 0:print “You're dead!”else:print “You're alive!”• Again, note how the if and else keywords and theiractions are indented. It’s very important to get thisright!
  • 39.
    Run Sample Script…•Load “if_else_statement.py” into IDLEand hit F5 to run it.
  • 40.
    If-elif-else Statement• Theif-elif-else statement allows us to pick one ofseveral possible actions by chaining two or more ifstatements together.health = 24if 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” intoIDLE and hit F5 to run it.
  • 42.
    while Statement• Thewhile statement allows us to continuously repeat an action untilsome condition is satisfied.numRocketsToFire = 3rocketCount = 0while rocketCount < numRocketsToFire:# Increase the rocket counter by onerocketCount = rocketCount + 1print “Firing rocket #” + str( rocketCount )• This while statement will continue to ‘loop’ and print out a “Firingrocket” message until the variable “rocketCount” reaches thecurrent value of “numRocketsToFire”, which is 3.
  • 43.
    Run Sample Script…•Load “while_statement.py” into IDLEand hit F5 to run it.
  • 44.
    for Statement• Thefor statement allows us to repeat an action based on theiteration 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 thecurrent item being worked with.
  • 45.
    Run Sample Script…•Load “for_statement.py” into IDLE andhit F5 to run it.
  • 46.
    break Keyword• Thebreak keyword can be used to escape from while and forloops 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 forloop above will be terminated as soon as the value 50 isfound.
  • 47.
    Run Sample Script…•Load “for_break_statement.py” intoIDLE and hit F5 to run it.
  • 48.
    continue Keyword• Thecontinue keyword can be used to short-circuit or bypassparts of a while or for loop.numbers = [100, 25, 125, 50, 150, 75, 175]for x in numbers:# Skip all triple digit numbersif 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 loopif x is found to be a triple digit number.
  • 49.
    Run Sample Script…•Load “for_continue_statement.py” intoIDLE and hit F5 to run it.
  • 50.
    Functions• A functionallows several Pythonstatements to be grouped together sothey can be called or executedrepeatedly from somewhere else inthe script.• We use the def keyword to define anew function.
  • 51.
    Defining functions• Below,we define a new function called“printGameOver”, which simply prints out, “GameOver!”.def printGameOver():print “Game Over!”• Again, note how indenting is used to denote thefunction’s body and how a semi-colon is used toterminate the function’s definition.
  • 52.
    Run Sample Script…•Load “function.py” into IDLE and hitF5 to run it.
  • 53.
    Function arguments• Oftenfunctions are required toperform some task based oninformation passed in by the user.• These bits of Information are passedin using function arguments.• Function arguments are defined withinthe parentheses “()”, which are placedat the end of the function’s name.
  • 54.
    Function arguments• Ournew version of printGameOver, can now printout customizable, “Game Over!”, messages byusing our new argument called “playersName”.def printGameOver( playersName ):print “Game Over... ” + playersName + “!”• Now, when we call our function we can specifywhich player is being killed off.
  • 55.
    Run Sample Script…•Load “function_arguments.py” intoIDLE and hit F5 to run it.
  • 56.
    Default Argument Values•Once you add arguments to yourfunction, it will be illegal to call thatfunction with out passing the requiredarguments.• The only way around this it is tospecify 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, thestring value of “Guest” will be usedautomatically.
  • 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 inthe 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” intoIDLE and hit F5 to run it.
  • 61.
    Keyword arguments• Ifyou really want to change the order of how the argumentsget 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 whencalling the function.
  • 62.
    Run Sample Script…•Load “keyword_arguments.py” intoIDLE and hit F5 to run it.
  • 63.
    Function Return Values•A function can also output or return a value based on itswork.• The function below calculates and returns the average of alist of numbers.def average( numberList ):numCount = 0runningTotal = 0for n in numberList:numCount = numCount + 1runningTotal = runningTotal + nreturn runningTotal / numCount• Note how the list’s average is returned using the returnkeyword.
  • 64.
    Assigning the returnvalue• Here’s how the return value of our average function would beused…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 ourvariable called “theAverage”.
  • 65.
    Run Sample Script…•Load “function_return_value.py” intoIDLE 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 listpassed in but it also returns a counter which tells us how manynumbers were in the list that was averaged.def average( numberList ):numCount = 0runningTotal = 0for n in numberList:numCount = numCount + 1runningTotal = runningTotal + nreturn runningTotal / numCount, numCount• Note how the return keyword now returns two values which areseparated by a comma.
  • 67.
    Assigning the returnvalues• Here’s how the multiple return value of our average functioncould 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 ourvariables “theAverage” and “numberCount”.
  • 68.
    Run Sample Script…•Load “multiple_return_values.py” intoIDLE and hit F5 to run it.
  • 69.
    Conclusion• This concludesyour introduction toPython.• You now know enough of the basicsto write useful Python scripts and toteach yourself some of the moreadvanced features of Python.• To learn more, consult thedocumentation that ships with Pythonor visit the online documentation.

[8]ページ先頭

©2009-2025 Movatter.jp