SlideShare a Scribd company logo
1 of 33
Download to read offline
Introduktion till
programmering
Iteration, felhantering och datasamlingar
Simon Johansson
mail@simon-johansson.com
name = 'Simon'
print 'Jag heter ' + name
x = 30
y = 20
svar = x + y
print svar
Repetition - variabler & datatyper ex.1
Jag heter Simon
50
temperatur = 0
if temperatur >= 20:
print 'Varmt och skönt!'
else:
print 'På med vantar och mössa'
Repetition - selektion ex.1
På med vantar
och mössa
def addera(tal1, tal2):
summa = tal1 + tal2
return summa
def main():
svar = addera(5, 10)
print svar
main()
Repetition - funktioner ex.2
15
Felhantering
Olika sorters fel:
● Syntaktiska fel
● Semantiska fel
● Undantag
Robusthet: kod som även kan hantera de undantag som
uppstår när användaren inte beter sig som förväntat
try:
#Kod som alltid körs,
#stöter potentiellt på ett error.
except typ-av-error:
#Kod som körs om try-blocket stöter
#på ett error
Felhantering
try:
userInput = raw_input('Skriv in ett heltal:')
number = int( userInput )
except ValueError:
print 'Det måste vara ett heltal!'
ValueError ex.3
def dividera(a, b):
try:
kvot = a / b
return 'Svaret är: ' + str(kvot)
except ZeroDivisionError:
return 'Division med 0 är inte tillåtet.'
ZeroDivisionError - del 1 ex.4
def main():
svar = dividera(10, 2)
print svar
svar2 = dividera(5, 0)
print svar2
main()
ZeroDivisionError - del 2 ex.4
Svaret är 5
Division med 0 är
inte tillåtet.
Booleska variabler
Booleska variabler tilldelas lämpligen något av värdena från
följande konstanter:
● True
● False
Men, till skillnad från i vissa andra språk så finns det även
andra värden för sant och falskt
Booleska värden
Som falskt räknas även bl a:
● None
● Siffran 0
● Tomma strängar eller datasamlingar: ””,[],()
De flesta andra värden räknas som sanna
villkor = False
if villkor == True:
print 'Ja, det är sant!'
else:
print 'Nej, det är falskt.'
Boolska villkor ex.5
Nej, det är falskt
Beslutsstrukturer
Cold
outside
Wear a coat
True
False
Wear a hat
if hp == 100:
print 'Du mår super!'
if-elif-else ex.6
Du mår helt okej.
elif hp <= 99 and hp >= 50:
print 'Du mår helt okej.'
elif hp <= 49 and hp >= 1:
print 'Du mår inget vidare.'
else:
print 'Du är tyvärr död.'
hp = 62
Iteration
Iteration = upprepning
Upprepa en beräkning eller en annan operation
tills ett önskat resultat har uppnåtts
Typer av loopar: while & for
Användbara kommandon: break & continue
Iteration: while-loop
Condition Statement(s)
True
False
tal = 1
while tal <= 7:
print tal
tal = tal + 1
while-loop ex.7
1
2
3
4
5
6
7
tal = 2
while tal <= 1000:
print tal
tal *= 2
if tal == 128:
break
while-loop: break ex.8
2
4
8
16
32
64
128
Iteration: for-loop
Bäst när du vet antalet iterationer
Passar bra med datasamlingar
Används tillsammans med range()
for i in range(0,7):
print i
for-loop ex.10
0
1
2
3
4
5
6
for i in range(0,7,2):
print i
for-loop ex.11
0
2
4
6
for i in range(7,0,-2):
print i
for-loop ex.12
7
5
3
1
Datasamlingar
Listor - []
Tupletter - ()
Ordlistor - {}
Ta nytta av inbyggda funktioner:
len() & extend()
frukter = ["Mango", "Kiwi", "Melon", "Lime"]
print frukter[0]
print frukter[3]
Datasamlingar: listor ex.13
Mango
Lime
frukter = ["Mango", "Kiwi", "Melon", "Lime"]
print len(frukter)
Datasamlingar: listor ex.13
4
Plommon
5
frukter.extend(["Plommon"])
print frukter[4]
print len(frukter)
frukter = ["Mango", "Kiwi", "Melon", "Lime"]
for element in frukter:
print element.upper()
Datasamlingar: listor ex.13
MANGO
KIWI
MELON
LIME
person = {"namn": "Simon",
"tele": 12345678,
"yrke": "Designer"}
print person["namn"]
print person["tele"]
Datasamlingar: ordlistor ex.15
Simon
12345678
Sammanfattning
Felhantering: try/except
Booleska variabler: True & False
Utökad selektion: if/elif/else
Iteration: while & for
Datasamlingar: [], (), {}
from random import randint
def main():
numberToGuess = randint(1,100)
answer = False
while answer == False:
try:
userInput = int(raw_input("Gissa talet:"))
except ValueError:
print "Det måste vara ett heltal"
continue
Sammanfattningsexempel - del 1 ex.16
if userInput > numberToGuess:
print "Fel, för högt!"
elif userInput < numberToGuess:
print "Fel, för lågt!"
else:
answer = True
print "Rätt!"
main()
Sammanfattningsexempel - del 2 ex.16
Tips
● Experimentera med exemplen från denna föreläsning
(speciellt looparna)
● Försök tänka er in i verkliga implementationer av
koncepten
● Ställ en massa frågor på handledningen och i forumet på
iLearn2
Frågor?!

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Introduktion till programmering - iteration, felhantering och datasamlingar

  • 3. name = 'Simon' print 'Jag heter ' + name x = 30 y = 20 svar = x + y print svar Repetition - variabler & datatyper ex.1 Jag heter Simon 50
  • 4. temperatur = 0 if temperatur >= 20: print 'Varmt och skönt!' else: print 'På med vantar och mössa' Repetition - selektion ex.1 På med vantar och mössa
  • 5. def addera(tal1, tal2): summa = tal1 + tal2 return summa def main(): svar = addera(5, 10) print svar main() Repetition - funktioner ex.2 15
  • 6. Felhantering Olika sorters fel: ● Syntaktiska fel ● Semantiska fel ● Undantag Robusthet: kod som även kan hantera de undantag som uppstår när användaren inte beter sig som förväntat
  • 7. try: #Kod som alltid körs, #stöter potentiellt på ett error. except typ-av-error: #Kod som körs om try-blocket stöter #på ett error Felhantering
  • 8. try: userInput = raw_input('Skriv in ett heltal:') number = int( userInput ) except ValueError: print 'Det måste vara ett heltal!' ValueError ex.3
  • 9. def dividera(a, b): try: kvot = a / b return 'Svaret är: ' + str(kvot) except ZeroDivisionError: return 'Division med 0 är inte tillåtet.' ZeroDivisionError - del 1 ex.4
  • 10. def main(): svar = dividera(10, 2) print svar svar2 = dividera(5, 0) print svar2 main() ZeroDivisionError - del 2 ex.4 Svaret är 5 Division med 0 är inte tillåtet.
  • 11. Booleska variabler Booleska variabler tilldelas lämpligen något av värdena från följande konstanter: ● True ● False Men, till skillnad från i vissa andra språk så finns det även andra värden för sant och falskt
  • 12. Booleska värden Som falskt räknas även bl a: ● None ● Siffran 0 ● Tomma strängar eller datasamlingar: ””,[],() De flesta andra värden räknas som sanna
  • 13. villkor = False if villkor == True: print 'Ja, det är sant!' else: print 'Nej, det är falskt.' Boolska villkor ex.5 Nej, det är falskt
  • 15. if hp == 100: print 'Du mår super!' if-elif-else ex.6 Du mår helt okej. elif hp <= 99 and hp >= 50: print 'Du mår helt okej.' elif hp <= 49 and hp >= 1: print 'Du mår inget vidare.' else: print 'Du är tyvärr död.' hp = 62
  • 16. Iteration Iteration = upprepning Upprepa en beräkning eller en annan operation tills ett önskat resultat har uppnåtts Typer av loopar: while & for Användbara kommandon: break & continue
  • 18. tal = 1 while tal <= 7: print tal tal = tal + 1 while-loop ex.7 1 2 3 4 5 6 7
  • 19. tal = 2 while tal <= 1000: print tal tal *= 2 if tal == 128: break while-loop: break ex.8 2 4 8 16 32 64 128
  • 20. Iteration: for-loop Bäst när du vet antalet iterationer Passar bra med datasamlingar Används tillsammans med range()
  • 21. for i in range(0,7): print i for-loop ex.10 0 1 2 3 4 5 6
  • 22. for i in range(0,7,2): print i for-loop ex.11 0 2 4 6
  • 23. for i in range(7,0,-2): print i for-loop ex.12 7 5 3 1
  • 24. Datasamlingar Listor - [] Tupletter - () Ordlistor - {} Ta nytta av inbyggda funktioner: len() & extend()
  • 25. frukter = ["Mango", "Kiwi", "Melon", "Lime"] print frukter[0] print frukter[3] Datasamlingar: listor ex.13 Mango Lime
  • 26. frukter = ["Mango", "Kiwi", "Melon", "Lime"] print len(frukter) Datasamlingar: listor ex.13 4 Plommon 5 frukter.extend(["Plommon"]) print frukter[4] print len(frukter)
  • 27. frukter = ["Mango", "Kiwi", "Melon", "Lime"] for element in frukter: print element.upper() Datasamlingar: listor ex.13 MANGO KIWI MELON LIME
  • 28. person = {"namn": "Simon", "tele": 12345678, "yrke": "Designer"} print person["namn"] print person["tele"] Datasamlingar: ordlistor ex.15 Simon 12345678
  • 29. Sammanfattning Felhantering: try/except Booleska variabler: True & False Utökad selektion: if/elif/else Iteration: while & for Datasamlingar: [], (), {}
  • 30. from random import randint def main(): numberToGuess = randint(1,100) answer = False while answer == False: try: userInput = int(raw_input("Gissa talet:")) except ValueError: print "Det måste vara ett heltal" continue Sammanfattningsexempel - del 1 ex.16
  • 31. if userInput > numberToGuess: print "Fel, för högt!" elif userInput < numberToGuess: print "Fel, för lågt!" else: answer = True print "Rätt!" main() Sammanfattningsexempel - del 2 ex.16
  • 32. Tips ● Experimentera med exemplen från denna föreläsning (speciellt looparna) ● Försök tänka er in i verkliga implementationer av koncepten ● Ställ en massa frågor på handledningen och i forumet på iLearn2