python - elite.polito.it · 06/03/19 python basics 72 •a way to logically organize the code...

79
Python BASICS Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.

Upload: others

Post on 19-Jul-2020

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

PythonBASICS

Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.

Page 2: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Identikit

• First appeared in 1991• Designed by Guido van Rossum• General purpose• High level• Emphasis on code readability and conciseness• Website– http://www.python.org

• We will use Python 3– not Python 2

06/03/19 Python basics 2

Page 3: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

#include <stdio.h>

int main(){

printf("Hello, world!");return 0;

}

06/03/19 Python basics 3

Page 4: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

print("Hello, world!")

06/03/19 Python basics 4

Page 5: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

# this will print "Hello, world!"print("Hello, world!")

06/03/19 Python basics 5

inline comment

Page 6: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Keywords

• and • del • from • not • while• as• elif• global• or• with

• assert • else • if • pass • yield• break • except • import • class • exec

06/03/19 Python basics 6

• in • raise• continue • finally • is • return• def• for • lambda • try

Page 7: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Variables

06/03/19 Python basics 7

language_name = "Python"

naming convention: joined_lower

this is a string

Page 8: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Variables

06/03/19 Python basics 8

language_name = "Python"version = '3.7.0'introduced = 1991is_awesome = True

Page 9: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Type Inference

06/03/19 Python basics 9

language_name = "Python" # stringversion = '3.7.0' # another stringintroduced = 1991 # integeris_awesome = True # boolean

actual type can be checked with type()

play_with_types.py

Page 10: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

String

06/03/19 Python basics 10

some_string = "I'm a string"

another_string = 'I'm a string, too'

Page 11: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

String

06/03/19 Python basics 11

some_string = "I'm a string"

another_string = 'I'm a string, too'# SyntaxError: invalid syntax

Page 12: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

String

06/03/19 Python basics 12

another_string = 'I am a string, too'

another_strig = 'I\'m a string, too'

escape sequence

Page 13: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

String

06/03/19 Python basics 13

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.'''

Page 14: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

If Statement

06/03/19 Python basics 14

people = 20cats = 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

Page 15: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

If Statement

06/03/19 Python basics 15

people = 20cats = 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.")

Page 16: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Comparators and Booleans Operators

06/03/19 Python basics 16

print(2 == 1)

print('string' == "string")

print(not False)

print(2==1 and True)

print(2==1 or True)

Page 17: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Comparators and Booleans Operators

06/03/19 Python basics 17

print(2 == 1) # False

print('string' == "string") # True

print(not False) # True

print(2==1 and True) # False

print(2==1 or True) # True

Page 18: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Characters

06/03/19 Python basics 18

for char in "hello":print(char)

hello

Page 19: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Characters

06/03/19 Python basics 19

say_hello = "hello!"print(say_hello[1])

e

index

Page 20: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Characters

06/03/19 Python basics 20

say_hello = "hello!"print(type(say_hello[1]))

<class 'str'>

Page 21: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Combining Strings

06/03/19 Python basics 21

language_name = "Python"version = '3.7.0'

python_version = language_name + version# python_version is Python3.7.0

print("my " + "name") # my name

concatenation

Page 22: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Combining Strings

06/03/19 Python basics 22

language_name = "Python"

a_lot_of_python = language_name*3# a_lot_of_python is PythonPythonPython

repetition

Page 23: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Building Complex Strings

06/03/19 Python basics 23

a = 3b = 5

# 3 times 5 is 15print(a, "times", b, "is", a*b)

works with print(), only

Page 24: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Building Complex Strings

06/03/19 Python basics 24

a = 3b = 5

# 3 times 5 is 15result = a + " times " + b + " is " + a*b

Page 25: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Building Complex Strings

06/03/19 Python basics 25

a = 3b = 5

# 3 times 5 is 15result = a + " times " + b + " is " + a*b#TypeError: unsupported operand type(s)

Page 26: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Building Complex Strings

06/03/19 Python basics 26

a = 3b = 5

# 3 times 5 is 15result = str(a) + " times " + str(b) + " is " + str(a*b)

Page 27: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

String Interpolation

06/03/19 Python basics 27

a = 3b = 5

# 3 times 5 is 15result = "%d times %d is %d" %(a, b, a*b)

Specifiers• %s, format strings• %d, format numbers• %r, raw representation

tuplespecifiers.py

Page 28: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

String Interpolation

06/03/19 Python basics 28

a = 3b = 5

# 3 times 5 is 15result = "{} times {} is {}".format(a, b, a*b)

new way!

Page 29: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

String Immutability

06/03/19 Python basics 29

# hellosay_hello = "helko"

# ops…say_hello[3] = "l"

Page 30: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

String Immutability

06/03/19 Python basics 30

# hellosay_hello = "helko"

# ops…say_hello[3] = "l"# TypeError

Page 31: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

String Immutability

06/03/19 Python basics 31

# hellosay_hello = "helko"

# ops…say_hello = "hello"

Other operations with strings? Python docs

Page 32: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Getting Input

06/03/19 Python basics 32

print("How old are you?")age = input() # age is a string

print("You are " + age + " years old")

Page 33: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Getting Input

06/03/19 Python basics 33

print("How old are you?")age = input() # age is a string

print("You are " + age + " years old")

# I want "age" to be a number!age = int(input())

Page 34: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Getting Input

06/03/19 Python basics 34

age = input("How old are you? ")

print("You are " + age + " years old")

Page 35: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

List

06/03/19 Python basics 35

fruits = ["apples", "oranges", "pears"]count = [1, 2, 3, 4, 5]change = [1, "pennies", 2, "dimes"]

a datatype to store multiple items, in sequence

Page 36: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Dictionary

06/03/19 Python basics 36

legs = {"ant": 6, "snake": 0, "cow": 4}states = {"Italy": "IT", "Germany": "DE"}

a datatype to store multiple items, not in sequence

key, immutable

value

Page 37: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Loops

06/03/19 Python basics 37

doctor = 1

while doctor <= 13:exterminate(doctor)doctor += 1

Page 38: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

For Loop: Strings

06/03/19 Python basics 38

for char in "hello":print(char)

hello

Page 39: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

For Loop: Ranges

06/03/19 Python basics 39

for number in range(0,5):print(number)

01234

Page 40: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

For Loop: Ranges

06/03/19 Python basics 40

for number in range(0,25,5):print(number)

05101520

Page 41: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

For Loop: Lists

06/03/19 Python basics 41

fruits = ["apples", "oranges", "pears"]

for fruit in fruits:print("I love", fruit)

I love applesI love orangesI love pears

Page 42: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

For Loop: Dictionaries

06/03/19 Python basics 42

legs = {"ant": 6, "snake": 0, "cow": 4}

for (animal, number) in legs.items():print("{} has {} legs".format(animal,

number))

ant has 6 legssnake has 0 legscow has 4 legs

Page 43: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Printing a List

06/03/19 Python basics 43

to_buy = ["eggs", "milk"]print(to_buy)

['eggs', 'milk']

Page 44: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Printing a List

06/03/19 Python basics 44

to_buy = ["eggs", "milk"]print(to_buy[0])

eggs

Page 45: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a List

06/03/19 Python basics 45

to_buy = ["eggs", "milk"]print(to_buy[0])

to_buy[0] = "butter"print(to_buy[0])

eggs

butter

Page 46: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a List

06/03/19 Python basics 46

to_buy = ["eggs", "milk"]

# I need to buy chocolate!to_buy.append("chocolate")

['eggs', 'milk', 'chocolate']

Page 47: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a List

06/03/19 Python basics 47

to_buy = ["eggs", "milk"]to_buy.append("chocolate")

to_buy.extend(["flour", "cheese"])

['eggs', 'milk', 'chocolate', 'flour', 'cheese']

Page 48: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a List

06/03/19 Python basics 48

to_buy = ["eggs", "milk"]to_buy.append("chocolate")

to_buy = to_buy + ["flour", "cheese"]

['eggs', 'milk', 'chocolate', 'flour', 'cheese']

concatenation

Page 49: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a List

06/03/19 Python basics 49

to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"]

print(to_buy[1:3])

['milk', 'chocolate']

slice operator

Page 50: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a List

06/03/19 Python basics 50

to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"]

# make a full copy of the listremember = to_buy[:]

works with strings, too

Page 51: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a List

06/03/19 Python basics 51

to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"]

# I don't need cheese!to_buy.pop()

# … neither milk, by the way!to_buy.pop(1)

Page 52: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a List

06/03/19 Python basics 52

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")

Page 53: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a List

06/03/19 Python basics 53

to_buy = ["eggs", "milk", "chocolate", "flour", "cheese"]

# I want my original list back!del to_buy[2:6]

['eggs', 'milk']

Page 54: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Strings vs. Lists

06/03/19 Python basics 54

A string is a sequence of characters…… but a list of characters is not a string

language_name = "Python"

# string to listname = list(language_name)

Page 55: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Strings vs. Lists

06/03/19 Python basics 55

sentence = "this is AmI"

# break a string into separate wordswords = sentence.split()

['this', 'is', 'AmI']

Page 56: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Copying Lists

06/03/19 Python basics 56

fruits = ['apple', 'orange']favorite_fruits = fruits

# add a fruit to the original listfruits.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'] ???

Page 57: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Copying Lists

06/03/19 Python basics 57

fruits = ['apple', 'orange']favorite_fruits = fruits

# add a fruit to the original listfruits.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!

Page 58: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Copying Lists (For Real!)

06/03/19 Python basics 58

# option 1: slicefavorite_fruits = fruits[:]

#option 2: create a new list - best!favorite_fruits = list(fruit)

#extend an empty listfavorite_fruits.extends(fruit)

Other operations with lists? Python docs

Page 59: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Printing a Dictionary

06/03/19 Python basics 59

legs = {"ant": 6, "snake": 0 }print(legs)

{'ant': 6, 'snake': 0}

Page 60: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a Dictionary

06/03/19 Python basics 60

legs = {"ant": 6, "snake": 0 }legs["spider"] = 273

{'ant': 6, 'snake': 0, 'spider': 273}

Page 61: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a Dictionary

06/03/19 Python basics 61

legs = {"ant": 6, "snake": 0 }legs["spider"] = 273 # basically, run!legs["spider"] = 8 # better!

{'ant': 6, 'snake': 0, 'spider': 8}

Page 62: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modifying a Dictionary

06/03/19 Python basics 62

legs = {"ant": 6, "snake": 0, "spider": 8}

# I don't like spidersdel legs["spider"]

# Clear all the things!legs.clear()

Page 63: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Retrieving a Value from a Dictionary

06/03/19 Python basics 63

legs = {"ant": 6, "snake": 0}

# get "ant"!legs["ant"] # 6

# get "spider"legs["spider"]

Page 64: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Retrieving a Value from a Dictionary

06/03/19 Python basics 64

legs = {"ant": 6, "snake": 0}

# get "ant"!legs["ant"] # 6

# get "spider"legs["spider"]# KeyError: spider

Page 65: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Retrieving a Value from a Dictionary

06/03/19 Python basics 65

legs = {"ant": 6, "snake": 0}

# check if "spider" is in the dictionary"spider" in legs # False

# get "spider" without throwing errorslegs.get("spider") # None

# get "spider" with a custom valuelegs.get("spider", "Not present")

Page 66: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Functions

06/03/19 Python basics 66

def say_hello():print("Hello!")

say_hello()

definition

call

Page 67: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Functions with Parameters

06/03/19 Python basics 67

def say_hello_to(name):print("Hello", name)

say_hello_to("AmI students")

Page 68: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Default Parameter Values

06/03/19 Python basics 68

def say_hello_to(name="AmI"):print("Hello", name)

say_hello_to() # Hello AmI

say_hello_to("students") # Hello students

Page 69: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Returning Values

06/03/19 Python basics 69

def build_greetings(name="AmI"):return "Hello" + name

greeting = build_greetings()print(greeting) # Hello AmI

Page 70: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Returning Multiple Values

06/03/19 Python basics 70

def build_greetings(name="AmI"):return ("Hello", name)

(greeting, person) = build_greetings()print(greeting + " to " + person)# Hello to AmI

Page 71: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Documenting Functions

06/03/19 Python basics 71

def build_greetings(name="AmI"):'''Build a greeting in the format

Hello plus a given name'''return ("Hello", name)

docstring

Page 72: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Modules

06/03/19 Python basics 72

• 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

Page 73: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Importing a Module

06/03/19 Python basics 73

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

Page 74: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Command Line Parameters

06/03/19 Python basics 74

from sys import argv

script, first = argv

print("The script is called:", script)print("The parameter is:", first)

> python my_script.py oneThe script is called: my_script.pyThe parameter is: one

unpacking

Page 75: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Reading Files

06/03/19 Python basics 75

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

Page 76: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Writing Files

06/03/19 Python basics 76

from sys import argv

filename = argv[1]# open in write mode and empty the file target = open(filename, "w")

# write a string into the filetarget.write("This is the new content")

target.close() # close the file

Page 77: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

References and Links

• Python Documentation, http://docs.python.org/3• The Python Tutorial,

http://docs.python.org/3/tutorial/• Online Python Tutor, http://pythontutor.com• «Think Python: How to think like a computer

scientist», 2nd edition, Allen Downey, Green Tea Press, Needham, Massachusetts

• «Dive into Python 3», Mark Pilgrim

• «Learning Python» (5th edition), Mark Lutz, O'Reilly

06/03/19 Python basics 77

Page 78: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

Questions?01QZP AMBIENT INTELLIGENCE

Luigi De Russis

[email protected]

Page 79: Python - elite.polito.it · 06/03/19 Python basics 72 •A way to logically organize the code •They are files consisting of Python code –they can define (and implement) functions,

License• This work is licensed under the Creative Commons “Attribution-

NonCommercial-ShareAlike Unported (CC BY-NC-SA 4.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 https://creativecommons.org/licenses/by-nc-sa/4.0/

06/03/19 Python basics 79