SlideShare ist ein Scribd-Unternehmen logo
1 von 59
Downloaden Sie, um offline zu lesen
Python
BASICS
Introduction to Python programming, basic
concepts: formatting, naming conventions,
variables, etc.
Editing / Formatting
• Python programs are
text files
• The end of a line
marks the end of a
statement
• Comments:
– Inline comments start
with a #
3/12/2015 Python basics 2
print 1+1 #statement
# inline comment
Editing / Formatting
• Code blocks are
defined through
identation
– mandatory
– 4 spaces strategy
• Use 4 spaces for code
identation
• Configure the text
editor to replace tabs
with 4 spaces (default
in PyDev)
• Exploit automatic
identation
3/12/2015 Python basics 3
def print_name():
# this is a block
name = 'sheldon'
surname = 'cooper'
print name, surname
4 spaces
4 spaces
4 spaces
4 spaces
Keywords
• and
• del
• from
• not
• while
• as
• elif
• global
• or
• with
• assert
• else
• if
• pass
• yield
• break
• except
• import
• print
• class
• exec
3/12/2015 Python basics 4
• in
• raise
• continue
• finally
• is
• return
• def
• for
• lambda
• try
Numbers and math
3/12/2015 Python basics 5
Operator Description
+ plus Sum
- minus Subtraction
/ slash Floor division
* asterisk Multiplication
** double asterisk Exponentiation
% percent Remainder
< less-than Comparison
> greater-than Comparison
<= less-than-equal Comparison
>= greater-than-equal Comparison
Numbers and math
3/12/2015 Python basics 6
print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
Order of operations
• PEMDAS
– Parenthesis
– Exponentiation
– Multiplication
– Division
– Addition
– Subtraction
• Same precedence
– Left to right execution
3/12/2015 Python basics 7
Naming conventions
• joined_lower
– for functions,
variables, attributes
• joined_lower or
ALL_CAPS
– for constants
• StudlyCaps
– for classes
3/12/2015 Python basics 8
#variables
my_variable = 12
my_second_variable = 'Hello!'
#functions
my_function(my_variable)
my_print(my_second_variable)
Variables
• Variable types are not
explicitly declared
• Runtime type-checking
• The same variable can
be reused for holding
different data types
3/12/2015 Python basics 9
#integer variable
a = 1
print a
#float variable
a = 2.345
print a
#re-assignment to string
a = 'my name'
print a
# double quotes could be
# used as well
a = "my name"
print a
More variables
• Actual type can be
checked through the
interpreter
• Check the first result,
what happened?
• Display 01,010,01010
• Display 08
• Octal numbering system?
3/12/2015 Python basics 10
Examples
3/12/2015 Python basics 11
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print 'There are', cars, 'cars available.'
print 'There are only', drivers, 'drivers available.'
print 'There will be', cars_not_driven, 'empty cars today.'
print 'We can transport', carpool_capacity, 'people today.'
print 'We have', passengers, 'to carpool today.'
print 'We need to put about', average_passengers_per_car,'in each car.'
Strings
• Defined by using quotes
– "first string"
– 'second string'
• Immutable
• Each character in a string is assigned a number
– the number is called index
• Mathematical operators cannot be applied
• Exceptions
– + : means concatenation
– * : means repetition
3/12/2015 Python basics 12
Strings
3/12/2015 Python basics 13
name = 'Anthony "Tony" Stark'
age = 45 # not a lie
height = 174 # cm
weight = 78 # kg
eyes = 'brown'
teeth = 'white'
hair = 'brown'
print "Let's talk about %s." % name
print "He's %d cm tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight)
Strings
3/12/2015 Python basics 14
name = 'Anthony "Tony" Stark'
age = 45 # not a lie
height = 174 # cm
weight = 78 # kg
eyes = 'brown'
teeth = 'white'
hair = 'brown'
print "Let's talk about %s." % name
print "He's %d cm tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight)
Specifiers
• %s, format strings
• %d, format numbers
• %r, raw representation
Tuple
More strings
3/12/2015 Python basics 15
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
print "I said: %r." % x
print "I also said: '%s'." % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
print w + e
Escape sequences
• n
– Line feed + Carriage return
• 
– Prints a «»
• We want to print «Hello»
– print "I said: "Hello" "
– Syntax error: no difference between quotes
• Solution: using escape sequences
– print "I said: “Hello" "
3/12/2015 Python basics 16
Getting input from people
• Asking questions
– We want to ask the user’s age
– We want to ask the user’s height
• The raw_input()function allows to read from
the console
3/12/2015 Python basics 17
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "You are %s years old, and you are about %s cm tall." % (age, height)
More input
3/12/2015 Python basics 18
height = int(raw_input("How tall are you? "))
name = raw_input("What's your name? ")
print type(height)
print type(name)
print("Hello %s, you are about %d tall" %(name, height) )
Command-line parameters
• Python scripts can receive launch parameters
– Placed just after the script name
– Any number
– Accessible through sys.argv
• sys
– Python module to handle system-level operations
• argv
– Argument variable
– for handling command-line parameters
3/12/2015 Python basics 19
Command-line parameters
3/12/2015 Python basics 20
from sys import argv
script, first, second, third = argv
print 'The script is called:', script
print 'Your first variable is:', first
print 'Your second variable is:', second
print 'Your third variable is:', third
Functions
• A function is a named sequence of statements
that performs a computation
– Definition first:
• specify the name and the sequence of statements
– Then usage:
• “call” the function by name
• Examples
– Type conversion functions
• int(‘32’)  32
• str(3.2479)  ‘3.2479’
3/12/2015 Python basics 21
Math functions
• Located in the math module
3/12/2015 Python basics 22
import math
signal_power = 10.0
noise_power = 0.01
ratio = signal_power / noise_power
print "ratio:", ratio
decibels = 10 * math.log10(ratio)
print "decibels:", decibels
radians = 0.7
height = math.sin(radians)
print height
Function call
String functions
• len()
– Gets the length (the number of characters) of a
string
• lower()
– Gets rid of all the capitalization in a string
• upper()
– Transform a string in upper case
• str()
– Transform «everything» in a string
3/12/2015 Python basics 23
String functions: an example
3/12/2015 Python basics 24
course_name = 'Ambient Intelligence'
string_len = len(course_name)
print string_len # 20
print course_name.lower() # ambient intelligence
print course_name.upper() # AMBIENT INTELLIGENCE
pi = 3.14
print "the value of pi is around " + str(pi) without str()
it gives an error
New functions
• Can be defined by developers
• Typically used to group homogeneous code
portions
– i.e., code for accomplishing a well-defined operation
• Enable re-use
– Same operation can be re-used several times
• Defined using the keyword def
3/12/2015 Python basics 25
New functions
3/12/2015 Python basics 26
• Compute the area of a disk, given the radius
import math
def circle_area(radius):
return radius**2*math.pi
radius = raw_input('Please, insert the radiusn')
print 'Radius: ', radius
print 'Area: ', circle_area(radius) Function call
Function definition
Docstring
• Optional, multiline comment
• Explains what the function does
• Starts and ends with """ or '''
3/12/2015 Python basics 27
import math
def circle_area(radius):
'''Compute the circle area given its radius'''
return radius**2*math.pi
radius = raw_input('Please, insert the radiusn')
print 'Radius: ', radius
print 'Area: ', circle_area(radius)
Modules
• 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 module math resides in a file named math.py
• We already met them
3/12/2015 Python basics 28
import math
from sys import argv
Importing modules
• import module_name
– allows to use all the items present in a module
3/12/2015 Python basics 29
import math
def circle_area(radius):
return radius**2*math.pi
…
Import the math module
Call the pi variable from
the math module
Importing modules
• from module_name import name
– it only imports name from the specified module
• from module_name import *
– it imports all names from a module
– do not use!
3/12/2015 Python basics 30
from math import pi
def circle_area(radius):
return radius**2*pi
…
Import pi from the math module
Use the pi variable
Playing with files
• Python script can read and write files
• First, open a file
– You can use the open() function
• Then, you can read or write it
– With read(), readline(), or write()
• Finally, remember to close the file
– You can use the close() function
3/12/2015 Python basics 31
Reading files
• Read a file taking its name from command line
3/12/2015 Python basics 32
from sys import argv
filename = argv[1]
txt = open(filename)
print “Here’s your file %r:", % filename
print txt.read()
print “nType the filename again:”
file_again = raw_input(“> ”)
txt_again = open(file_again)
print txt_again.read()
Open the file
Show the file content
Writing files
3/12/2015 Python basics 33
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "Opening the file..."
target = open(filename, 'w')
print "… truncating the file. Goodbye!"
target.truncate()
print "nNow I'm going to ask you for two lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
print "I'm going to write these to the file."
target.write(line1)
target.write("n")
target.write(line2)
target.write("n")
print "And finally, we close it."
target.close()
Open the file in write mode
Empties the file
Write a string to the file
Conditionals and control flow
• Control flow gives the ability to choose among
outcomes
– based off what else is happening in the program
• Comparators
– Equal to  ==
– Not equal to  !=
– Less than  <
– Less than or equal to  <=
– Greater than  >
– Greater than or equal to  >=
3/12/2015 Python basics 34
Comparators: an example
3/12/2015 Python basics 35
print 2 == 1 # False
print 2 == 2 # True
print 10 >= 2 # True
print 2 < 10 # True
print 5 != 5 # False
print 'string' == "string" # True
number = 123
print number > 100 # True
Boolean operators
• They are three:
– not
– and
– or
• Not evaluated from left to right
– not is evaluated first
– and is evaluated next
– or is evaluated last
3/12/2015 Python basics 36
Boolean operators: an example
3/12/2015 Python basics 37
print 2 == 1 and True # False
print 2 == 2 or True # True
print 10 >= 2 and 2 != 1 # True
print not True # False
print 10 > 5 and 10 == 10 or 5 < 2 # True
print not False and True # True
Conditional statement
• if is a statements that executes some code
after checking if a given expression is True
• Structure
if expression:
do something
3/12/2015 Python basics 38
people = 20
cats = 30
if people < cats:
print 'Too many cats! The world
is doomed!'
if people > cats:
print 'Not many cats! The world
is saved!'
More “if”
• Let’s try to “improve” the previous example
• Chained conditionals
– To express more than two possibilities
– Each condition is checked in order
3/12/2015 Python basics 39
people = 20
cats = 30
if people < cats:
print 'Too many cats! The world is doomed!'
elif people > cats:
print 'Not many cats! The world is saved!'
else:
print "We can’t decide.”
else if
Loops and lists
• Loop
– An easy way to do repetitive things
– A condition to start and stop the loop is required
– e.g., for and while loops
• List
– A datatype for storing multiple items
• a sequence of values
– You can assign items to a list in this way:
list_name = [item1, item2, …]
3/12/2015 Python basics 40
Loops and lists: an example
3/12/2015 Python basics 41
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print 'This is count %d' % number
# same as above
for fruit in fruits:
print 'A fruit of type: %s' % fruit
# we can go through mixed lists too
# notice that we have to use %r since we don't know what's in it
for i in change:
print 'I got %r' % i
Three lists
Loops and lists: an example
3/12/2015 Python basics 42
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print 'This is count %d' % number
# same as above
for fruit in fruits:
print 'A fruit of type: %s' % fruit
# we can go through mixed lists too
# notice that we have to use %r since we don't know what's in it
for i in change:
print 'I got %r' % i
Structure of a for loop
• for variable in collection:
• indent for the loop body
More “for”
3/12/2015 Python basics 43
# we can also build lists: start with an empty one…
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print 'Adding %d to the list.' % i
# append() is a function that lists understand
elements.append(i)
# now we can print them out
for i in elements:
print 'Element was: %d' % i
Empty list
Repeat 6 times
Lists
• Mutable
• Do not have a fixed length
– You can add items to a list at any time
• Accessible by index
3/12/2015 Python basics 44
letters = [‘a’, ‘b’, ‘c’]
letters.append(‘d’)
print letters # a, b, c, d
print letters[0] # a
print len(letters) # 4
letters[3] = ‘e’
print letters # a, b, c, e
More lists
• List concatenation
– with the + operator
• List slices
– to access a portion of a list
– with the [:] operator
3/12/2015 Python basics 45
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print c # 1, 2, 3, 4, 5, 6
c = [1, 2, 3, 4, 5, 6]
d = c[1:3] # d is [2, 3]
e = c[:3] # e is [1, 2, 3]
f = c[:] # f is a full copy of c
More lists
• List concatenation
– with the + operator
• List slices
– to access a portion of a list
– with the [:] operator
3/12/2015 Python basics 46
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print c # 1, 2, 3, 4, 5, 6
c = [1, 2, 3, 4, 5, 6]
d = c[1:3] # d is [2, 3]
e = c[:3] # e is [1, 2, 3]
f = c[:] # f is a full copy of c
works with string, too
List functions
• append()
– add a new element to the end of a list
– e.g., my_list.append(‘d’)
• sort()
– arrange the elements of the list from low to high
– e.g., from a to z, from 1 to infinite, etc.
• extend()
– takes a list as an argument and appends all its
elements
– e.g., first_list.extend(second_list)
3/12/2015 Python basics 47
Deleting elements from a list
• Several ways to delete elements from a list
• If you know the index of the element to
remove: pop()
– without providing an index, pop() delete the last
element
• If you know the element to remove (but not the
index): remove()
• To remove more than one element: del()
– with a slice index
• e.g., del my_list[5:8]
3/12/2015 Python basics 48
Strings vs. lists
• A string is a sequence of character, but a list of
character is not a string
• To convert a string into a list of characters: list()
– e.g., my_list = list(my_string)
• To break a string into separate words: split()
– split a list according to some delimiters (default:
space)
– e.g., my_list = my_string.split()
– The inverse function is join()
3/12/2015 Python basics 49
Copying lists
• What happens here?
3/12/2015 Python basics 50
fruits = ['apple', 'orange', 'pear', 'apricot']
print 'The fruits are:', fruits
favourite_fruits = fruits
print 'My favourite fruits are', favourite_fruits
# add a fruit to the original list
fruits.append(‘banana’)
print 'The fruits now are:', fruits
print 'My favourite fruits are', favourite_fruits
Copying lists
• What happens here?
3/12/2015 Python basics 51
fruits = ['apple', 'orange', 'pear', 'apricot']
print 'The fruits are:', fruits
favourite_fruits = fruits
print 'My favourite fruits are', favourite_fruits
# add a fruit to the original list
fruits.append(‘banana’)
print 'The fruits now are:', fruits
print 'My favourite fruits are', favourite_fruits
We do not make a copy of
the entire list, but we only
make a reference to it!
Copying lists
• How to make a full copy of a list?
• Various methods exist
– you can entirely slice a list
• favourite_fruits = fruits[:]
– you can create a new list from the existing one
• favourite_fruits = list(fruit)
– you can extend an empty list with the existing one
• favourite_fruits.extend(fruit)
• Prefer the list() method, when possible!
3/12/2015 Python basics 52
Dictionaries
• Similar to lists, but you can access values by
looking up a key instead of an index
– A key can be a string or a number
• Example
– A dictionary with 3 key-value pairs
dict = { ‘key1’ : 1, ‘key2’ : 2, ‘key3’ : 3 }
• Mutable, like lists
– They can be changed after their creation
3/12/2015 Python basics 53
Dictionaries: an example
3/12/2015 Python basics 54
# create a mapping of U.S. state to abbreviation
states = {
'Oregon' : 'OR',
'Florida' : 'FL',
'California' : 'CA'
}
print 'States:', states
print 'Is Oregon available?', 'Oregon' in states
# add some more states
states['New York'] = 'NY'
states['Michigan'] = 'MI'
# print two states
print "New York’s abbreviation is: ", states[‘New York’]
print "Florida’s abbreviation is: ", states[‘Florida’]
Create a dictionary with 3 key-value pairs
Add two more key-value pairs
More dictionaries
3/12/2015 Python basics 55
# states is a dictionary defined as before
# print every state abbreviation
for state, abbrev in states.items():
print "%s is abbreviated %s", % (state, abbrev)
# safely get an abbreviation of a state that might not be there
state = states.get('Texas', None) # None is the default
if not state:
print "Sorry, no Texas."
# get a state abbreviation with a default value
next_state = states.get('Massachusetts', 'Does Not Exist')
print "Massachusetts is abbreviated %s", % next_state
Dictionary functions
• len()
– dictionary length: the number of key-value pairs
• del()
– remove a key-value pair
• e.g., del my_dict[my_key]
• clear()
– remove all items from a dictionary
• keys() and values()
– return a copy of the dictionary’s list of key and value,
respectively
3/12/2015 Python basics 56
References and Links
• The Python Tutorial,
http://docs.python.org/2/tutorial/
• «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
• The Google Python course,
https://developer.google.com/edu/python
• Online Python Tutor, http://pythontutor.com
3/12/2015 Python basics 57
Questions?
01PRD AMBIENT INTELLIGENCE: TECHNOLOGY AND DESIGN
Luigi De Russis and Dario Bonino
luigi.derussis@polito.it
bonino@isbm.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/12/2015 Version Control with Git 59

Weitere ähnliche Inhalte

Was ist angesagt?

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-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming LanguageRohan Gupta
 
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
 
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
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginnersKálmán "KAMI" Szalai
 
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
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programmingDamian T. Gordon
 
Programming in Python
Programming in Python Programming in Python
Programming in Python Tiji Thomas
 
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 - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Twoamiable_indian
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2RajKumar Rampelli
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutesSidharth Nadhan
 

Was ist angesagt? (20)

Introduction to Python - Training for Kids
Introduction to Python - Training for KidsIntroduction to Python - Training for Kids
Introduction to Python - Training for Kids
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming Language
 
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
 
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
 
An introduction to Python for absolute beginners
An introduction to Python for absolute beginnersAn introduction to Python for absolute beginners
An introduction to Python for absolute beginners
 
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)
 
Basics of python 3
Basics of python 3Basics of python 3
Basics of python 3
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
 
Python for Beginners(v1)
Python for Beginners(v1)Python for Beginners(v1)
Python for Beginners(v1)
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python
PythonPython
Python
 
python.ppt
python.pptpython.ppt
python.ppt
 
Programming in Python
Programming in Python Programming in Python
Programming in Python
 
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)
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
Introduction to Python - Part Two
Introduction to Python - Part TwoIntroduction to Python - Part Two
Introduction to Python - Part Two
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
 
Python basic
Python basicPython basic
Python basic
 
Learn python in 20 minutes
Learn python in 20 minutesLearn python in 20 minutes
Learn python in 20 minutes
 

Andere mochten auch (20)

Python - basics
Python - basicsPython - basics
Python - basics
 
PythonIntro
PythonIntroPythonIntro
PythonIntro
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
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 Workshop
Python WorkshopPython Workshop
Python Workshop
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
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
 
Classification of computers
Classification of computersClassification of computers
Classification of computers
 
Introduction to Python Basics Programming
Introduction to Python Basics ProgrammingIntroduction to Python Basics Programming
Introduction to Python Basics Programming
 
Python 101
Python 101Python 101
Python 101
 
Classification of computers
Classification of computers Classification of computers
Classification of computers
 
Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)Mastering Python 3 I/O (Version 2)
Mastering Python 3 I/O (Version 2)
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
 

Ähnlich wie AmI 2015 - 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 WayUtkarsh Sengar
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdflailoesakhan
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methodsPranavSB
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in pythoneShikshak
 
Computer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptComputer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptRedenOriola
 
Brixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBrixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBasil Bibi
 

Ähnlich wie AmI 2015 - Python basics (20)

Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
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_class.pptx
python_class.pptxpython_class.pptx
python_class.pptx
 
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdfProgFund_Lecture_4_Functions_and_Modules-1.pdf
ProgFund_Lecture_4_Functions_and_Modules-1.pdf
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 
Functions, List and String methods
Functions, List and String methodsFunctions, List and String methods
Functions, List and String methods
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Python-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdfPython-Cheat-Sheet.pdf
Python-Cheat-Sheet.pdf
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Intro
IntroIntro
Intro
 
Computer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .pptComputer 10 Quarter 3 Lesson .ppt
Computer 10 Quarter 3 Lesson .ppt
 
P2 2017 python_strings
P2 2017 python_stringsP2 2017 python_strings
P2 2017 python_strings
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Brixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 RecapBrixton Library Technology Initiative Week0 Recap
Brixton Library Technology Initiative Week0 Recap
 
PEP 498: The Monologue
PEP 498: The MonologuePEP 498: The Monologue
PEP 498: The Monologue
 

Mehr von 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
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introductionLuigi De Russis
 
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
 
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
 
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
 
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
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introductionLuigi 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
 

Mehr von 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
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
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)
 
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
 
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...
 
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
 
Semantic Web: an introduction
Semantic Web: an introductionSemantic Web: an introduction
Semantic Web: an introduction
 
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
 

Kürzlich hochgeladen

Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
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
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 

Kürzlich hochgeladen (20)

Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
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
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

AmI 2015 - Python basics

  • 1. Python BASICS Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.
  • 2. Editing / Formatting • Python programs are text files • The end of a line marks the end of a statement • Comments: – Inline comments start with a # 3/12/2015 Python basics 2 print 1+1 #statement # inline comment
  • 3. Editing / Formatting • Code blocks are defined through identation – mandatory – 4 spaces strategy • Use 4 spaces for code identation • Configure the text editor to replace tabs with 4 spaces (default in PyDev) • Exploit automatic identation 3/12/2015 Python basics 3 def print_name(): # this is a block name = 'sheldon' surname = 'cooper' print name, surname 4 spaces 4 spaces 4 spaces 4 spaces
  • 4. Keywords • and • del • from • not • while • as • elif • global • or • with • assert • else • if • pass • yield • break • except • import • print • class • exec 3/12/2015 Python basics 4 • in • raise • continue • finally • is • return • def • for • lambda • try
  • 5. Numbers and math 3/12/2015 Python basics 5 Operator Description + plus Sum - minus Subtraction / slash Floor division * asterisk Multiplication ** double asterisk Exponentiation % percent Remainder < less-than Comparison > greater-than Comparison <= less-than-equal Comparison >= greater-than-equal Comparison
  • 6. Numbers and math 3/12/2015 Python basics 6 print "I will now count my chickens:" print "Hens", 25 + 30 / 6 print "Roosters", 100 - 25 * 3 % 4 print "Now I will count the eggs:" print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 print "Is it true that 3 + 2 < 5 - 7?" print 3 + 2 < 5 - 7 print "What is 3 + 2?", 3 + 2 print "What is 5 - 7?", 5 - 7 print "Oh, that's why it's False." print "How about some more." print "Is it greater?", 5 > -2
  • 7. Order of operations • PEMDAS – Parenthesis – Exponentiation – Multiplication – Division – Addition – Subtraction • Same precedence – Left to right execution 3/12/2015 Python basics 7
  • 8. Naming conventions • joined_lower – for functions, variables, attributes • joined_lower or ALL_CAPS – for constants • StudlyCaps – for classes 3/12/2015 Python basics 8 #variables my_variable = 12 my_second_variable = 'Hello!' #functions my_function(my_variable) my_print(my_second_variable)
  • 9. Variables • Variable types are not explicitly declared • Runtime type-checking • The same variable can be reused for holding different data types 3/12/2015 Python basics 9 #integer variable a = 1 print a #float variable a = 2.345 print a #re-assignment to string a = 'my name' print a # double quotes could be # used as well a = "my name" print a
  • 10. More variables • Actual type can be checked through the interpreter • Check the first result, what happened? • Display 01,010,01010 • Display 08 • Octal numbering system? 3/12/2015 Python basics 10
  • 11. Examples 3/12/2015 Python basics 11 cars = 100 space_in_a_car = 4.0 drivers = 30 passengers = 90 cars_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_per_car = passengers / cars_driven print 'There are', cars, 'cars available.' print 'There are only', drivers, 'drivers available.' print 'There will be', cars_not_driven, 'empty cars today.' print 'We can transport', carpool_capacity, 'people today.' print 'We have', passengers, 'to carpool today.' print 'We need to put about', average_passengers_per_car,'in each car.'
  • 12. Strings • Defined by using quotes – "first string" – 'second string' • Immutable • Each character in a string is assigned a number – the number is called index • Mathematical operators cannot be applied • Exceptions – + : means concatenation – * : means repetition 3/12/2015 Python basics 12
  • 13. Strings 3/12/2015 Python basics 13 name = 'Anthony "Tony" Stark' age = 45 # not a lie height = 174 # cm weight = 78 # kg eyes = 'brown' teeth = 'white' hair = 'brown' print "Let's talk about %s." % name print "He's %d cm tall." % height print "He's %d pounds heavy." % weight print "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (eyes, hair) print "His teeth are usually %s depending on the coffee." % teeth # this line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight)
  • 14. Strings 3/12/2015 Python basics 14 name = 'Anthony "Tony" Stark' age = 45 # not a lie height = 174 # cm weight = 78 # kg eyes = 'brown' teeth = 'white' hair = 'brown' print "Let's talk about %s." % name print "He's %d cm tall." % height print "He's %d pounds heavy." % weight print "Actually that's not too heavy." print "He's got %s eyes and %s hair." % (eyes, hair) print "His teeth are usually %s depending on the coffee." % teeth # this line is tricky, try to get it exactly right print "If I add %d, %d, and %d I get %d." % (age, height, weight, age + height + weight) Specifiers • %s, format strings • %d, format numbers • %r, raw representation Tuple
  • 15. More strings 3/12/2015 Python basics 15 x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s." % (binary, do_not) print x print y print "I said: %r." % x print "I also said: '%s'." % y hilarious = False joke_evaluation = "Isn't that joke so funny?! %r" print joke_evaluation % hilarious w = "This is the left side of..." e = "a string with a right side." print w + e
  • 16. Escape sequences • n – Line feed + Carriage return • – Prints a «» • We want to print «Hello» – print "I said: "Hello" " – Syntax error: no difference between quotes • Solution: using escape sequences – print "I said: “Hello" " 3/12/2015 Python basics 16
  • 17. Getting input from people • Asking questions – We want to ask the user’s age – We want to ask the user’s height • The raw_input()function allows to read from the console 3/12/2015 Python basics 17 print "How old are you?", age = raw_input() print "How tall are you?", height = raw_input() print "You are %s years old, and you are about %s cm tall." % (age, height)
  • 18. More input 3/12/2015 Python basics 18 height = int(raw_input("How tall are you? ")) name = raw_input("What's your name? ") print type(height) print type(name) print("Hello %s, you are about %d tall" %(name, height) )
  • 19. Command-line parameters • Python scripts can receive launch parameters – Placed just after the script name – Any number – Accessible through sys.argv • sys – Python module to handle system-level operations • argv – Argument variable – for handling command-line parameters 3/12/2015 Python basics 19
  • 20. Command-line parameters 3/12/2015 Python basics 20 from sys import argv script, first, second, third = argv print 'The script is called:', script print 'Your first variable is:', first print 'Your second variable is:', second print 'Your third variable is:', third
  • 21. Functions • A function is a named sequence of statements that performs a computation – Definition first: • specify the name and the sequence of statements – Then usage: • “call” the function by name • Examples – Type conversion functions • int(‘32’)  32 • str(3.2479)  ‘3.2479’ 3/12/2015 Python basics 21
  • 22. Math functions • Located in the math module 3/12/2015 Python basics 22 import math signal_power = 10.0 noise_power = 0.01 ratio = signal_power / noise_power print "ratio:", ratio decibels = 10 * math.log10(ratio) print "decibels:", decibels radians = 0.7 height = math.sin(radians) print height Function call
  • 23. String functions • len() – Gets the length (the number of characters) of a string • lower() – Gets rid of all the capitalization in a string • upper() – Transform a string in upper case • str() – Transform «everything» in a string 3/12/2015 Python basics 23
  • 24. String functions: an example 3/12/2015 Python basics 24 course_name = 'Ambient Intelligence' string_len = len(course_name) print string_len # 20 print course_name.lower() # ambient intelligence print course_name.upper() # AMBIENT INTELLIGENCE pi = 3.14 print "the value of pi is around " + str(pi) without str() it gives an error
  • 25. New functions • Can be defined by developers • Typically used to group homogeneous code portions – i.e., code for accomplishing a well-defined operation • Enable re-use – Same operation can be re-used several times • Defined using the keyword def 3/12/2015 Python basics 25
  • 26. New functions 3/12/2015 Python basics 26 • Compute the area of a disk, given the radius import math def circle_area(radius): return radius**2*math.pi radius = raw_input('Please, insert the radiusn') print 'Radius: ', radius print 'Area: ', circle_area(radius) Function call Function definition
  • 27. Docstring • Optional, multiline comment • Explains what the function does • Starts and ends with """ or ''' 3/12/2015 Python basics 27 import math def circle_area(radius): '''Compute the circle area given its radius''' return radius**2*math.pi radius = raw_input('Please, insert the radiusn') print 'Radius: ', radius print 'Area: ', circle_area(radius)
  • 28. Modules • 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 module math resides in a file named math.py • We already met them 3/12/2015 Python basics 28 import math from sys import argv
  • 29. Importing modules • import module_name – allows to use all the items present in a module 3/12/2015 Python basics 29 import math def circle_area(radius): return radius**2*math.pi … Import the math module Call the pi variable from the math module
  • 30. Importing modules • from module_name import name – it only imports name from the specified module • from module_name import * – it imports all names from a module – do not use! 3/12/2015 Python basics 30 from math import pi def circle_area(radius): return radius**2*pi … Import pi from the math module Use the pi variable
  • 31. Playing with files • Python script can read and write files • First, open a file – You can use the open() function • Then, you can read or write it – With read(), readline(), or write() • Finally, remember to close the file – You can use the close() function 3/12/2015 Python basics 31
  • 32. Reading files • Read a file taking its name from command line 3/12/2015 Python basics 32 from sys import argv filename = argv[1] txt = open(filename) print “Here’s your file %r:", % filename print txt.read() print “nType the filename again:” file_again = raw_input(“> ”) txt_again = open(file_again) print txt_again.read() Open the file Show the file content
  • 33. Writing files 3/12/2015 Python basics 33 from sys import argv script, filename = argv print "We're going to erase %r." % filename print "Opening the file..." target = open(filename, 'w') print "… truncating the file. Goodbye!" target.truncate() print "nNow I'm going to ask you for two lines." line1 = raw_input("line 1: ") line2 = raw_input("line 2: ") print "I'm going to write these to the file." target.write(line1) target.write("n") target.write(line2) target.write("n") print "And finally, we close it." target.close() Open the file in write mode Empties the file Write a string to the file
  • 34. Conditionals and control flow • Control flow gives the ability to choose among outcomes – based off what else is happening in the program • Comparators – Equal to  == – Not equal to  != – Less than  < – Less than or equal to  <= – Greater than  > – Greater than or equal to  >= 3/12/2015 Python basics 34
  • 35. Comparators: an example 3/12/2015 Python basics 35 print 2 == 1 # False print 2 == 2 # True print 10 >= 2 # True print 2 < 10 # True print 5 != 5 # False print 'string' == "string" # True number = 123 print number > 100 # True
  • 36. Boolean operators • They are three: – not – and – or • Not evaluated from left to right – not is evaluated first – and is evaluated next – or is evaluated last 3/12/2015 Python basics 36
  • 37. Boolean operators: an example 3/12/2015 Python basics 37 print 2 == 1 and True # False print 2 == 2 or True # True print 10 >= 2 and 2 != 1 # True print not True # False print 10 > 5 and 10 == 10 or 5 < 2 # True print not False and True # True
  • 38. Conditional statement • if is a statements that executes some code after checking if a given expression is True • Structure if expression: do something 3/12/2015 Python basics 38 people = 20 cats = 30 if people < cats: print 'Too many cats! The world is doomed!' if people > cats: print 'Not many cats! The world is saved!'
  • 39. More “if” • Let’s try to “improve” the previous example • Chained conditionals – To express more than two possibilities – Each condition is checked in order 3/12/2015 Python basics 39 people = 20 cats = 30 if people < cats: print 'Too many cats! The world is doomed!' elif people > cats: print 'Not many cats! The world is saved!' else: print "We can’t decide.” else if
  • 40. Loops and lists • Loop – An easy way to do repetitive things – A condition to start and stop the loop is required – e.g., for and while loops • List – A datatype for storing multiple items • a sequence of values – You can assign items to a list in this way: list_name = [item1, item2, …] 3/12/2015 Python basics 40
  • 41. Loops and lists: an example 3/12/2015 Python basics 41 the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print 'This is count %d' % number # same as above for fruit in fruits: print 'A fruit of type: %s' % fruit # we can go through mixed lists too # notice that we have to use %r since we don't know what's in it for i in change: print 'I got %r' % i Three lists
  • 42. Loops and lists: an example 3/12/2015 Python basics 42 the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print 'This is count %d' % number # same as above for fruit in fruits: print 'A fruit of type: %s' % fruit # we can go through mixed lists too # notice that we have to use %r since we don't know what's in it for i in change: print 'I got %r' % i Structure of a for loop • for variable in collection: • indent for the loop body
  • 43. More “for” 3/12/2015 Python basics 43 # we can also build lists: start with an empty one… elements = [] # then use the range function to do 0 to 5 counts for i in range(0, 6): print 'Adding %d to the list.' % i # append() is a function that lists understand elements.append(i) # now we can print them out for i in elements: print 'Element was: %d' % i Empty list Repeat 6 times
  • 44. Lists • Mutable • Do not have a fixed length – You can add items to a list at any time • Accessible by index 3/12/2015 Python basics 44 letters = [‘a’, ‘b’, ‘c’] letters.append(‘d’) print letters # a, b, c, d print letters[0] # a print len(letters) # 4 letters[3] = ‘e’ print letters # a, b, c, e
  • 45. More lists • List concatenation – with the + operator • List slices – to access a portion of a list – with the [:] operator 3/12/2015 Python basics 45 a = [1, 2, 3] b = [4, 5, 6] c = a + b print c # 1, 2, 3, 4, 5, 6 c = [1, 2, 3, 4, 5, 6] d = c[1:3] # d is [2, 3] e = c[:3] # e is [1, 2, 3] f = c[:] # f is a full copy of c
  • 46. More lists • List concatenation – with the + operator • List slices – to access a portion of a list – with the [:] operator 3/12/2015 Python basics 46 a = [1, 2, 3] b = [4, 5, 6] c = a + b print c # 1, 2, 3, 4, 5, 6 c = [1, 2, 3, 4, 5, 6] d = c[1:3] # d is [2, 3] e = c[:3] # e is [1, 2, 3] f = c[:] # f is a full copy of c works with string, too
  • 47. List functions • append() – add a new element to the end of a list – e.g., my_list.append(‘d’) • sort() – arrange the elements of the list from low to high – e.g., from a to z, from 1 to infinite, etc. • extend() – takes a list as an argument and appends all its elements – e.g., first_list.extend(second_list) 3/12/2015 Python basics 47
  • 48. Deleting elements from a list • Several ways to delete elements from a list • If you know the index of the element to remove: pop() – without providing an index, pop() delete the last element • If you know the element to remove (but not the index): remove() • To remove more than one element: del() – with a slice index • e.g., del my_list[5:8] 3/12/2015 Python basics 48
  • 49. Strings vs. lists • A string is a sequence of character, but a list of character is not a string • To convert a string into a list of characters: list() – e.g., my_list = list(my_string) • To break a string into separate words: split() – split a list according to some delimiters (default: space) – e.g., my_list = my_string.split() – The inverse function is join() 3/12/2015 Python basics 49
  • 50. Copying lists • What happens here? 3/12/2015 Python basics 50 fruits = ['apple', 'orange', 'pear', 'apricot'] print 'The fruits are:', fruits favourite_fruits = fruits print 'My favourite fruits are', favourite_fruits # add a fruit to the original list fruits.append(‘banana’) print 'The fruits now are:', fruits print 'My favourite fruits are', favourite_fruits
  • 51. Copying lists • What happens here? 3/12/2015 Python basics 51 fruits = ['apple', 'orange', 'pear', 'apricot'] print 'The fruits are:', fruits favourite_fruits = fruits print 'My favourite fruits are', favourite_fruits # add a fruit to the original list fruits.append(‘banana’) print 'The fruits now are:', fruits print 'My favourite fruits are', favourite_fruits We do not make a copy of the entire list, but we only make a reference to it!
  • 52. Copying lists • How to make a full copy of a list? • Various methods exist – you can entirely slice a list • favourite_fruits = fruits[:] – you can create a new list from the existing one • favourite_fruits = list(fruit) – you can extend an empty list with the existing one • favourite_fruits.extend(fruit) • Prefer the list() method, when possible! 3/12/2015 Python basics 52
  • 53. Dictionaries • Similar to lists, but you can access values by looking up a key instead of an index – A key can be a string or a number • Example – A dictionary with 3 key-value pairs dict = { ‘key1’ : 1, ‘key2’ : 2, ‘key3’ : 3 } • Mutable, like lists – They can be changed after their creation 3/12/2015 Python basics 53
  • 54. Dictionaries: an example 3/12/2015 Python basics 54 # create a mapping of U.S. state to abbreviation states = { 'Oregon' : 'OR', 'Florida' : 'FL', 'California' : 'CA' } print 'States:', states print 'Is Oregon available?', 'Oregon' in states # add some more states states['New York'] = 'NY' states['Michigan'] = 'MI' # print two states print "New York’s abbreviation is: ", states[‘New York’] print "Florida’s abbreviation is: ", states[‘Florida’] Create a dictionary with 3 key-value pairs Add two more key-value pairs
  • 55. More dictionaries 3/12/2015 Python basics 55 # states is a dictionary defined as before # print every state abbreviation for state, abbrev in states.items(): print "%s is abbreviated %s", % (state, abbrev) # safely get an abbreviation of a state that might not be there state = states.get('Texas', None) # None is the default if not state: print "Sorry, no Texas." # get a state abbreviation with a default value next_state = states.get('Massachusetts', 'Does Not Exist') print "Massachusetts is abbreviated %s", % next_state
  • 56. Dictionary functions • len() – dictionary length: the number of key-value pairs • del() – remove a key-value pair • e.g., del my_dict[my_key] • clear() – remove all items from a dictionary • keys() and values() – return a copy of the dictionary’s list of key and value, respectively 3/12/2015 Python basics 56
  • 57. References and Links • The Python Tutorial, http://docs.python.org/2/tutorial/ • «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 • The Google Python course, https://developer.google.com/edu/python • Online Python Tutor, http://pythontutor.com 3/12/2015 Python basics 57
  • 58. Questions? 01PRD AMBIENT INTELLIGENCE: TECHNOLOGY AND DESIGN Luigi De Russis and Dario Bonino luigi.derussis@polito.it bonino@isbm.it
  • 59. 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/12/2015 Version Control with Git 59