SlideShare une entreprise Scribd logo
1  sur  46
Télécharger pour lire hors ligne
Python 101
McBryde 101
Feb 22, 2013
Overview for Today
1. Setting up Python
2. Background on Python
3. Basics of Python
4. Data Structures in Python
5. Control Structures in Python
6. Functions in Python
Things you should do
Ask questions!
   If you are confused, there is a 80% chance that
someone else is even more confused.
Participate!
   We're all friends here. Tell us if we're going too slowly.
Tell us if we're boring. Tell us if have an idea for
something.
Follow along!
   Open up Python and try stuff!
Setting up Python
Download & Install Python
http://www.python.org/download/

Run python
Windows: python.exe
Mac/Linux: python
Background on Python
What is Python?
● A language

● An interpreter

● A reference to a British sketch comedy:
  "Monty Python's Flying Circus"
   (The documentation is full of jokes referencing the
show)
Why Python?
● Traditional languages (C++, C, Java)
  evolved for large-scale programming

● Scripting language (Perl, Python) evolved
  for simplicity and flexibility
The Python Language
● Free!
● Elegant and Powerful!
● Cross-Platform!
● Tons of useful modules!
● Chock full of technical buzzwords!
  ○ Object-oriented, dynamic-typing
The "Zen" of Python
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
...
Readability Counts
... (It's actually a lot longer)
The Basics
Printing in Python
>>> print "Hello World."
Hello World.


Meanwhile, in Java land:
public class MyFirstProgram {
   public static void main(String[] args) {
     System.out.println("Hello World");
   }
}
Input in Python
>>> input("Tell me something: ")
Tell me something:


Type something in and press enter
Comments in Python
>>> # This is a comment
...


The following will NOT work:
/*
Multiline comment in Java
*/
// Single line comment in Java
Scripts in Python
1. In your IDE/Text Editor, write
   # My first program!
   print "Hello", "World"
2. Save the file as helloworld.py
3. From the terminal,
   > python helloworld.py
   Hello World.
Congratulations!
You are now all Python programmers.
Basic Data
Values in Python
-5           #   Integer type
23.1         #   Float type
"Some words" #   String type
True         #   Boolean type

Variables in Python
age                =   23
miles_from_home    =   301.36
name               =   "Cory Bart"
has_dog            =   False
Operators
Numerics    Strings
1 + 4       "Hello " + "World"
2 - 3       "Repeat" * 5
4 * 1
10.0 / 2    Comparisons
10.5 // 2   10 >= 5
2 ** 4      3 < 80
22 % 12     5 == 10
            3 != 3
Operators continued...
Boolean logic
True and False
True or True
not True
Exercise
given a string myString and a
numbernumRepetitions, return myString
multiplied numRepetitions times.

multiplyString('a', 4) → 'aaaa'
multiplyString('Hello', 2) → 'HelloHello'
multiplyString('Python', 3) →
'PythonPythonPython'
Control and Data Structures
If statements
if has_dogs:
   print "Has dogs"
elif age >= 25:
   print "Can rent a car"
elif name == "Ellie" or name == "Becky"
   print "Is awesome!"
else:
   print "Not a great fellow"

*Note the white-space!*
Defining functions
def add(first, second):
  return first + second

value = add(10, 5)
Exercise
Write a function that can compute tips for a
meal, given the price and how generous the
user is.

# price: float
# generous: string, either "stingy"
#           or "generous"
# returns a float indicating tip
def calculate_tip(price, generosity):
   ...
Multiple returns!
def flip_coordinates(pos):
  x, y = pos
  return -x, -y

x, y = flip_coordinates((5, -5))
Sequences
Lists are Mutable and Ordered
a_list       = [1, 3, 2]
Tuples are Immutable and Ordered
a_tuple = (1, 2, 3)
Sets are Mutable, Unordered, and Unique
a_set        = set([1, 2, 3])
Dictionaries are Key-Value pairs
a_dictionary         = {'A': 1, 'B': 2, 'C': 3}
Strings are immutable sequences of one-character Strings!
a_string = "Also a sequence!"
Working with a list
colors = ['red', 'blue', 'yellow', 'purple']
Add to a list
colors.append('green') or colors.insert
(index)
Remove from a list
colors.pop() or colors.remove(index)
Sets are a little different
>>> set([1, 1, 2,    -2, 3, 3, 4])
set([1, 2, -2, 3,    4])
>>> set([1, 2, -2,   3, 4]).add(4)
set([1, 2, -2, 3,    4])
>>> set([1, 2, -2,   3, 4]).add(5)
set([1, 2, -2, 3,    4, 5])
Tuples are a little different
>>> my_tuple = (1, 2, 3, 4)
>>> my_tuple.add(5)
NOPE!

Tuples will be more awesome when we get to
functions.
Dictionaries are wonderful
>>> scores = {"Cory": 32,
              "Ellie": 100,
              "Becky": 78}

>>> print scores["Cory"]
32
Working with sequences
Get an element of a sequence:
"Puzzle"[2]
Get the length of a sequence
len(set([1, 2, 3, 4, 5, 6]))
Is something in a sequence?
5 in (1, 2, 3, 4, 5)
Get a sublist from a list
['red', 'blue', 'yellow', 'green'][1:2]
There are many built-in functions for sequences
sum((1, 2, 3, 4))
min((5, 10, 15))
Strings have a ton of methods!
"1, 2, 3, 4".split(",")

",".join([1,2,3,4])

"   whitespace   ".strip()

"I am 22".replace("am", "was")

"HeLlO wOrLd".swapcase()
Converting between types
str(5)                ->   "5"
int("10")             ->   10
float("10.0")         ->   10.0
bool(None)            ->   False
list((1, 2, 3, 4))    ->   [1,2,3,4]
tuple([1, 2, 4, 8])   ->   (1,2,4,8)
Truthiness in Python
        True                  False
True                  False
5                     0
-5                    []
[1, 2, 3]             ""
"Hello world"         None

         items_left = [1, 2, 3]
         while items_left:
           print items_left.pop()
Looping
The for-each loop is best!
                                      List
for item in [1, 2, 3]:                Set
  print item                         Tuple
                                    String
                                 File handler
You can also use a while loop.

while True:
  # do something
xrange
for value in xrange(5):
   print value

0
1
2
3
4
Iterating with indices
for index, item in enumerate("ABCDE"):
   print index, item

0   A
1   B
2   C
3   D
4   E
Iterating over Dictionary
a_dictionary = {'a':1,'b':2}
for key, value in a_dictionary.items():
   print key, value
Exercise
Write a program that will "translate" a sentence
into Pyglatin:

"We only speak Pyglatin in Pyrome"
->
"Eway onlyay peaksay Yglatinpay inay yromeay"
List comprehensions
You can make a list by sticking a for loop inside!

[value*2 for value in range(10)]

[int(number) for number in "123456789"]
File I/O
file = open('word_lists.txt', 'r')
for line in file:
  print line

file = open('numbers.txt', 'w')
for number in range(100):
  file.write(number)
Importing
import random
random.choice(("Heads", "Tails"))

import sys
print sys.args

import math
print math.sqrt(36)
Command line arguments
>python file.py this is a test

Inside of file.py
import sys
print sys.args

Outputs
['this', 'is', 'a', 'test']
What should I do next?
The Python Challenge
  http://www.pythonchallenge.com/

Online Books:
  http://tinyurl.com/interactivepython
Feedback
● Facebook - http://tinyurl.com/letscode


● Would you be interested in this formulating
  into a meetup group?
● How often?
● What would you like to learn next?
● Does the location matter?
● Any other feedback?
● How large/small class size would you
  prefer?

Contenu connexe

Tendances

Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Edureka!
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaEdureka!
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaEdureka!
 
Learn REST API with Python
Learn REST API with PythonLearn REST API with Python
Learn REST API with PythonLarry Cai
 
Network programming Using Python
Network programming Using PythonNetwork programming Using Python
Network programming Using PythonKarim Sonbol
 
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...Edureka!
 
Python for Data Science with Anaconda
Python for Data Science with AnacondaPython for Data Science with Anaconda
Python for Data Science with AnacondaTravis Oliphant
 
What it takes to run Hadoop at Scale: Yahoo! Perspectives
What it takes to run Hadoop at Scale: Yahoo! PerspectivesWhat it takes to run Hadoop at Scale: Yahoo! Perspectives
What it takes to run Hadoop at Scale: Yahoo! PerspectivesDataWorks Summit
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaEdureka!
 

Tendances (20)

Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
 
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
Python Projects For Beginners | Python Projects Examples | Python Tutorial | ...
 
Flask
FlaskFlask
Flask
 
Pydata-Python tools for webscraping
Pydata-Python tools for webscrapingPydata-Python tools for webscraping
Pydata-Python tools for webscraping
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Python Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | EdurekaPython Class | Python Programming | Python Tutorial | Edureka
Python Class | Python Programming | Python Tutorial | Edureka
 
Python Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math modulePython Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math module
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Python
PythonPython
Python
 
Overloading vs Overriding.pptx
Overloading vs Overriding.pptxOverloading vs Overriding.pptx
Overloading vs Overriding.pptx
 
Python Programming Tutorial | Edureka
Python Programming Tutorial | EdurekaPython Programming Tutorial | Edureka
Python Programming Tutorial | Edureka
 
Learn REST API with Python
Learn REST API with PythonLearn REST API with Python
Learn REST API with Python
 
Network programming Using Python
Network programming Using PythonNetwork programming Using Python
Network programming Using Python
 
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 for Data Science with Anaconda
Python for Data Science with AnacondaPython for Data Science with Anaconda
Python for Data Science with Anaconda
 
What it takes to run Hadoop at Scale: Yahoo! Perspectives
What it takes to run Hadoop at Scale: Yahoo! PerspectivesWhat it takes to run Hadoop at Scale: Yahoo! Perspectives
What it takes to run Hadoop at Scale: Yahoo! Perspectives
 
Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
 
Intro to Jupyter Notebooks
Intro to Jupyter NotebooksIntro to Jupyter Notebooks
Intro to Jupyter Notebooks
 

En vedette

Why I Love Python
Why I Love PythonWhy I Love Python
Why I Love Pythondidip
 
Python data structures - best in class for data analysis
Python data structures -   best in class for data analysisPython data structures -   best in class for data analysis
Python data structures - best in class for data analysisRajesh M
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
Seminar report On Python
Seminar report On PythonSeminar report On Python
Seminar report On PythonShivam Gupta
 
Lecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data StructuresLecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data StructuresHaitham El-Ghareeb
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in PythonJuan-Manuel Gimeno
 
Python PPT
Python PPTPython PPT
Python PPTEdureka!
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 

En vedette (11)

Why I Love Python
Why I Love PythonWhy I Love Python
Why I Love Python
 
Python data structures - best in class for data analysis
Python data structures -   best in class for data analysisPython data structures -   best in class for data analysis
Python data structures - best in class for data analysis
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Seminar report On Python
Seminar report On PythonSeminar report On Python
Seminar report On Python
 
Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
Lecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data StructuresLecture 9 - DSA - Python Data Structures
Lecture 9 - DSA - Python Data Structures
 
Object-oriented Programming in Python
Object-oriented Programming in PythonObject-oriented Programming in Python
Object-oriented Programming in Python
 
Python PPT
Python PPTPython PPT
Python PPT
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Similaire à Python 101 1

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Simplilearn
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
python chapter 1
python chapter 1python chapter 1
python chapter 1Raghu nath
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2Raghu nath
 
Session 02 python basics
Session 02 python basicsSession 02 python basics
Session 02 python basicsSara-Jayne Terp
 
Session 02 python basics
Session 02 python basicsSession 02 python basics
Session 02 python basicsbodaceacat
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computingGo Asgard
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanWei-Yuan Chang
 
Python in 90mins
Python in 90minsPython in 90mins
Python in 90minsLarry Cai
 
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...amit kuraria
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonAhmed Salama
 
Chapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptxChapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptxSovannDoeur
 
From 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideFrom 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideDinesh Manajipet
 

Similaire à Python 101 1 (20)

Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...Python Interview Questions | Python Interview Questions And Answers | Python ...
Python Interview Questions | Python Interview Questions And Answers | Python ...
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python slide
Python slidePython slide
Python slide
 
python chapter 1
python chapter 1python chapter 1
python chapter 1
 
Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
Session 02 python basics
Session 02 python basicsSession 02 python basics
Session 02 python basics
 
Session 02 python basics
Session 02 python basicsSession 02 python basics
Session 02 python basics
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
 
Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computing
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
Python Basic
Python BasicPython Basic
Python Basic
 
Python in 90mins
Python in 90minsPython in 90mins
Python in 90mins
 
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
Write better python code with these 10 tricks | by yong cui, ph.d. | aug, 202...
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Chapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptxChapter 2 Python Language Basics, IPython.pptx
Chapter 2 Python Language Basics, IPython.pptx
 
From 0 to mine sweeper in pyside
From 0 to mine sweeper in pysideFrom 0 to mine sweeper in pyside
From 0 to mine sweeper in pyside
 

Plus de Iccha Sethi

Resilient Event Driven Systems With Kafka
Resilient Event Driven Systems With KafkaResilient Event Driven Systems With Kafka
Resilient Event Driven Systems With KafkaIccha Sethi
 
Redis High availability and fault tolerance in a multitenant environment
Redis High availability and fault tolerance in a multitenant environmentRedis High availability and fault tolerance in a multitenant environment
Redis High availability and fault tolerance in a multitenant environmentIccha Sethi
 
So youwanttobeopenstackcontributor
So youwanttobeopenstackcontributorSo youwanttobeopenstackcontributor
So youwanttobeopenstackcontributorIccha Sethi
 
OpenStack Workshop - WECode Harvard Conference
OpenStack Workshop - WECode Harvard ConferenceOpenStack Workshop - WECode Harvard Conference
OpenStack Workshop - WECode Harvard ConferenceIccha Sethi
 
Grace Hopper Conference Opensource Day - OpenStack workshop
Grace Hopper Conference Opensource Day - OpenStack workshopGrace Hopper Conference Opensource Day - OpenStack workshop
Grace Hopper Conference Opensource Day - OpenStack workshopIccha Sethi
 
Lets code classes_python
Lets code classes_pythonLets code classes_python
Lets code classes_pythonIccha Sethi
 
Clinician Decision Support Dashboard
Clinician Decision Support DashboardClinician Decision Support Dashboard
Clinician Decision Support DashboardIccha Sethi
 

Plus de Iccha Sethi (8)

Resilient Event Driven Systems With Kafka
Resilient Event Driven Systems With KafkaResilient Event Driven Systems With Kafka
Resilient Event Driven Systems With Kafka
 
Redis High availability and fault tolerance in a multitenant environment
Redis High availability and fault tolerance in a multitenant environmentRedis High availability and fault tolerance in a multitenant environment
Redis High availability and fault tolerance in a multitenant environment
 
So youwanttobeopenstackcontributor
So youwanttobeopenstackcontributorSo youwanttobeopenstackcontributor
So youwanttobeopenstackcontributor
 
OpenStack Workshop - WECode Harvard Conference
OpenStack Workshop - WECode Harvard ConferenceOpenStack Workshop - WECode Harvard Conference
OpenStack Workshop - WECode Harvard Conference
 
Grace Hopper Conference Opensource Day - OpenStack workshop
Grace Hopper Conference Opensource Day - OpenStack workshopGrace Hopper Conference Opensource Day - OpenStack workshop
Grace Hopper Conference Opensource Day - OpenStack workshop
 
Lets code classes_python
Lets code classes_pythonLets code classes_python
Lets code classes_python
 
Osrs
OsrsOsrs
Osrs
 
Clinician Decision Support Dashboard
Clinician Decision Support DashboardClinician Decision Support Dashboard
Clinician Decision Support Dashboard
 

Python 101 1

  • 2. Overview for Today 1. Setting up Python 2. Background on Python 3. Basics of Python 4. Data Structures in Python 5. Control Structures in Python 6. Functions in Python
  • 3. Things you should do Ask questions! If you are confused, there is a 80% chance that someone else is even more confused. Participate! We're all friends here. Tell us if we're going too slowly. Tell us if we're boring. Tell us if have an idea for something. Follow along! Open up Python and try stuff!
  • 5. Download & Install Python http://www.python.org/download/ Run python Windows: python.exe Mac/Linux: python
  • 7. What is Python? ● A language ● An interpreter ● A reference to a British sketch comedy: "Monty Python's Flying Circus" (The documentation is full of jokes referencing the show)
  • 8. Why Python? ● Traditional languages (C++, C, Java) evolved for large-scale programming ● Scripting language (Perl, Python) evolved for simplicity and flexibility
  • 9. The Python Language ● Free! ● Elegant and Powerful! ● Cross-Platform! ● Tons of useful modules! ● Chock full of technical buzzwords! ○ Object-oriented, dynamic-typing
  • 10. The "Zen" of Python Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. ... Readability Counts ... (It's actually a lot longer)
  • 12. Printing in Python >>> print "Hello World." Hello World. Meanwhile, in Java land: public class MyFirstProgram { public static void main(String[] args) { System.out.println("Hello World"); } }
  • 13. Input in Python >>> input("Tell me something: ") Tell me something: Type something in and press enter
  • 14. Comments in Python >>> # This is a comment ... The following will NOT work: /* Multiline comment in Java */ // Single line comment in Java
  • 15. Scripts in Python 1. In your IDE/Text Editor, write # My first program! print "Hello", "World" 2. Save the file as helloworld.py 3. From the terminal, > python helloworld.py Hello World.
  • 16. Congratulations! You are now all Python programmers.
  • 18. Values in Python -5 # Integer type 23.1 # Float type "Some words" # String type True # Boolean type Variables in Python age = 23 miles_from_home = 301.36 name = "Cory Bart" has_dog = False
  • 19. Operators Numerics Strings 1 + 4 "Hello " + "World" 2 - 3 "Repeat" * 5 4 * 1 10.0 / 2 Comparisons 10.5 // 2 10 >= 5 2 ** 4 3 < 80 22 % 12 5 == 10 3 != 3
  • 20. Operators continued... Boolean logic True and False True or True not True
  • 21. Exercise given a string myString and a numbernumRepetitions, return myString multiplied numRepetitions times. multiplyString('a', 4) → 'aaaa' multiplyString('Hello', 2) → 'HelloHello' multiplyString('Python', 3) → 'PythonPythonPython'
  • 22. Control and Data Structures
  • 23. If statements if has_dogs: print "Has dogs" elif age >= 25: print "Can rent a car" elif name == "Ellie" or name == "Becky" print "Is awesome!" else: print "Not a great fellow" *Note the white-space!*
  • 24. Defining functions def add(first, second): return first + second value = add(10, 5)
  • 25. Exercise Write a function that can compute tips for a meal, given the price and how generous the user is. # price: float # generous: string, either "stingy" # or "generous" # returns a float indicating tip def calculate_tip(price, generosity): ...
  • 26. Multiple returns! def flip_coordinates(pos): x, y = pos return -x, -y x, y = flip_coordinates((5, -5))
  • 27. Sequences Lists are Mutable and Ordered a_list = [1, 3, 2] Tuples are Immutable and Ordered a_tuple = (1, 2, 3) Sets are Mutable, Unordered, and Unique a_set = set([1, 2, 3]) Dictionaries are Key-Value pairs a_dictionary = {'A': 1, 'B': 2, 'C': 3} Strings are immutable sequences of one-character Strings! a_string = "Also a sequence!"
  • 28. Working with a list colors = ['red', 'blue', 'yellow', 'purple'] Add to a list colors.append('green') or colors.insert (index) Remove from a list colors.pop() or colors.remove(index)
  • 29. Sets are a little different >>> set([1, 1, 2, -2, 3, 3, 4]) set([1, 2, -2, 3, 4]) >>> set([1, 2, -2, 3, 4]).add(4) set([1, 2, -2, 3, 4]) >>> set([1, 2, -2, 3, 4]).add(5) set([1, 2, -2, 3, 4, 5])
  • 30. Tuples are a little different >>> my_tuple = (1, 2, 3, 4) >>> my_tuple.add(5) NOPE! Tuples will be more awesome when we get to functions.
  • 31. Dictionaries are wonderful >>> scores = {"Cory": 32, "Ellie": 100, "Becky": 78} >>> print scores["Cory"] 32
  • 32. Working with sequences Get an element of a sequence: "Puzzle"[2] Get the length of a sequence len(set([1, 2, 3, 4, 5, 6])) Is something in a sequence? 5 in (1, 2, 3, 4, 5) Get a sublist from a list ['red', 'blue', 'yellow', 'green'][1:2] There are many built-in functions for sequences sum((1, 2, 3, 4)) min((5, 10, 15))
  • 33. Strings have a ton of methods! "1, 2, 3, 4".split(",") ",".join([1,2,3,4]) " whitespace ".strip() "I am 22".replace("am", "was") "HeLlO wOrLd".swapcase()
  • 34. Converting between types str(5) -> "5" int("10") -> 10 float("10.0") -> 10.0 bool(None) -> False list((1, 2, 3, 4)) -> [1,2,3,4] tuple([1, 2, 4, 8]) -> (1,2,4,8)
  • 35. Truthiness in Python True False True False 5 0 -5 [] [1, 2, 3] "" "Hello world" None items_left = [1, 2, 3] while items_left: print items_left.pop()
  • 36. Looping The for-each loop is best! List for item in [1, 2, 3]: Set print item Tuple String File handler You can also use a while loop. while True: # do something
  • 37. xrange for value in xrange(5): print value 0 1 2 3 4
  • 38. Iterating with indices for index, item in enumerate("ABCDE"): print index, item 0 A 1 B 2 C 3 D 4 E
  • 39. Iterating over Dictionary a_dictionary = {'a':1,'b':2} for key, value in a_dictionary.items(): print key, value
  • 40. Exercise Write a program that will "translate" a sentence into Pyglatin: "We only speak Pyglatin in Pyrome" -> "Eway onlyay peaksay Yglatinpay inay yromeay"
  • 41. List comprehensions You can make a list by sticking a for loop inside! [value*2 for value in range(10)] [int(number) for number in "123456789"]
  • 42. File I/O file = open('word_lists.txt', 'r') for line in file: print line file = open('numbers.txt', 'w') for number in range(100): file.write(number)
  • 43. Importing import random random.choice(("Heads", "Tails")) import sys print sys.args import math print math.sqrt(36)
  • 44. Command line arguments >python file.py this is a test Inside of file.py import sys print sys.args Outputs ['this', 'is', 'a', 'test']
  • 45. What should I do next? The Python Challenge http://www.pythonchallenge.com/ Online Books: http://tinyurl.com/interactivepython
  • 46. Feedback ● Facebook - http://tinyurl.com/letscode ● Would you be interested in this formulating into a meetup group? ● How often? ● What would you like to learn next? ● Does the location matter? ● Any other feedback? ● How large/small class size would you prefer?