SlideShare une entreprise Scribd logo
1  sur  78
Télécharger pour lire hors ligne
Python
BASICS
Introduction to Python programming, basic
concepts: formatting, naming conventions,
variables, etc.
#include <stdio.h>
int main()
{
printf("Hello, world!");
return 0;
}
3/10/2016 Python basics 2
print "Hello, world!"
3/10/2016 Python basics 3
# this will print "Hello, world!"
print "Hello, world!"
3/10/2016 Python basics 4
inline comment
Keywords
• and
• del
• from
• not
• while
• as
• elif
• global
• or
• with
• assert
• else
• if
• pass
• yield
• break
• except
• import
• print
• class
• exec
3/10/2016 Python basics 5
• in
• raise
• continue
• finally
• is
• return
• def
• for
• lambda
• try
Variables
3/10/2016 Python basics 6
language_name = "Python"
naming convention: joined_lower
this is a string
Variables
3/10/2016 Python basics 7
language_name = "Python"
version = '2.7.11'
introduced = 1991
is_awesome = True
Type Inference
3/10/2016 Python basics 8
language_name = "Python" # string
version = '2.7.11' # another string
introduced = 1991 # integer
is_awesome = True # boolean
actual type can be checked with type()
play_with_types.py
String
3/10/2016 Python basics 9
some_string = "I'm a string"
another_string = 'I'm a string, too'
String
3/10/2016 Python basics 10
some_string = "I'm a string"
another_string = 'I'm a string, too'
# SyntaxError: invalid syntax
String
3/10/2016 Python basics 11
another_string = 'I am a string, too'
another_strig = 'I'm a string, too'
escape sequence
String
3/10/2016 Python basics 12
long_string = """I am a long string.
I span over two lines."""
long_string = '''I am another long
string.
I span over three lines.
I am composed by three sentences.'''
If Statement
3/10/2016 Python basics 13
people = 20
cats = 30
if people < cats:
print "Too many cats! We are doomed!"
if people > cats:
print "Not many cats! We are safe!"
4 spaces
4 spaces
If Statement
3/10/2016 Python basics 14
people = 20
cats = 30
if people < cats:
print "Too many cats! We are doomed!"
elif people > cats:
print "Not many cats! We are safe!"
else:
print "We can't decide."
Comparators and Booleans
Operators
3/10/2016 Python basics 15
print 2 == 1
print 'string' == "string"
print not False
print 2==1 and True
print 2==1 or True
Comparators and Booleans
Operators
3/10/2016 Python basics 16
print 2 == 1 # False
print 'string' == "string" # True
print not False # True
print 2==1 and True # False
print 2==1 or True # True
Characters
3/10/2016 Python basics 17
for char in "hello":
print char
h
e
l
l
o
Characters
3/10/2016 Python basics 18
say_hello = "hello!"
print say_hello[1]
e
index
Characters
3/10/2016 Python basics 19
say_hello = "hello!"
print type(say_hello[1])
<type 'str'>
Combining Strings
3/10/2016 Python basics 20
language_name = "Python"
version = '2.7.11'
python_version = language_name + version
# python_version is Python2.7.11
print "my " + "name" # my name
concatenation
Combining Strings
3/10/2016 Python basics 21
language_name = "Python"
a_lot_of_python = language_name*3
# a_lot_of_python is PythonPythonPython
repetition
Building Complex Strings
3/10/2016 Python basics 22
a = 3
b = 5
# 3 times 5 is 15
print a, "times", b, "is", a*b
works with print, only
Building Complex Strings
3/10/2016 Python basics 23
a = 3
b = 5
# 3 times 5 is 15
result = a + " times " + b + " is " + a*b
Building Complex Strings
3/10/2016 Python basics 24
a = 3
b = 5
# 3 times 5 is 15
result = a + " times " + b + " is " + a*b
#TypeError: unsupported operand type(s)
Building Complex Strings
3/10/2016 Python basics 25
a = 3
b = 5
# 3 times 5 is 15
result = str(a) + " times " + str(b) + "
is " + str(a*b)
String Interpolation
3/10/2016 Python basics 26
a = 3
b = 5
# 3 times 5 is 15
result = "%d times %d is %d" %(a, b, a*b)
Specifiers
• %s, format strings
• %d, format numbers
• %r, raw representation
tuplespecifiers.py
String Interpolation
3/10/2016 Python basics 27
a = 3
b = 5
# 3 times 5 is 15
result = "{} times {} is {}".format(a, b,
a*b)
new way!
String Immutability
3/10/2016 Python basics 28
# hello
say_hello = "helko"
# ops…
say_hello[3] = "l"
String Immutability
3/10/2016 Python basics 29
# hello
say_hello = "helko"
# ops…
say_hello[3] = "l"
# TypeError
String Immutability
3/10/2016 Python basics 30
# hello
say_hello = "helko"
# ops…
say_hello = "hello"
Other operations with strings? Python docs
Getting Input
3/10/2016 Python basics 31
print "How old are you?"
age = raw_input() # age is a string
print "You are " + age + " years old"
Getting Input
3/10/2016 Python basics 32
print "How old are you?"
age = raw_input() # age is a string
print "You are " + age + " years old"
# I want "age" to be a number!
age = int(raw_input())
Getting Input
3/10/2016 Python basics 33
age = raw_input("How old are you? ")
print "You are " + age + " years old"
List
3/10/2016 Python basics 34
fruits = ["apples", "oranges", "pears"]
count = [1, 2, 3, 4, 5]
change = [1, "pennies", 2, "dimes"]
a datatype to store multiple items, in sequence
Dictionary
3/10/2016 Python basics 35
legs = {"ant": 6, "snake": 0, "cow": 4}
states = {"Italy": "IT", "Germany": "DE"}
a datatype to store multiple items, not in sequence
key, immutable
value
Loops
3/10/2016 Python basics 36
doctor = 1
while doctor <= 13:
exterminate(doctor)
doctor += 1
For Loop: Strings
3/10/2016 Python basics 37
for char in "hello":
print char
h
e
l
l
o
For Loop: Ranges
3/10/2016 Python basics 38
for number in range(0,5):
print number
0
1
2
3
4
For Loop: Ranges
3/10/2016 Python basics 39
for number in range(0,25,5):
print number
0
5
10
15
20
For Loop: Lists
3/10/2016 Python basics 40
fruits = ["apples", "oranges", "pears"]
for fruit in fruits:
print "I love", fruit
I love apples
I love oranges
I love pears
For Loop: Dictionaries
3/10/2016 Python basics 41
legs = {"ant": 6, "snake": 0, "cow": 4}
for (animal, number) in legs.items():
print "{} has {} legs".format(animal,
number)
ant has 6 legs
snake has 0 legs
cow has 4 legs
Printing a List
3/10/2016 Python basics 42
to_buy = ["eggs", "milk"]
print to_buy
['eggs', 'milk']
Printing a List
3/10/2016 Python basics 43
to_buy = ["eggs", "milk"]
print to_buy[0]
eggs
Modifying a List
3/10/2016 Python basics 44
to_buy = ["eggs", "milk"]
print to_buy[0]
to_buy[0] = "butter"
print to_buy[0]
eggs
butter
Modifying a List
3/10/2016 Python basics 45
to_buy = ["eggs", "milk"]
# I need to buy chocolate!
to_buy.append("chocolate")
['eggs', 'milk', 'chocolate']
Modifying a List
3/10/2016 Python basics 46
to_buy = ["eggs", "milk"]
to_buy.append("chocolate")
to_buy.extend(["flour", "cheese"])
['eggs', 'milk', 'chocolate', 'flour', 'cheese']
Modifying a List
3/10/2016 Python basics 47
to_buy = ["eggs", "milk"]
to_buy.append("chocolate")
to_buy = to_buy + ["flour", "cheese"]
['eggs', 'milk', 'chocolate', 'flour', 'cheese']
concatenation
Modifying a List
3/10/2016 Python basics 48
to_buy = ["eggs", "milk", "chocolate",
"flour", "cheese"]
print to_buy[1:3]
['milk', 'chocolate']
slice operator
Modifying a List
3/10/2016 Python basics 49
to_buy = ["eggs", "milk", "chocolate",
"flour", "cheese"]
# make a full copy of the list
remember = to_buy[:]
works with strings, too
Modifying a List
3/10/2016 Python basics 50
to_buy = ["eggs", "milk", "chocolate",
"flour", "cheese"]
# I don't need cheese!
to_buy.pop()
# … neither milk, by the way!
to_buy.pop(1)
Modifying a List
3/10/2016 Python basics 51
to_buy = ["eggs", "milk", "chocolate",
"flour", "cheese"]
# I don't need cheese!
to_buy.remove("cheese")
# … neither milk, by the way!
to_buy.remove("milk")
Modifying a List
3/10/2016 Python basics 52
to_buy = ["eggs", "milk", "chocolate",
"flour", "cheese"]
# I want my original list back!
del to_buy[2:6]
['eggs', 'milk']
Strings vs. Lists
3/10/2016 Python basics 53
A string is a sequence of characters…
… but a list of characters is not a string
language_name = "Python"
# string to list
name = list(language_name)
Strings vs. Lists
3/10/2016 Python basics 54
sentence = "this is AmI"
# break a string into separate words
words = sentence.split()
['this', 'is', 'AmI']
Copying Lists
3/10/2016 Python basics 55
fruits = ['apple', 'orange']
favorite_fruits = fruits
# add a fruit to the original list
fruits.append('banana')
print 'The fruits now are:', fruits
print 'My favorite fruits are', favorite_fruits
Fruits are: ['apple', 'orange', 'banana']
My favorite fruits are: ['apple', 'orange',
'banana']
???
Copying Lists
3/10/2016 Python basics 56
fruits = ['apple', 'orange']
favorite_fruits = fruits
# add a fruit to the original list
fruits.append('banana')
print 'The fruits now are:', fruits
print 'My favorite fruits are', favorite_fruits
We do not make a copy of
the entire list, but we only
make a reference to it!
Copying Lists (For Real!)
3/10/2016 Python basics 57
# option 1: slice
favorite_fruits = fruits[:]
#option 2: create a new list - best!
favorite_fruits = list(fruit)
#extend an empty list
favorite_fruits.extends(fruit)
Other operations with lists? Python docs
Printing a Dictionary
3/10/2016 Python basics 58
legs = {"ant": 6, "snake": 0 }
print legs
{'ant': 6, 'snake': 0}
Modifying a Dictionary
3/10/2016 Python basics 59
legs = {"ant": 6, "snake": 0 }
legs["spider"] = 273
{'ant': 6, 'snake': 0, 'spider': 273}
Modifying a Dictionary
3/10/2016 Python basics 60
legs = {"ant": 6, "snake": 0 }
legs["spider"] = 273 # basically, run!
legs["spider"] = 8 # better!
{'ant': 6, 'snake': 0, 'spider': 8}
Modifying a Dictionary
3/10/2016 Python basics 61
legs = {"ant": 6, "snake": 0, "spider": 8}
# I don't like spiders
legs.del["spider"]
# Clear all the things!
legs.clear()
Retrieving a Value from a
Dictionary
3/10/2016 Python basics 62
legs = {"ant": 6, "snake": 0}
# get "ant"!
legs["ant"] # 6
# get "spider"
legs["spider"]
Retrieving a Value from a
Dictionary
3/10/2016 Python basics 63
legs = {"ant": 6, "snake": 0}
# get "ant"!
legs["ant"] # 6
# get "spider"
legs["spider"]
# KeyError: spider
Retrieving a Value from a
Dictionary
3/10/2016 Python basics 64
legs = {"ant": 6, "snake": 0}
# check if "spider" is in the dictionary
"spider" in legs # False
# get "spider" without throwing errors
legs.get("spider") # None
# get "spider" with a custom value
legs.get("spider", "Not present")
Functions
3/10/2016 Python basics 65
def say_hello():
print "Hello!"
say_hello()
definition
call
Functions with Parameters
3/10/2016 Python basics 66
def say_hello_to(name):
print "Hello", name
say_hello_to("AmI students")
Default Parameter Values
3/10/2016 Python basics 67
def say_hello_to(name="AmI"):
print "Hello", name
say_hello_to() # Hello AmI
say_hello_to("students") # Hello students
Returning Values
3/10/2016 Python basics 68
def build_greetings(name="AmI"):
return "Hello" + name
greeting = build_greetings()
print greeting # Hello AmI
Returning Multiple Values
3/10/2016 Python basics 69
def build_greetings(name="AmI"):
return ("Hello", name)
(greeting, person) = build_greetings()
print greeting + " to " + person
# Hello to AmI
Documenting Functions
3/10/2016 Python basics 70
def build_greetings(name="AmI"):
'''Build a greeting in the format
Hello plus a given name'''
return ("Hello", name)
docstring
Modules
3/10/2016 Python basics 71
• A way to logically organize the code
• They are files consisting of Python code
– they can define (and implement) functions, variables,
etc.
– typically, the file containing a module is called in the
same way
• e.g., the math module resides in a file named math.py
Importing a Module
3/10/2016 Python basics 72
import math # import the math module
print math.pi # print 3.141592…
from math import pi # import pi, only!
print pi # print 3.141592…
from math import * # import all the names
print pi DO NOT USE
Command Line Parameters
3/10/2016 Python basics 73
from sys import argv
script, first = argv
print "The script is called:", script
print "The parameter is:", first
> python my_script.py one
The script is called: my_script.py
The parameter is: one
unpacking
Reading Files
3/10/2016 Python basics 74
from sys import argv
filename = argv[1]
txt = open(filename)
print "Here's your file %r:", % filename
print txt.read()
open the file
show the file content
Writing Files
3/10/2016 Python basics 75
from sys import argv
filename = argv[1]
# open the file in write mode
target = open(filename, "w")
target.truncate() # empties the file
# write a string into the file
target.write("This is the new content")
target.close() # close the file
References and Links
• Python Documentation, http://docs.python.org/2
• The Python Tutorial, http://docs.python.org/2/tutorial/
• The Google Python course,
https://developer.google.com/edu/python
• Online Python Tutor, http://pythontutor.com
• «Think Python: How to think like a computer scientist»,
Allen Downey, Green Tea Press, Needham,
Massachusetts
• «Dive into Python 2», Mark Pilgrim
• «Learn Python the Hard Way», Zed Shaw
• «Learning Python» (5th edition), Mark Lutz, O'Reilly
3/10/2016 Python basics 76
Questions?
01QZP AMBIENT INTELLIGENCE
Luigi De Russis
luigi.derussis@polito.it
License
• This work is licensed under the Creative Commons “Attribution-
NonCommercial-ShareAlike Unported (CC BY-NC-SA 3,0)” License.
• You are free:
– to Share - to copy, distribute and transmit the work
– to Remix - to adapt the work
• Under the following conditions:
– Attribution - You must attribute the work in the manner specified by the
author or licensor (but not in any way that suggests that they endorse you
or your use of the work).
– Noncommercial - You may not use this work for commercial purposes.
– Share Alike - If you alter, transform, or build upon this work, you may
distribute the resulting work only under the same or similar license to this
one.
• To view a copy of this license, visit
http://creativecommons.org/license/by-nc-sa/3.0/
3/10/2016 Version Control with Git 78

Contenu connexe

Tendances

Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for KidsAimee Maree Forsstrom
 
Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin IGuixing Bai
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutesSidharth Nadhan
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming LanguageRohan Gupta
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In PythonMarwan Osman
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data TypesRavi Shankar
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced pythonCharles-Axel Dein
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentationNimrita Koul
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlowBayu Aldi Yansyah
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)Pedro Rodrigues
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanWei-Yuan Chang
 
Class 5: If, while & lists
Class 5: If, while & listsClass 5: If, while & lists
Class 5: If, while & listsMarc Gouw
 

Tendances (20)

Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Basics of python 3
Basics of python 3Basics of python 3
Basics of python 3
 
Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin I
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming Language
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data Types
 
python codes
python codespython codes
python codes
 
Python
PythonPython
Python
 
Python 101
Python 101Python 101
Python 101
 
Introduction to advanced python
Introduction to advanced pythonIntroduction to advanced python
Introduction to advanced python
 
Python Traning presentation
Python Traning presentationPython Traning presentation
Python Traning presentation
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
 
Python fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuanPython fundamentals - basic | WeiYuan
Python fundamentals - basic | WeiYuan
 
Class 5: If, while & lists
Class 5: If, while & listsClass 5: If, while & lists
Class 5: If, while & lists
 

En vedette

AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introductionLuigi De Russis
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introductionLuigi De Russis
 
Interacting with Smart Environments - Ph.D. Thesis Presentation
Interacting with Smart Environments - Ph.D. Thesis PresentationInteracting with Smart Environments - Ph.D. Thesis Presentation
Interacting with Smart Environments - Ph.D. Thesis PresentationLuigi De Russis
 
PowerOnt: an ontology-based approach for power consumption estimation in Smar...
PowerOnt: an ontology-based approach for power consumption estimation in Smar...PowerOnt: an ontology-based approach for power consumption estimation in Smar...
PowerOnt: an ontology-based approach for power consumption estimation in Smar...Luigi De Russis
 
Python Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationPython Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationP3 InfoTech Solutions Pvt. Ltd.
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Pedro Rodrigues
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programmingKiran Vadakkath
 
Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)Luigi De Russis
 
Classification of computers
Classification of computersClassification of computers
Classification of computerssunil kumar
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd roundYouhei Sakurai
 
Evolution and classification of computers
Evolution and classification of computersEvolution and classification of computers
Evolution and classification of computersAVINASH ANAND
 

En vedette (20)

AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introduction
 
Interacting with Smart Environments - Ph.D. Thesis Presentation
Interacting with Smart Environments - Ph.D. Thesis PresentationInteracting with Smart Environments - Ph.D. Thesis Presentation
Interacting with Smart Environments - Ph.D. Thesis Presentation
 
PowerOnt: an ontology-based approach for power consumption estimation in Smar...
PowerOnt: an ontology-based approach for power consumption estimation in Smar...PowerOnt: an ontology-based approach for power consumption estimation in Smar...
PowerOnt: an ontology-based approach for power consumption estimation in Smar...
 
Python Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationPython Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and Indentation
 
Python - basics
Python - basicsPython - basics
Python - basics
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
PythonIntro
PythonIntroPythonIntro
PythonIntro
 
Python Workshop
Python WorkshopPython Workshop
Python Workshop
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python basics
Python basicsPython basics
Python basics
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)Introduction to OpenCV 3.x (with Java)
Introduction to OpenCV 3.x (with Java)
 
Python basics
Python basicsPython basics
Python basics
 
Classification of computers
Classification of computersClassification of computers
Classification of computers
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd round
 
Evolution and classification of computers
Evolution and classification of computersEvolution and classification of computers
Evolution and classification of computers
 
Python programming language
Python programming languagePython programming language
Python programming language
 

Similaire à Python Basics Guide: Introduction to Programming Concepts

Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computingGo Asgard
 
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
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in pythoneShikshak
 
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
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from DataMosky Liu
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinAhmad Arif Faizin
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School ProgrammersSiva Arunachalam
 
Τα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonΤα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonMoses Boudourides
 
python-an-introduction
python-an-introductionpython-an-introduction
python-an-introductionShrinivasan T
 
Mastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loopsMastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loopsRuth Marvin
 
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
 
A Gentle Introduction to Coding ... with Python
A Gentle Introduction to Coding ... with PythonA Gentle Introduction to Coding ... with Python
A Gentle Introduction to Coding ... with PythonTariq Rashid
 

Similaire à Python Basics Guide: Introduction to Programming Concepts (20)

Python for scientific computing
Python for scientific computingPython for scientific computing
Python for scientific computing
 
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 slide
Python slidePython slide
Python slide
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
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)
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from Data
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
PEP 498: The Monologue
PEP 498: The MonologuePEP 498: The Monologue
PEP 498: The Monologue
 
Python- strings
Python- stringsPython- strings
Python- strings
 
python_class.pptx
python_class.pptxpython_class.pptx
python_class.pptx
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlin
 
Robust Python.pptx
Robust Python.pptxRobust Python.pptx
Robust Python.pptx
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 
Τα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την PythonΤα Πολύ Βασικά για την Python
Τα Πολύ Βασικά για την Python
 
python-an-introduction
python-an-introductionpython-an-introduction
python-an-introduction
 
Mastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loopsMastering Python lesson3b_for_loops
Mastering Python lesson3b_for_loops
 
Python 101 1
Python 101   1Python 101   1
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...
 
A Gentle Introduction to Coding ... with Python
A Gentle Introduction to Coding ... with PythonA Gentle Introduction to Coding ... with Python
A Gentle Introduction to Coding ... with Python
 

Plus de Luigi De Russis

Assessing Virtual Assistant Capabilities with Italian Dysarthric Speech
Assessing Virtual Assistant Capabilities with Italian Dysarthric SpeechAssessing Virtual Assistant Capabilities with Italian Dysarthric Speech
Assessing Virtual Assistant Capabilities with Italian Dysarthric SpeechLuigi De Russis
 
Semantic Web: an Introduction
Semantic Web: an IntroductionSemantic Web: an Introduction
Semantic Web: an IntroductionLuigi De Russis
 
Programming the Semantic Web
Programming the Semantic WebProgramming the Semantic Web
Programming the Semantic WebLuigi De Russis
 
Semantic Web - Ontology 101
Semantic Web - Ontology 101Semantic Web - Ontology 101
Semantic Web - Ontology 101Luigi De Russis
 
AmI 2017 - Python intermediate
AmI 2017 - Python intermediateAmI 2017 - Python intermediate
AmI 2017 - Python intermediateLuigi De Russis
 
Ambient Intelligence: An Overview
Ambient Intelligence: An OverviewAmbient Intelligence: An Overview
Ambient Intelligence: An OverviewLuigi De Russis
 
Version Control with Git
Version Control with GitVersion Control with Git
Version Control with GitLuigi De Russis
 
LAM 2015 - Social Networks Technologies
LAM 2015 - Social Networks TechnologiesLAM 2015 - Social Networks Technologies
LAM 2015 - Social Networks TechnologiesLuigi De Russis
 
Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)Luigi De Russis
 
Living in Smart Environments - 3rd year PhD Report
Living in Smart Environments - 3rd year PhD ReportLiving in Smart Environments - 3rd year PhD Report
Living in Smart Environments - 3rd year PhD ReportLuigi De Russis
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introductionLuigi De Russis
 
Social Network Technologies
Social Network TechnologiesSocial Network Technologies
Social Network TechnologiesLuigi De Russis
 
Living in Smart Environments - 2nd year PhD Report
Living in Smart Environments - 2nd year PhD ReportLiving in Smart Environments - 2nd year PhD Report
Living in Smart Environments - 2nd year PhD ReportLuigi De Russis
 
Installing OpenCV 2.4.x with Qt
Installing OpenCV 2.4.x with QtInstalling OpenCV 2.4.x with Qt
Installing OpenCV 2.4.x with QtLuigi De Russis
 
dWatch: a Personal Wrist Watch for Smart Environments
dWatch: a Personal Wrist Watch for Smart EnvironmentsdWatch: a Personal Wrist Watch for Smart Environments
dWatch: a Personal Wrist Watch for Smart EnvironmentsLuigi De Russis
 
Introduction to OpenCV 2.3.1
Introduction to OpenCV 2.3.1Introduction to OpenCV 2.3.1
Introduction to OpenCV 2.3.1Luigi De Russis
 
Installing OpenCV 2.3.1 with Qt
Installing OpenCV 2.3.1 with QtInstalling OpenCV 2.3.1 with Qt
Installing OpenCV 2.3.1 with QtLuigi De Russis
 
Version Control with Git
Version Control with GitVersion Control with Git
Version Control with GitLuigi De Russis
 

Plus de Luigi De Russis (20)

Assessing Virtual Assistant Capabilities with Italian Dysarthric Speech
Assessing Virtual Assistant Capabilities with Italian Dysarthric SpeechAssessing Virtual Assistant Capabilities with Italian Dysarthric Speech
Assessing Virtual Assistant Capabilities with Italian Dysarthric Speech
 
Semantic Web: an Introduction
Semantic Web: an IntroductionSemantic Web: an Introduction
Semantic Web: an Introduction
 
Programming the Semantic Web
Programming the Semantic WebProgramming the Semantic Web
Programming the Semantic Web
 
Semantic Web - Ontology 101
Semantic Web - Ontology 101Semantic Web - Ontology 101
Semantic Web - Ontology 101
 
AmI 2017 - Python intermediate
AmI 2017 - Python intermediateAmI 2017 - Python intermediate
AmI 2017 - Python intermediate
 
Ambient Intelligence: An Overview
Ambient Intelligence: An OverviewAmbient Intelligence: An Overview
Ambient Intelligence: An Overview
 
Version Control with Git
Version Control with GitVersion Control with Git
Version Control with Git
 
LAM 2015 - Social Networks Technologies
LAM 2015 - Social Networks TechnologiesLAM 2015 - Social Networks Technologies
LAM 2015 - Social Networks Technologies
 
Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)Introduction to OpenCV (with Java)
Introduction to OpenCV (with Java)
 
Living in Smart Environments - 3rd year PhD Report
Living in Smart Environments - 3rd year PhD ReportLiving in Smart Environments - 3rd year PhD Report
Living in Smart Environments - 3rd year PhD Report
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introduction
 
Social Network Technologies
Social Network TechnologiesSocial Network Technologies
Social Network Technologies
 
Clean Code
Clean CodeClean Code
Clean Code
 
Living in Smart Environments - 2nd year PhD Report
Living in Smart Environments - 2nd year PhD ReportLiving in Smart Environments - 2nd year PhD Report
Living in Smart Environments - 2nd year PhD Report
 
Introduction to OpenCV
Introduction to OpenCVIntroduction to OpenCV
Introduction to OpenCV
 
Installing OpenCV 2.4.x with Qt
Installing OpenCV 2.4.x with QtInstalling OpenCV 2.4.x with Qt
Installing OpenCV 2.4.x with Qt
 
dWatch: a Personal Wrist Watch for Smart Environments
dWatch: a Personal Wrist Watch for Smart EnvironmentsdWatch: a Personal Wrist Watch for Smart Environments
dWatch: a Personal Wrist Watch for Smart Environments
 
Introduction to OpenCV 2.3.1
Introduction to OpenCV 2.3.1Introduction to OpenCV 2.3.1
Introduction to OpenCV 2.3.1
 
Installing OpenCV 2.3.1 with Qt
Installing OpenCV 2.3.1 with QtInstalling OpenCV 2.3.1 with Qt
Installing OpenCV 2.3.1 with Qt
 
Version Control with Git
Version Control with GitVersion Control with Git
Version Control with Git
 

Dernier

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 

Dernier (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 

Python Basics Guide: Introduction to Programming Concepts

  • 1. Python BASICS Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.
  • 2. #include <stdio.h> int main() { printf("Hello, world!"); return 0; } 3/10/2016 Python basics 2
  • 4. # this will print "Hello, world!" print "Hello, world!" 3/10/2016 Python basics 4 inline comment
  • 5. Keywords • and • del • from • not • while • as • elif • global • or • with • assert • else • if • pass • yield • break • except • import • print • class • exec 3/10/2016 Python basics 5 • in • raise • continue • finally • is • return • def • for • lambda • try
  • 6. Variables 3/10/2016 Python basics 6 language_name = "Python" naming convention: joined_lower this is a string
  • 7. Variables 3/10/2016 Python basics 7 language_name = "Python" version = '2.7.11' introduced = 1991 is_awesome = True
  • 8. Type Inference 3/10/2016 Python basics 8 language_name = "Python" # string version = '2.7.11' # another string introduced = 1991 # integer is_awesome = True # boolean actual type can be checked with type() play_with_types.py
  • 9. String 3/10/2016 Python basics 9 some_string = "I'm a string" another_string = 'I'm a string, too'
  • 10. String 3/10/2016 Python basics 10 some_string = "I'm a string" another_string = 'I'm a string, too' # SyntaxError: invalid syntax
  • 11. String 3/10/2016 Python basics 11 another_string = 'I am a string, too' another_strig = 'I'm a string, too' escape sequence
  • 12. String 3/10/2016 Python basics 12 long_string = """I am a long string. I span over two lines.""" long_string = '''I am another long string. I span over three lines. I am composed by three sentences.'''
  • 13. If Statement 3/10/2016 Python basics 13 people = 20 cats = 30 if people < cats: print "Too many cats! We are doomed!" if people > cats: print "Not many cats! We are safe!" 4 spaces 4 spaces
  • 14. If Statement 3/10/2016 Python basics 14 people = 20 cats = 30 if people < cats: print "Too many cats! We are doomed!" elif people > cats: print "Not many cats! We are safe!" else: print "We can't decide."
  • 15. Comparators and Booleans Operators 3/10/2016 Python basics 15 print 2 == 1 print 'string' == "string" print not False print 2==1 and True print 2==1 or True
  • 16. Comparators and Booleans Operators 3/10/2016 Python basics 16 print 2 == 1 # False print 'string' == "string" # True print not False # True print 2==1 and True # False print 2==1 or True # True
  • 17. Characters 3/10/2016 Python basics 17 for char in "hello": print char h e l l o
  • 18. Characters 3/10/2016 Python basics 18 say_hello = "hello!" print say_hello[1] e index
  • 19. Characters 3/10/2016 Python basics 19 say_hello = "hello!" print type(say_hello[1]) <type 'str'>
  • 20. Combining Strings 3/10/2016 Python basics 20 language_name = "Python" version = '2.7.11' python_version = language_name + version # python_version is Python2.7.11 print "my " + "name" # my name concatenation
  • 21. Combining Strings 3/10/2016 Python basics 21 language_name = "Python" a_lot_of_python = language_name*3 # a_lot_of_python is PythonPythonPython repetition
  • 22. Building Complex Strings 3/10/2016 Python basics 22 a = 3 b = 5 # 3 times 5 is 15 print a, "times", b, "is", a*b works with print, only
  • 23. Building Complex Strings 3/10/2016 Python basics 23 a = 3 b = 5 # 3 times 5 is 15 result = a + " times " + b + " is " + a*b
  • 24. Building Complex Strings 3/10/2016 Python basics 24 a = 3 b = 5 # 3 times 5 is 15 result = a + " times " + b + " is " + a*b #TypeError: unsupported operand type(s)
  • 25. Building Complex Strings 3/10/2016 Python basics 25 a = 3 b = 5 # 3 times 5 is 15 result = str(a) + " times " + str(b) + " is " + str(a*b)
  • 26. String Interpolation 3/10/2016 Python basics 26 a = 3 b = 5 # 3 times 5 is 15 result = "%d times %d is %d" %(a, b, a*b) Specifiers • %s, format strings • %d, format numbers • %r, raw representation tuplespecifiers.py
  • 27. String Interpolation 3/10/2016 Python basics 27 a = 3 b = 5 # 3 times 5 is 15 result = "{} times {} is {}".format(a, b, a*b) new way!
  • 28. String Immutability 3/10/2016 Python basics 28 # hello say_hello = "helko" # ops… say_hello[3] = "l"
  • 29. String Immutability 3/10/2016 Python basics 29 # hello say_hello = "helko" # ops… say_hello[3] = "l" # TypeError
  • 30. String Immutability 3/10/2016 Python basics 30 # hello say_hello = "helko" # ops… say_hello = "hello" Other operations with strings? Python docs
  • 31. Getting Input 3/10/2016 Python basics 31 print "How old are you?" age = raw_input() # age is a string print "You are " + age + " years old"
  • 32. Getting Input 3/10/2016 Python basics 32 print "How old are you?" age = raw_input() # age is a string print "You are " + age + " years old" # I want "age" to be a number! age = int(raw_input())
  • 33. Getting Input 3/10/2016 Python basics 33 age = raw_input("How old are you? ") print "You are " + age + " years old"
  • 34. List 3/10/2016 Python basics 34 fruits = ["apples", "oranges", "pears"] count = [1, 2, 3, 4, 5] change = [1, "pennies", 2, "dimes"] a datatype to store multiple items, in sequence
  • 35. Dictionary 3/10/2016 Python basics 35 legs = {"ant": 6, "snake": 0, "cow": 4} states = {"Italy": "IT", "Germany": "DE"} a datatype to store multiple items, not in sequence key, immutable value
  • 36. Loops 3/10/2016 Python basics 36 doctor = 1 while doctor <= 13: exterminate(doctor) doctor += 1
  • 37. For Loop: Strings 3/10/2016 Python basics 37 for char in "hello": print char h e l l o
  • 38. For Loop: Ranges 3/10/2016 Python basics 38 for number in range(0,5): print number 0 1 2 3 4
  • 39. For Loop: Ranges 3/10/2016 Python basics 39 for number in range(0,25,5): print number 0 5 10 15 20
  • 40. For Loop: Lists 3/10/2016 Python basics 40 fruits = ["apples", "oranges", "pears"] for fruit in fruits: print "I love", fruit I love apples I love oranges I love pears
  • 41. For Loop: Dictionaries 3/10/2016 Python basics 41 legs = {"ant": 6, "snake": 0, "cow": 4} for (animal, number) in legs.items(): print "{} has {} legs".format(animal, number) ant has 6 legs snake has 0 legs cow has 4 legs
  • 42. Printing a List 3/10/2016 Python basics 42 to_buy = ["eggs", "milk"] print to_buy ['eggs', 'milk']
  • 43. Printing a List 3/10/2016 Python basics 43 to_buy = ["eggs", "milk"] print to_buy[0] eggs
  • 44. Modifying a List 3/10/2016 Python basics 44 to_buy = ["eggs", "milk"] print to_buy[0] to_buy[0] = "butter" print to_buy[0] eggs butter
  • 45. Modifying a List 3/10/2016 Python basics 45 to_buy = ["eggs", "milk"] # I need to buy chocolate! to_buy.append("chocolate") ['eggs', 'milk', 'chocolate']
  • 46. Modifying a List 3/10/2016 Python basics 46 to_buy = ["eggs", "milk"] to_buy.append("chocolate") to_buy.extend(["flour", "cheese"]) ['eggs', 'milk', 'chocolate', 'flour', 'cheese']
  • 47. Modifying a List 3/10/2016 Python basics 47 to_buy = ["eggs", "milk"] to_buy.append("chocolate") to_buy = to_buy + ["flour", "cheese"] ['eggs', 'milk', 'chocolate', 'flour', 'cheese'] concatenation
  • 48. Modifying a List 3/10/2016 Python basics 48 to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"] print to_buy[1:3] ['milk', 'chocolate'] slice operator
  • 49. Modifying a List 3/10/2016 Python basics 49 to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"] # make a full copy of the list remember = to_buy[:] works with strings, too
  • 50. Modifying a List 3/10/2016 Python basics 50 to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"] # I don't need cheese! to_buy.pop() # … neither milk, by the way! to_buy.pop(1)
  • 51. Modifying a List 3/10/2016 Python basics 51 to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"] # I don't need cheese! to_buy.remove("cheese") # … neither milk, by the way! to_buy.remove("milk")
  • 52. Modifying a List 3/10/2016 Python basics 52 to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"] # I want my original list back! del to_buy[2:6] ['eggs', 'milk']
  • 53. Strings vs. Lists 3/10/2016 Python basics 53 A string is a sequence of characters… … but a list of characters is not a string language_name = "Python" # string to list name = list(language_name)
  • 54. Strings vs. Lists 3/10/2016 Python basics 54 sentence = "this is AmI" # break a string into separate words words = sentence.split() ['this', 'is', 'AmI']
  • 55. Copying Lists 3/10/2016 Python basics 55 fruits = ['apple', 'orange'] favorite_fruits = fruits # add a fruit to the original list fruits.append('banana') print 'The fruits now are:', fruits print 'My favorite fruits are', favorite_fruits Fruits are: ['apple', 'orange', 'banana'] My favorite fruits are: ['apple', 'orange', 'banana'] ???
  • 56. Copying Lists 3/10/2016 Python basics 56 fruits = ['apple', 'orange'] favorite_fruits = fruits # add a fruit to the original list fruits.append('banana') print 'The fruits now are:', fruits print 'My favorite fruits are', favorite_fruits We do not make a copy of the entire list, but we only make a reference to it!
  • 57. Copying Lists (For Real!) 3/10/2016 Python basics 57 # option 1: slice favorite_fruits = fruits[:] #option 2: create a new list - best! favorite_fruits = list(fruit) #extend an empty list favorite_fruits.extends(fruit) Other operations with lists? Python docs
  • 58. Printing a Dictionary 3/10/2016 Python basics 58 legs = {"ant": 6, "snake": 0 } print legs {'ant': 6, 'snake': 0}
  • 59. Modifying a Dictionary 3/10/2016 Python basics 59 legs = {"ant": 6, "snake": 0 } legs["spider"] = 273 {'ant': 6, 'snake': 0, 'spider': 273}
  • 60. Modifying a Dictionary 3/10/2016 Python basics 60 legs = {"ant": 6, "snake": 0 } legs["spider"] = 273 # basically, run! legs["spider"] = 8 # better! {'ant': 6, 'snake': 0, 'spider': 8}
  • 61. Modifying a Dictionary 3/10/2016 Python basics 61 legs = {"ant": 6, "snake": 0, "spider": 8} # I don't like spiders legs.del["spider"] # Clear all the things! legs.clear()
  • 62. Retrieving a Value from a Dictionary 3/10/2016 Python basics 62 legs = {"ant": 6, "snake": 0} # get "ant"! legs["ant"] # 6 # get "spider" legs["spider"]
  • 63. Retrieving a Value from a Dictionary 3/10/2016 Python basics 63 legs = {"ant": 6, "snake": 0} # get "ant"! legs["ant"] # 6 # get "spider" legs["spider"] # KeyError: spider
  • 64. Retrieving a Value from a Dictionary 3/10/2016 Python basics 64 legs = {"ant": 6, "snake": 0} # check if "spider" is in the dictionary "spider" in legs # False # get "spider" without throwing errors legs.get("spider") # None # get "spider" with a custom value legs.get("spider", "Not present")
  • 65. Functions 3/10/2016 Python basics 65 def say_hello(): print "Hello!" say_hello() definition call
  • 66. Functions with Parameters 3/10/2016 Python basics 66 def say_hello_to(name): print "Hello", name say_hello_to("AmI students")
  • 67. Default Parameter Values 3/10/2016 Python basics 67 def say_hello_to(name="AmI"): print "Hello", name say_hello_to() # Hello AmI say_hello_to("students") # Hello students
  • 68. Returning Values 3/10/2016 Python basics 68 def build_greetings(name="AmI"): return "Hello" + name greeting = build_greetings() print greeting # Hello AmI
  • 69. Returning Multiple Values 3/10/2016 Python basics 69 def build_greetings(name="AmI"): return ("Hello", name) (greeting, person) = build_greetings() print greeting + " to " + person # Hello to AmI
  • 70. Documenting Functions 3/10/2016 Python basics 70 def build_greetings(name="AmI"): '''Build a greeting in the format Hello plus a given name''' return ("Hello", name) docstring
  • 71. Modules 3/10/2016 Python basics 71 • A way to logically organize the code • They are files consisting of Python code – they can define (and implement) functions, variables, etc. – typically, the file containing a module is called in the same way • e.g., the math module resides in a file named math.py
  • 72. Importing a Module 3/10/2016 Python basics 72 import math # import the math module print math.pi # print 3.141592… from math import pi # import pi, only! print pi # print 3.141592… from math import * # import all the names print pi DO NOT USE
  • 73. Command Line Parameters 3/10/2016 Python basics 73 from sys import argv script, first = argv print "The script is called:", script print "The parameter is:", first > python my_script.py one The script is called: my_script.py The parameter is: one unpacking
  • 74. Reading Files 3/10/2016 Python basics 74 from sys import argv filename = argv[1] txt = open(filename) print "Here's your file %r:", % filename print txt.read() open the file show the file content
  • 75. Writing Files 3/10/2016 Python basics 75 from sys import argv filename = argv[1] # open the file in write mode target = open(filename, "w") target.truncate() # empties the file # write a string into the file target.write("This is the new content") target.close() # close the file
  • 76. References and Links • Python Documentation, http://docs.python.org/2 • The Python Tutorial, http://docs.python.org/2/tutorial/ • The Google Python course, https://developer.google.com/edu/python • Online Python Tutor, http://pythontutor.com • «Think Python: How to think like a computer scientist», Allen Downey, Green Tea Press, Needham, Massachusetts • «Dive into Python 2», Mark Pilgrim • «Learn Python the Hard Way», Zed Shaw • «Learning Python» (5th edition), Mark Lutz, O'Reilly 3/10/2016 Python basics 76
  • 77. Questions? 01QZP AMBIENT INTELLIGENCE Luigi De Russis luigi.derussis@polito.it
  • 78. License • This work is licensed under the Creative Commons “Attribution- NonCommercial-ShareAlike Unported (CC BY-NC-SA 3,0)” License. • You are free: – to Share - to copy, distribute and transmit the work – to Remix - to adapt the work • Under the following conditions: – Attribution - You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). – Noncommercial - You may not use this work for commercial purposes. – Share Alike - If you alter, transform, or build upon this work, you may distribute the resulting work only under the same or similar license to this one. • To view a copy of this license, visit http://creativecommons.org/license/by-nc-sa/3.0/ 3/10/2016 Version Control with Git 78