Ptikka.mbnet.fi



Lyhyt ja ytimek?s Python-opas, Pauli Tikka, 17.1.17-21.2.17Sis?llys TOC \o "1-3" \h \z \u Perusteet PAGEREF _Toc475357516 \h 2Atomissa PAGEREF _Toc475357517 \h 2Powershelliss? tai Geany:ss? PAGEREF _Toc475357518 \h 2Peruskomentoja PAGEREF _Toc475357519 \h 2Jos ohjelma sis?lt?? ”argv:n” niin lis?-arvot laitetaan seuraavasti PAGEREF _Toc475357520 \h 3N?yt? tiedosta v?h?n PAGEREF _Toc475357521 \h 3Python -ajo-ohjelman l?yt?minen ja sulkeminen Powershelliss?: PAGEREF _Toc475357522 \h 3Koodaus, Tekstink?sittely- ja ajo-ohjelmassa PAGEREF _Toc475357523 \h 4Koodi-1, sanakirjoista PAGEREF _Toc475357524 \h 4Koodin 1 ajo PAGEREF _Toc475357525 \h 4Koodi-2, sanakirjan sanat for loopille PAGEREF _Toc475357526 \h 4Koodin 2 ajo: PAGEREF _Toc475357527 \h 4Koodi-3, while looppi laskussa ja if lause PAGEREF _Toc475357528 \h 4Koodin-3 ajo PAGEREF _Toc475357529 \h 4Koodi-4, funktio ja positionaaliset argumentit PAGEREF _Toc475357530 \h 5Koodin-4 ajo PAGEREF _Toc475357531 \h 5Koodi-5, moduli-tiedoston funktiot ja ohjelmatiedoston funktiohaut arvoineen PAGEREF _Toc475357532 \h 5Koodin-5 ajo PAGEREF _Toc475357533 \h 5Koodi-6, luokan teko PAGEREF _Toc475357534 \h 6Koodin 6 ajo PAGEREF _Toc475357535 \h 6Koodi 7, tiedoston kanssa leikkiminen PAGEREF _Toc475357536 \h 6Koodin 7 ajo PAGEREF _Toc475357537 \h 6Koodi 8, tiedoston kanssa leikkiminen, osa2 PAGEREF _Toc475357538 \h 7Koodin 8 ajo PAGEREF _Toc475357539 \h 7Koodi 9, tiedoston luonti ja kirjoitus PAGEREF _Toc475357540 \h 7Koodin 9 ajo PAGEREF _Toc475357541 \h 7Koodi 10, usean tiedoston analysointi PAGEREF _Toc475357542 \h 7Koodin 10 ajo PAGEREF _Toc475357543 \h 7Koodi 11, plottaus ja looppi PAGEREF _Toc475357544 \h 8Koodin 11 ajo PAGEREF _Toc475357545 \h 8Koodi 12, random-k?velyn (rmk) plottaus PAGEREF _Toc475357546 \h 8Koodin 12 ajo PAGEREF _Toc475357547 \h 9Koodi 13, nopat tiedostot: C:\Python34\harkat PAGEREF _Toc475357548 \h 10Koodin 13 ajo, k?ytet??n geany –ohjelmaa, valmiina run PAGEREF _Toc475357549 \h 11Koodi 14, datan tuonti ulkosesta l?hteest? PAGEREF _Toc475357550 \h 11Koodin 14 ajo (geniess?) PAGEREF _Toc475357551 \h 12Koodi 15, lis?? datan tuontia ja analysointia PAGEREF _Toc475357552 \h 12Koodin 15 ajo (geanyss?) PAGEREF _Toc475357553 \h 13Python filosofointia PAGEREF _Toc475357554 \h 13PerusteetMit? tarvitaan python koodailuun?Koodin kirjoitusohjelma, joku kehittynyt tekstink?sittelyohjelma, kuten Atom. Koodin ajo-ohjelma, voi tehd? ’komentokehote’, PowerShell alias DOS, –ohjelmissa, mutta graaffinen ajo-ohjelma on selke?mpi, esim. Geany. Pythonin perusasennuksessa toimii parhaiten Powershell ja j?rjestelm? muuttujien lis?ys windowsisa. Googletuksen j?lkeen lataa ja asenna graaffinen ajo-ohjelma sek? tekstink?sittelyohjelma. ”Python crash course” (Eric Matthes, 2016) -kirjassa hyv?t ohjeet asennuksiin ja perusk?ytt??n. Kannattaa olla uusin python versio ellei joku spesifinen juttusi vaadi muuta, jos et varma, niin uusin.AtomissaKaksoisklikkaa Windows-ikonia p??st?ksesi ohjelmaan.Kirjoita ohjelmasi t?ydess? loistossaan python-kielell? t?ss? ohjelmassa teksti-tyyppisesti ja tallenna nimell? ja muodossa xyz.py. Powershelliss? tai Geany:ss?Kaksoisklikkaa Windows-ikonia p??st?ksesi ohjelmaan.Aja Atomissa tekem?si ohjelmasi suoraan Geany:ss? klikkaamalla ’suorita’ tai Powershelliss? kirjoittamalla python hakemistossasi, esim. C:\python27\harkat python xyz.py (ja paina enter). Varmista, ett? kaikki tarvittavat tiedostot ovat samassa kansiossa ja ohjelmien n?kyviss?.Peruskomentojamkdir hei -> tekee tiedoston hei (t?st? l?htien oletan, ett? komennot tulee vahvistaa enterill?)cd hei -> siirt?? sinut tiedostoon heiAjaaksesi ohjelman ex1.py kirjoita Poweshellin komentokehotteessa:C:\python27\harkat> python ex1.py Jos ohjelma sis?lt?? ”argv:n” niin lis?-arvot laitetaan seuraavastiC:\python27\harkat> python ex13.py pauli ratkaisi kiitosThe script is called: ex13.pyYour first variable is: pauliYour second variable is: ratkaisiYour third variable is: kiitosMuuta ajoa: python ex17.py test.txt new_file.txtpython -m pydoc raw_input # pydoc - -m = manual, pydoc=the Python documentation toolN?yt? tiedosta v?h?nPS C:\python27\harkat> cat test.txtTama on elamaa parhaimmillaan, eiko?Kylla, tasta vaan sitten eteenpain!Jee!!!tee pikkutiedosto:echo "This is a test file." > test.txtPython -ajo-ohjelman l?yt?minen ja sulkeminen Powershelliss?: Pikku python ohjelmat voi ajaa python -ajo-ohjelmassa, jonne p??set kirjoittamalla Powerhsellin oikeassa hakemistossa ”python” (+enter) ja sielt? pois kirjoittamalla quit(): PS C:\python27\harkat> pythonPython 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win3Type "help", "copyright", "credits" or "license" for more information.>>> , esim.:>>> cars=['bmw','audi','toyota','subaru']>>> len(cars)ja>>> quit()PS C:\python27\harkat>ja edelleen>>> print 7/41>>> print "test2, tarkka", 7.0/4.0test2, tarkka 1.75Koodaus, Tekstink?sittely- ja ajo-ohjelmassaKoodi-1, sanakirjoistaalien_0 = {'color': 'green', 'points': 5} #’ color’ on avain (key) ja ‘green’ on arvo (value)print(alien_0['color'])print(alien_0['points'])Koodin 1 ajoPS C:\python27\harkat> python alien.pygreen5Koodi-2, sanakirjan sanat for loopillefavorite_languages = {'jen': 'python','sarah': 'c','edward': 'ruby','phil': 'python'}for name, language in favorite_languages.items(): print (name.title() + "'s favorite language is " + language.title() + ".")Koodin 2 ajo:PS C:\python27\harkat> python favorite_languages.pySarah's favorite language is C.Edward's favorite language is Ruby.Jen's favorite language is Python.Phil's favorite language is Python. #huom. kielten j?rjestys… Koodi-3, while looppi laskussa ja if lausecurrent_number = 0while current_number < 10: current_number += 1 if current_number % 2 == 0: continueprint(current_number)Koodin-3 ajoPS C:\python27\harkat> python counting.p13579Koodi-4, funktio ja positionaaliset argumentitdef describe_pet(animal_type, pet_name): #def:n j?lkeen tulee funktio nimelt??n “describe_pet” """Display information about a pet.""" print("\nI have a " + animal_type + ".")#koodin teht?v? on printata infoa el?imist? print("My " + animal_type + "'s name is " + pet_name.title() + ".")describe_pet('hamster','harry') #“el?in” ja ”nimi” ovat positionaaliset argumentit funktiossadescribe_pet('dog', 'willie')Koodin-4 ajoPS C:\python27\harkat> python pets.pyI have a hamster.My hamster's name is Harry.I have a dog.My dog's name is Willie.Koodi-5, moduli-tiedoston funktiot ja ohjelmatiedoston funktiohaut arvoineenModuli –tiedosto, abc.py, esim. pizza.pydef make_pizza(*toppings):#funktio on nyt nimelt??n make_pizza """Summarize the pizza with the following toppings.""" print("\nMaking a pizza with the following toppings:") for topping in toppings:#t?ss? se for looppi print("- " + topping)make_pizza('pepperoni')# n?it? kutsutaan ”arbitary” argumenteiksimake_pizza('mushrooms', 'green peppers', 'extra cheese')Ohjelma/ajo –tiedosto, xyz.py, esim. making_pizza.pyfrom pizza import make_pizza #funktion make_pizza haku moduli –tiedostosta pizza.pymake_pizza(16, 'pepperoni')make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')Koodin-5 ajoPS C:\python27\harkat> python making_pizza.py #huom.! ajetaan vain ohjelma/ajo –tiedostolla!!Making a 16-inch pizza with the following toppings:- pepperoniMaking a 12-inch pizza with the following toppings:- mushrooms- green peppers- extra cheeseKoodi-6, luokan tekoLuokka –tiedosto (class file)class Dog(object): """A simple attempt to model a dog.""" def __init__(self, name, age) #funktiota nimitet??n luokan alla metodiksi, method; _,_ kaksi kpl! """Initialize name and age attributes.""" self.name = name# self.name:a nimitet??n atribuutiksi (attribute) self.age = age def sit(self): """Simulate a dog sitting in response to a command.""" print(self.name.title() + " is now sitting.") def roll_over(self): """Simulate rolling over in response to a command.""" print(self.name.title() + " rolled over!")my_dog = Dog('willie', 3) #my_dog:in ja your_dogi:in nimitys on luokan instanssi ‘instance’your_dog = Dog('lucy', 3)print("My dog's name is " + my_dog.name.title() + ".") #t?ss? alla teht?v?t ko. instansseilleprint("My dog is " + str(my_dog.age) + " years old.")my_dog.sit()my_dog.roll_over()print("My dog's name is " + your_dog.name.title() + ".")print("My dog is " + str(your_dog.age) + " years old.")your_dog.sit()your_dog.roll_over()Koodin 6 ajoPS C:\python27\harkat> python dog.py #luokka –tiedostossa voi olla sek? metodit, ett? ’ajokoodi’My dog's name is Willie.My dog is 3 years old.Willie is now sitting.Willie rolled over!My dog's name is Lucy.My dog is 3 years old.Lucy is now sitting.Lucy rolled over!Koodi 7, tiedoston kanssa leikkiminenwith open('pi_digits.txt') as file_object:# tiedoston pi:digits.txt avaus ja tallennus, open(x) as y contents = file_object.read() # sis?ll?n uudelleentallennus ja luku, z=y*read() print(contents.rstrip())# ohjelman teht?v?/p??funktio on “printata z n?yt?lle” Koodin 7 ajoPS C:\python27\harkat> python file_reader.py3.1415926535 8979323846 2643383279# z.rstrip():lla rivi pois lopustaKoodi 8, tiedoston kanssa leikkiminen, osa2filename = 'pi_digits.txt'# sama tiedosto tallennetaan muuttujaksi, filename with open(filename) as file_object: # jos eri kansiossa kirjoita: open(filepath=‘C:\...\filename’) lines = file_object.readlines()# koko tiedosto luetaan rivikerrallaan, readlines()pi_string = ''# tehd??n muuttuja pi_string eli numerot tekstin?for line in lines:# pi_string:ille annetaan lines-muuttujan arvot pi_string += line.strip()# for-loopissa poistetaan rivien v?liset aukot, line.strip()print(pi_string)# printataan koko rimpsuprint(len(pi_string))# printataan my?s rimpsun pituusKoodin 8 ajoPS C:\python27\harkat> python pi_string.py3.141592653589793238462643383279 # laita koodiin int(pi_string) saadaksesi numerot arvoina 32 # rimspun pituus, 32Koodi 9, tiedoston luonti ja kirjoitusfilename = 'abcd.txt'# jos t?t? tiedostoa ei ollut, niin se tehd??nwith open(filename, 'w') as file_object: # se avataan write –moodissa (‘w’), append (‘a’) lis?? siihen file_object.write("I love programming.")# siihen kirjoitetaan… Koodin 9 ajoPS C:\python27\harkat> python write_message.pyPS C:\python27\harkat> cat abcd.txtI love programming. Koodi 10, usean tiedoston analysointidef count_words(filename):# sis?lt?? laskufunktion ja suorituksen (alla) """Count the approximate number of words in a file.""" try:# jos ei poikkeuksia niin kokeillaan (try) with open(filename) as f_obj: contents = f_obj.read() except IOError:# kirjassa t?? poikkeus oli ‘FileNotFoundError’ (python3?) msg = "Sorry, the file " + filename + " does not exist." print(msg) else: # Count approximate number of words in the file. words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.")filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for filename in filenames:count_words(filename) # funktio suoritetaan looppina ‘filenames’ tiedostoilleKoodin 10 ajoPS C:\python27\harkat> python word_count.py #ajoskripti ja funktio oli samassa tiedostossaThe file alice.txt has about 29461 words.Sorry, the file siddhartha.txt does not exist.# ajo osasi my?s todeta poikkeuksenThe file moby_dick.txt has about 215136 words.The file little_women.txt has about 189079 words.Koodi 11, plottaus ja looppiimport matplotlib.pyplot as plt # matplotlib:i? varten k?yt?n python3.4:sta, l?yt foam.pif v??nt?esx=list(range(1,1001))# 1000 arvoa ei k?yd? k?sin l?pi, tehd??n autom. listallay=[x**2 for x in x]# t?ss? looppi listan y-arvoilleplt.scatter(x,y, s=100)# p??funktio on scatter, joka plottaa x&y:n piste kerrallaan# Set chart title and label axes.# sitten kaikkee kuvateknist? yksityiskohtaaplt.title("Square Numbers", fontsize=24)plt.xlabel("Value", fontsize=14)plt.ylabel("Square of Value", fontsize=14)# # Set size of tick labels.plt.tick_params(axis='both', which='major', labelsize=14)# Set the range for each axisplt.axis([0, 1100, 0, 1100000])plt.show()Koodin 11 ajoC:\Python34\harkat>python scatter_squares.py Koodi 12, random-k?velyn (rmk) plottausfrom random import choice# rmk:n funktiot luokka -tiedostossaclass RandomWalk(): """A class to generate random walks.""" def __init__(self, num_points=5000): # rw-pointtien m??r?n voi vaihtaa my?s ajo -tiedostossa """Initialize attributes of a walk.""" self.num_points = num_points # All walks start at (0,0). self.x_values = [0] self.y_values = [0] def fill_walk(self): """Calculate all the points in the walk.""" # Keep taking steps until the walk reaches the desired length. while len(self.x_values) < self.num_points: # Decide which direction to go and how far to go in that direction. x_direction = choice([1, -1])# oikealla tai vasemmalle x_distance = choice([0, 1, 2, 3, 4]) # ilmeisesti voi edet? jopa nelj? askelta kerrallaan! x_step = x_direction * x_distance y_direction = choice([1, -1])# yl?s tai alas y_distance = choice([0, 1, 2, 3, 4]) y_step = y_direction * y_distance # Reject moves that go nowhere: if x_step == 0 and y_step == 0:# eli jos distance:n arvo on 0 (mit? se voi olla) continue # Calculate the next x and y values. next_x = self.x_values[-1] + x_step # -1 on edellinen “koordinaatti” esim. 57 next_y = self.y_values[-1] + y_step self.x_values.append(next_x) # x_values:ksi annetaan next_x edellisen kaavan mukaan self.y_values.append(next_y) # t?m? tehd??n .append -funktiollaimport matplotlib.pyplot as plt# rmk:n plottaus ja ajo -tiedostofrom random_walk import RandomWalk# Keep making new walks, as long as the program is asctive.while True: # Make a random walk, and plot the points. rw = RandomWalk(100000)# aika monta rw-pointtia laitettiin rw.fill_walk() # Set the size of the plotting window. plt.figure(figsize=(10,6))# plottikuvan koko # Plot the points, and show the plot. point_numbers = list(range(rw.num_points)) plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=1)# rw-pointit v?rj?ttiin kasvavasti sinisell? # Emphasize the first and last points. plt.scatter(0, 0, c='green', edgecolors='none', s=100) # alkupiste vihre?ll? ja loppu punaisella plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100) # Remove the axes. plt.axes().get_xaxis().set_visible(False)# kommentoi pois/True, jos haluat akselit n?kyviin plt.axes().get_yaxis().set_visible(False) plt.show() keep_running = input("Make another walk? (y/n): ") # kuvia tehd??n kunnes toisin m??r?t??n if keep_running == 'n': breakKoodin 12 ajoPS C:\python34\harkat> python rw_visual.py Make another walk? (y/n): nKoodi 13, nopat tiedostot: C:\Python34\harkatfrom random import randint # nopat funktiot class -tiedostossaclass Die: """A class representing a single die.""" def __init__(self, num_sides=6): """Assume a six-sided die.""" self.num_sides = num_sides def roll(self): """Return a random value between 1 and number of sides.""" return randint(1, self.num_sides)import pygal# kahden noppan ajo –tiedosto, voi olla enemm?nkin, looppaa x-labelsfrom die import Die# Create a D6.die_1 = Die()die_2 = Die(10)# Make some rolls, and store results in a list.results = []for roll_num in range(50000): result = die_1.roll()+die_2.roll() results.append(result)# Analyze the results.frequencies = []max_result = die_1.num_sides+die_2.num_sidesfor value in range(2, max_result+1):frequency = results.count(value)frequencies.append(frequency)# Visualize the results.hist = pygal.Bar()hist.title = "Results of rolling a D6 and a D10 50000 times."hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12','13','14','15','16']hist.x_title = "Result"hist.y_title = "Frequency of Result"hist.add('D6 + D10', frequencies)hist.render_to_file('die_visual3.svg') # 13 ajo, k?ytet??n geany –ohjelmaa, valmiina runKoodi 14, datan tuonti ulkosesta l?hteest?from pygal.maps.world import COUNTRIES# modulitiedosto “country codes.py”from pygal_maps_world import i18ndef get_country_code(country_name): """Return the Pygal 2-digit country code for the given country.""" for code, name in COUNTRIES.items(): if name == country_name: return code # If the country wasn't found, return None. return Noneimport json# Ajo –tiedosto, world_population.py, tarvitaan json modulifrom country_codes import get_country_code# t?ss? kutsutaan funktiotiedostoa# Load the date into a list.filename = 'population_data.json' # datan (*.json) tulee l?yty? samasta kansiosta kuin ajo -tiedostowith open(filename) as f: pop_data = json.load(f)# Print the 2010 population for each country.for pop_dict in pop_data: if pop_dict['Year'] == '2010': country_name = pop_dict['Country Name'] population = int(float(pop_dict['Value'])) code = get_country_code(country_name) if code: print(code + ": " + str(population)) else: print('ERROR - ' + country_name)Koodin 14 ajo (geniess?)ERROR - Arab World# ohjelma ok, data:ssa puutteita, no problemERROR - Caribbean small states--snip—zm: 12927000zw: 12571000Koodi 15, lis?? datan tuontia ja analysointiaimport csv# ajo –tiedostossa, high_lows.py, tarvitaan csv funktio from datetime import datetime# valmis moduli pythonissafrom matplotlib import pyplot as plt# pyplot funktion nimi vaihdettiin plt:ksi# Get dates and high temperatures from file.filename = 'death_valley_2014.csv'# tiedosto tuodaan *.csv -muodossawith open(filename) as f:# muutetaan tiedoston ‘ajonimeksi f’ reader = csv.reader(f)# lyhyt nimi, helppo laittaa funktion sis??n header_row = next(reader) dates, highs, lows = [], [], [] for row in reader:# jos data-tiedostossa on virheit? t?ytyy varautua huomattamalla ValueErrorista try: current_date=datetime.strptime(row[0], "%Y-%m-%d")# pvm on *.csv:n rivill? ‘0’ high = int(row[1]) low = int(row[3]) except ValueError: print(current_date, 'missing data')# “current_date” on tiedoston current_date else: dates.append(current_date) highs.append(high) lows.append(low) print(highs) # Plot data. fig = plt.figure(dpi=128, figsize=(10, 6)) plt.plot(dates, highs, c='red', alpha=0.5) plt.plot(dates, lows, c='blue', alpha=0.5) plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1) # Format plot. title="Daily high and low temperatures - 2014\nDeath Valley, CA" plt.title(title, fontsize=24) plt.xlabel('', fontsize=16) fig.autofmt_xdate() plt.ylabel("Temperature (F)", fontsize=16) plt.tick_params(axis='both', which='major', labelsize=16) plt.show()Koodin 15 ajo (geanyss?)Python filosofointiaIt does not really matter which calling style you use. As long as your function calls produce the output you want, just use the style you find easiest to understand.Give your variables and functions descriptive names!!A function doesn’t always have to display its output directly. Python ei toimi!? =>Run ja ’Ei n?y’: Laitoitko ”print” –komennon ajo –skrpitiisi? Error: Onko ajo –tiedostossasi uusin kirjasto/kirjotusvirhe, milt? data n?ytt??, puuttuvia rivej? tai muuta ep?m??r?st?? Ks. kirjastoversio win –powershelliss?: ’pip show ”pygal”’ tai ’pip freeze’ tai paranna skripti?.Uudemmassa kirjastossa eri koodi kuin esim. oppikirjassa ja puuttuva data tulee skipata.Ohjauspaneeli\Kaikki ohjauspaneelin…\J?rjestelm? -> onko k?ytt?m?si python ’path’ ok?Onko ohjelmasi tai kirjastosi samaa versiota kuin nykyinen k?ytt?m?si python (2/3.x)?Youtubasitko/googletitko ongelmaasi? Huom. helpoin ratkaisu yleens? riitt??!!Koodauksen ajanhallinnasta. K?ytitk? koodiasian selvitt?miseen alle 10 min vai yli 30 min? Jos yli 30 min, ongelmasi on eri kuin milt? se nyt n?ytt??; jatka etsint??si muualta! Jos alle 10 min; jatka alkuper?ist? selvittely?! ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download