SlideShare a Scribd company logo
1 of 11
Page 1



6.189 Exam
Session 5

Administrivia
Name:



MIT ID:



Instructions:
1. Err..complete the questions :). Warning: they do increase in difficulty.
2. No calculators, no laptops, etc.
3. When we ask for output, you DON'T have to write the spaces/newlines in.
   Program Text:

     print “X”,

     print “X”,



   Output:



                                                  XX

Day 1: Variables, Operators, and Expressions
Tips/Notes:
 ­ Variables are typed (this is a string, that's an integer, etc.) type(x) is a function that returns the type
   of its parameter.
 ­ You can convert information from one type to another using the built-in conversion functions: int(x),
   str(x), float(x), bool(x). These tend to fail for conversions that don't make sense, e.g. int("hello")
   crashes.
 ­ Every variable you create should have a meaning. Give your variables names that match their 

   meaning: don't just name all your variables a, b, c (exception: if you're writing a quiz to test your 

   students, only use names like a, b, c)


Problem 1: Neophyte (hey, this was just 4 days ago)
What is the output of the following code?

   Program Text:

     a = 5

     b = a + 7

     a = 10

     print b
Page 2


    Output:

                                                   12



Problem 2: Type Theory

What is the type of each of the following expressions (within the type function)?


    Program Text:                                           Output:

      print type(5)
                                                           int


    Program Text:                                           Output:

      print type("abc")
                                                   string


    Program Text:                                           Output:

      print type(True)
                                                   boolean


    Program Text:                                           Output:

      print type(5.5)
                                                      float


    Program Text:                                           Output:

      print type(12/27)
                                                       int


    Program Text:                                           Output:

      print type(2.0/1)
                                                    float


    Program Text:                                           Output:

      print type(12 ** 3)
                                                     int


    Program Text:                                           Output:

      print type(5 == “5”)
                                               boolean


    Program Text:

      a = str((-4 + abs(-5) / 2 ** 3) + 321 - ((64 / 16) % 4) ** 2)
      print type(a)


    Output:


                                               string
Page 3





Problem 3: Expressive Expressions
What is the output of the following code?


       Program Text:                                               Output:

         print 5 == 5.0
                                                             True1

       Program Text:                                               Output:

         print float(1/2)
                                                            0.0


       Program Text:                                               Output:

         print float(1)/2
                                                             0.5


       Program Text:                                               Output:

         print 5 == "5"
                                                            false


       Program Text:                                               Output:

         print "sdf" != "sdf"
                                                      false


       Program Text:                                               Output:

         print True and (False or not True)
                                        false


       Program Text:                                               Output:

         print str(53) + str(True)
                                                 53true


       Program Text:

         a = 20
         print 15-(a-15), “,”,
         a = 10
         print 15-(a-15),

       Output:

                                                      10,20



Day 3: Conditionals
Tips/Notes:
 ­ The if statement executes a sequence of statements only if some condition is true. This condition
   can be anything.



1
    Scheme (the initial language taught at MIT before Python) took type to an extreme. 5.0 and 5 were not
    considered equal because one was an integer and the other was a float. You weren’t even allowed to do (4 + 6.0.)
    Python is more rational – it treats the two values as equal.
Page 4


 ­ elif / else is optional. Remember that at most one block of statements is executed. else occurs if
   none of the above conditions are satisfied.

Problem 4: Basics
Consider the following code

   Program Text:

     a = ?

     if a > 10 and a % 6 = 3:
       print "a",
     elif a > 10 and a < 20:
       print "b",
     else:
       print "c",


Give a value for a that would produce the following outputs. If no value of a would produce that output,
write none.

   Value of a:                                   Output:

                     none                                               a b

   Value of a:                                   Output:

                   15,21,27,…                                            a

   Value of a:                                   Output:

          11,12,…,19 (except 15)                                         b

   Value of a:                                   Output:

                   Any other                                             c

   Value of a:                                   Output:

                     none                                      victory is mine!


Problem 5: Trickier Duet
Removed due to time constraints.
Page 5



Day 3: While loop
Tips/Notes:
 ­ A while loop allows us to repeat a sequence of statements many times.
 ­ You can use almost anything for the condition. Not every while loop has to be a simple counter.

Problem 6: This is not a loopy title
What is the output of the following code? If the code does not terminate, write error.

    Program Text:

      a = 5
      while a < 8:
        print "X",

    Output:

                                        Loops forever


    Program Text:

      a = -1
      while a < 3:
        print "X",
        a = a + 1

    Output:

                                                 XXXX


    Program Text:

      a = 1
      while a % 7 != 0:
        if a % 2 == 0:
          print "O"
        if a == 2:
          print "X"
        a = a + 1

    Output:

                                                OXOO
Page 6


Problem 7: Subtle variants
We’re going to show you variants of the same code. Write the output of each code snippet.

    Program Text:

      keep_going = True
      a = 0
      b = 0
      while keep_going:
        print "O"
        a = a + 5
        b = b + 7
        if a + b >= 24:
          keep_going = False
    Output:

                                                  OO



We rearranged the code within the while loop here.

    Program Text:

      keep_going = True
      a = 0
      b = 0
      while keep_going:
        print "O"

        if a + b >= 24:

          keep_going = False
        a = a + 5
        b = b + 7
    Output:

                                                 OOO



The remaining two variants are duplicates of the first two with >= replaced by >.
    Program Text:

      keep_going = True
      a = 0
      b = 0
      while keep_going:
        print "O"
        a = a + 5
        b = b + 7
        if a + b > 24:
          keep_going = False
Page 7




    Output:

                                                 OOO


    Program Text:

      keep_going = True
      a = 0
      b = 0
      while keep_going:
        print "O"

        if a + b > 24:

          keep_going = False
        a = a + 5
        b = b + 7
    Output:

                                                OOOO



Day 3: Nested loops
Tips/Notes:
 ­ This isn't anything new, but we can put loops inside other loops. We can also do fairly crazy things:
   nest a while in an if in a while in another while.
 ­ The break keyword exits the innermost loop.

Problem 8: Freebie!
What is the output of the following code? If the code does not terminate, write error.

    Program Text:

      a = 0
      while a < 3:
        while True:
          print "X",
          break
        print "O",
        a = a + 1

    Output:

                                              XOXOXO
Page 8




Problem 9: (insert evil laugh) ..is what I’d like to say. Still not that bad, though
What is the output of the following code? If the code does not terminate, write error.

    Program Text:

      a = 1
      while a <     3:
        while a     < 3:
          print     "O",
        a = a +     1

    Output:

                                         Loops forever


    Program Text:

      a = 1
      while a < 3:
        if a % 2 == 0:
          b = 1
          while b < 3:
            print "X",
            b = b + 1
        print "O",
        a = a + 1
    Output:

                                                  OXXO



Extra Credit (mainly due to time constraints.) Solve this if you finish early!:
    Program Text:

      a = 1
      while a < 3:
        b = 1
        while b < 3:
          if a == 2:
            print "X",
          print "O",
          b = b + 1
        print "O",
    Output:

               Loops forever (due to typo.) Fixed, it would be

                                oooxoxoo
Page 9




Day 2: Functions
Tips/Notes:
 ­ A function is just a named sequence of statements. We usually define functions at the beginning of
   code – definitions just associate the name with the sequence of statements.
 ­ Functions can take parameters (within the parenthesis suffix) and can return information via return
 ­ return is NOT a function. Like if, while, .. its a keyword: a basic command of the language.
 ­ You can find out more information about functions using the help(x) function, e.g. help(sqrt).
   Remember to write from math import * first.

Problem 10: Sanity Check
What is the output of the following code? If the code does not terminate, write error.

    Program Text:

      def f(a):
        a = a + 5
        return a

      b = 0

      f(b)

      print b, ",",

      b = f(b)

      print b



    Output:

                                                   0,5



Problem 11: Last but not least (somewhere in the middle)
You know that functions can call other functions, right? Here’s an interesting fact – functions can call
themselves!

    Program Text:

      def f(x):

        print "X",

        if x <= 1:

          return 1

        else:

          return x+f(x-1)
Page 10


Fill out the following table for the return value and output of each function call.

Function call:   Return value:                          Output:

  f(1)                           1                                              X

Function call:   Return value:                          Output:

  f(2)                           3                                             XX

Function call:   Return value:                          Output:

  f(3)                           6                                            XXX

Function call:   Return value:                          Output:

  f(4)                           10                                          XXXX
Page 11


Extra stuff
If you were reasonably comfortable with this test, here is some extra stuff that you might find useful
(you can rip this page out if you like.)
   ­	 Don’t forget about using # to write notes/comments in your code!
   ­	 Instead of always writing a = a + 5 or a = a / 7, you can use the shorthand a += 5 and a /= 7. Be
      careful not to get confused by this notation:

    Program Text:
     ­
     ­a = 5
     ­b = a
     ­a += 3
     ­print b #still 5

  ­	 String stuff
     � You can use either a single quotation mark (‘) or a double quotation mark for strings. The only
       difference is either one can contain the other (‘This is a “test”’ is valid, “This is a ‘test’” is valid,
       “This is a “test”” is not valid.)
     � You can use “n” to insert a newline (Enter key) in a string.
     � You can define multi-line strings using the triple-quotation """ operator.

    Program Text:
     ­
     ­ print “““Thisis a sentence.nThis sentence is on the second line.
     ­ This sentenceis on the third line.
     ­This is on the fourth.”””
     ­

  ­ You can write a description of a function by putting a string as the first line of the function.

    Program Text:
     ­
     ­ def hypo(a,b):
     ­   """This function returns the length of the hypotenuse defined by
     ­      the right triangle with side lengths a,b"""
     ­   return sqrt(a*a + b*b)

    Try calling help(hypo) on the function you just wrote!
  ­ print is a keyword, not a function (like if, while, return.) There’s no particularly good reason why it’s
    a keyword – future versions of Python are changing it into a function.

More Related Content

What's hot

Course Breakup Plan- C
Course Breakup Plan- CCourse Breakup Plan- C
Course Breakup Plan- Cswatisinghal
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++Nimrita Koul
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 
05 -working_with_the_preproce
05  -working_with_the_preproce05  -working_with_the_preproce
05 -working_with_the_preproceHector Garzo
 
16 -ansi-iso_standards
16  -ansi-iso_standards16  -ansi-iso_standards
16 -ansi-iso_standardsHector Garzo
 
Hands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageHands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageVincenzo De Florio
 
Kuliah komputer pemrograman
Kuliah  komputer pemrogramanKuliah  komputer pemrograman
Kuliah komputer pemrogramanhardryu
 
miniLesson on the printf() function
miniLesson on the printf() functionminiLesson on the printf() function
miniLesson on the printf() functionChristine Wolfe
 
Lecture#5 c lang new
Lecture#5 c lang newLecture#5 c lang new
Lecture#5 c lang newZeeshan Ahmad
 
Storage classes, linkage & memory management
Storage classes, linkage & memory managementStorage classes, linkage & memory management
Storage classes, linkage & memory managementMomenMostafa
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semKavita Dagar
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic conceptsAbhinav Vatsa
 

What's hot (19)

Course Breakup Plan- C
Course Breakup Plan- CCourse Breakup Plan- C
Course Breakup Plan- C
 
Deep C
Deep CDeep C
Deep C
 
Templates and Exception Handling in C++
Templates and Exception Handling in C++Templates and Exception Handling in C++
Templates and Exception Handling in C++
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
05 -working_with_the_preproce
05  -working_with_the_preproce05  -working_with_the_preproce
05 -working_with_the_preproce
 
16 -ansi-iso_standards
16  -ansi-iso_standards16  -ansi-iso_standards
16 -ansi-iso_standards
 
Hands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming LanguageHands-on Introduction to the C Programming Language
Hands-on Introduction to the C Programming Language
 
Aptitute question papers in c
Aptitute question papers in cAptitute question papers in c
Aptitute question papers in c
 
Basics of c++
Basics of c++Basics of c++
Basics of c++
 
Kuliah komputer pemrograman
Kuliah  komputer pemrogramanKuliah  komputer pemrograman
Kuliah komputer pemrograman
 
miniLesson on the printf() function
miniLesson on the printf() functionminiLesson on the printf() function
miniLesson on the printf() function
 
C++ for beginners
C++ for beginnersC++ for beginners
C++ for beginners
 
Lecture#5 c lang new
Lecture#5 c lang newLecture#5 c lang new
Lecture#5 c lang new
 
Storage classes, linkage & memory management
Storage classes, linkage & memory managementStorage classes, linkage & memory management
Storage classes, linkage & memory management
 
C notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-semC notes diploma-ee-3rd-sem
C notes diploma-ee-3rd-sem
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
C the basic concepts
C the basic conceptsC the basic concepts
C the basic concepts
 

Viewers also liked

Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 01
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 01Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 01
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 01Sukarya
 
What is smart writing
What is smart writingWhat is smart writing
What is smart writingLEE Chang-Bin
 
دراسة في الاستحواذ الأدبي وارتجالية الترجمة
دراسة في الاستحواذ الأدبي وارتجالية الترجمةدراسة في الاستحواذ الأدبي وارتجالية الترجمة
دراسة في الاستحواذ الأدبي وارتجالية الترجمةMériem Touati
 
Buus - pitchdeck
Buus - pitchdeckBuus - pitchdeck
Buus - pitchdeckStartupi
 
haiku invite 2008
haiku invite 2008haiku invite 2008
haiku invite 2008Karen Lo
 
Trustee Of A Florida Land Trust
Trustee Of A Florida Land TrustTrustee Of A Florida Land Trust
Trustee Of A Florida Land TrustMichael Belgeri
 
Secret Garden prom
Secret Garden promSecret Garden prom
Secret Garden promKaren Lo
 
Florbela espanca fanatismo
Florbela espanca fanatismoFlorbela espanca fanatismo
Florbela espanca fanatismoLuzia Gabriele
 
Lessons on problem-solving, inclusivity, and empowerment from classical music
Lessons on problem-solving, inclusivity, and empowerment from classical musicLessons on problem-solving, inclusivity, and empowerment from classical music
Lessons on problem-solving, inclusivity, and empowerment from classical musicSmitha Prasadh
 
Bedtime story for kids
Bedtime story for kidsBedtime story for kids
Bedtime story for kidsjohn joni
 
Price determination under monopolistic competition
Price determination under monopolistic competitionPrice determination under monopolistic competition
Price determination under monopolistic competitionJithin Thomas
 
Price determination under oligopoly
Price determination under   oligopolyPrice determination under   oligopoly
Price determination under oligopolysukhpal0015
 
UX Design: An Introduction
UX Design: An IntroductionUX Design: An Introduction
UX Design: An IntroductionSmitha Prasadh
 
Price determination under monopoly
Price determination under monopolyPrice determination under monopoly
Price determination under monopolyJithin Thomas
 

Viewers also liked (19)

Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 01
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 01Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 01
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 01
 
RESUMEAshley
RESUMEAshleyRESUMEAshley
RESUMEAshley
 
What is smart writing
What is smart writingWhat is smart writing
What is smart writing
 
دراسة في الاستحواذ الأدبي وارتجالية الترجمة
دراسة في الاستحواذ الأدبي وارتجالية الترجمةدراسة في الاستحواذ الأدبي وارتجالية الترجمة
دراسة في الاستحواذ الأدبي وارتجالية الترجمة
 
Piano Lessons
Piano LessonsPiano Lessons
Piano Lessons
 
Buus - pitchdeck
Buus - pitchdeckBuus - pitchdeck
Buus - pitchdeck
 
practica 2
practica 2practica 2
practica 2
 
haiku invite 2008
haiku invite 2008haiku invite 2008
haiku invite 2008
 
Trustee Of A Florida Land Trust
Trustee Of A Florida Land TrustTrustee Of A Florida Land Trust
Trustee Of A Florida Land Trust
 
Colores William
Colores WilliamColores William
Colores William
 
Secret Garden prom
Secret Garden promSecret Garden prom
Secret Garden prom
 
Horizon 2020  sh
Horizon 2020  shHorizon 2020  sh
Horizon 2020  sh
 
Florbela espanca fanatismo
Florbela espanca fanatismoFlorbela espanca fanatismo
Florbela espanca fanatismo
 
Lessons on problem-solving, inclusivity, and empowerment from classical music
Lessons on problem-solving, inclusivity, and empowerment from classical musicLessons on problem-solving, inclusivity, and empowerment from classical music
Lessons on problem-solving, inclusivity, and empowerment from classical music
 
Bedtime story for kids
Bedtime story for kidsBedtime story for kids
Bedtime story for kids
 
Price determination under monopolistic competition
Price determination under monopolistic competitionPrice determination under monopolistic competition
Price determination under monopolistic competition
 
Price determination under oligopoly
Price determination under   oligopolyPrice determination under   oligopoly
Price determination under oligopoly
 
UX Design: An Introduction
UX Design: An IntroductionUX Design: An Introduction
UX Design: An Introduction
 
Price determination under monopoly
Price determination under monopolyPrice determination under monopoly
Price determination under monopoly
 

Similar to pyton Exam1 soln

What is turbo c and how it works
What is turbo c and how it worksWhat is turbo c and how it works
What is turbo c and how it worksMark John Lado, MIT
 
Deep C Programming
Deep C ProgrammingDeep C Programming
Deep C ProgrammingWang Hao Lee
 
if statements in Python -A lecture class
if statements in Python -A lecture classif statements in Python -A lecture class
if statements in Python -A lecture classbinzbinz3
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topicsveningstonk
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As CompDavid Halliday
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As CompDavid Halliday
 
Cis 170 c ilab 5 of 7 arrays and strings
Cis 170 c ilab 5 of 7 arrays and stringsCis 170 c ilab 5 of 7 arrays and strings
Cis 170 c ilab 5 of 7 arrays and stringsCIS321
 
Review chapter 1 2-3
Review chapter 1 2-3Review chapter 1 2-3
Review chapter 1 2-3ahmed22dg
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make YASHU40
 
C language questions_answers_explanation
C language questions_answers_explanationC language questions_answers_explanation
C language questions_answers_explanationsrinath v
 
3150 Chapter 2 Part 1
3150 Chapter 2 Part 13150 Chapter 2 Part 1
3150 Chapter 2 Part 1Mole Wong
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c languagefarishah
 
Devry cis 170 c i lab 5 of 7 arrays and strings
Devry cis 170 c i lab 5 of 7 arrays and stringsDevry cis 170 c i lab 5 of 7 arrays and strings
Devry cis 170 c i lab 5 of 7 arrays and stringsjody zoll
 

Similar to pyton Exam1 soln (20)

What is turbo c and how it works
What is turbo c and how it worksWhat is turbo c and how it works
What is turbo c and how it works
 
Deep C Programming
Deep C ProgrammingDeep C Programming
Deep C Programming
 
if statements in Python -A lecture class
if statements in Python -A lecture classif statements in Python -A lecture class
if statements in Python -A lecture class
 
Unit 1 c - all topics
Unit 1   c - all topicsUnit 1   c - all topics
Unit 1 c - all topics
 
Programming in c
Programming in cProgramming in c
Programming in c
 
2 debugging-c
2 debugging-c2 debugging-c
2 debugging-c
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
 
2621008 - C++ 1
2621008 -  C++ 12621008 -  C++ 1
2621008 - C++ 1
 
Cis 170 c ilab 5 of 7 arrays and strings
Cis 170 c ilab 5 of 7 arrays and stringsCis 170 c ilab 5 of 7 arrays and strings
Cis 170 c ilab 5 of 7 arrays and strings
 
The basics of c programming
The basics of c programmingThe basics of c programming
The basics of c programming
 
Review chapter 1 2-3
Review chapter 1 2-3Review chapter 1 2-3
Review chapter 1 2-3
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make
 
C language questions_answers_explanation
C language questions_answers_explanationC language questions_answers_explanation
C language questions_answers_explanation
 
3150 Chapter 2 Part 1
3150 Chapter 2 Part 13150 Chapter 2 Part 1
3150 Chapter 2 Part 1
 
pyton Notes1
pyton Notes1pyton Notes1
pyton Notes1
 
Introduction of c language
Introduction of c languageIntroduction of c language
Introduction of c language
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
Devry cis 170 c i lab 5 of 7 arrays and strings
Devry cis 170 c i lab 5 of 7 arrays and stringsDevry cis 170 c i lab 5 of 7 arrays and strings
Devry cis 170 c i lab 5 of 7 arrays and strings
 

More from Amba Research

More from Amba Research (20)

Case Econ08 Ppt 16
Case Econ08 Ppt 16Case Econ08 Ppt 16
Case Econ08 Ppt 16
 
Case Econ08 Ppt 08
Case Econ08 Ppt 08Case Econ08 Ppt 08
Case Econ08 Ppt 08
 
Case Econ08 Ppt 11
Case Econ08 Ppt 11Case Econ08 Ppt 11
Case Econ08 Ppt 11
 
Case Econ08 Ppt 14
Case Econ08 Ppt 14Case Econ08 Ppt 14
Case Econ08 Ppt 14
 
Case Econ08 Ppt 12
Case Econ08 Ppt 12Case Econ08 Ppt 12
Case Econ08 Ppt 12
 
Case Econ08 Ppt 10
Case Econ08 Ppt 10Case Econ08 Ppt 10
Case Econ08 Ppt 10
 
Case Econ08 Ppt 15
Case Econ08 Ppt 15Case Econ08 Ppt 15
Case Econ08 Ppt 15
 
Case Econ08 Ppt 13
Case Econ08 Ppt 13Case Econ08 Ppt 13
Case Econ08 Ppt 13
 
Case Econ08 Ppt 07
Case Econ08 Ppt 07Case Econ08 Ppt 07
Case Econ08 Ppt 07
 
Case Econ08 Ppt 06
Case Econ08 Ppt 06Case Econ08 Ppt 06
Case Econ08 Ppt 06
 
Case Econ08 Ppt 05
Case Econ08 Ppt 05Case Econ08 Ppt 05
Case Econ08 Ppt 05
 
Case Econ08 Ppt 04
Case Econ08 Ppt 04Case Econ08 Ppt 04
Case Econ08 Ppt 04
 
Case Econ08 Ppt 03
Case Econ08 Ppt 03Case Econ08 Ppt 03
Case Econ08 Ppt 03
 
Case Econ08 Ppt 02
Case Econ08 Ppt 02Case Econ08 Ppt 02
Case Econ08 Ppt 02
 
Case Econ08 Ppt 01
Case Econ08 Ppt 01Case Econ08 Ppt 01
Case Econ08 Ppt 01
 
pyton Notes9
pyton Notes9pyton Notes9
pyton Notes9
 
Notes8
Notes8Notes8
Notes8
 
Notes7
Notes7Notes7
Notes7
 
pyton Notes6
 pyton Notes6 pyton Notes6
pyton Notes6
 
learn matlab for ease Lec5
learn matlab for ease Lec5learn matlab for ease Lec5
learn matlab for ease Lec5
 

Recently uploaded

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 

Recently uploaded (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 

pyton Exam1 soln

  • 1. Page 1 6.189 Exam Session 5 Administrivia Name: MIT ID: Instructions: 1. Err..complete the questions :). Warning: they do increase in difficulty. 2. No calculators, no laptops, etc. 3. When we ask for output, you DON'T have to write the spaces/newlines in. Program Text: print “X”, print “X”, Output: XX Day 1: Variables, Operators, and Expressions Tips/Notes: ­ Variables are typed (this is a string, that's an integer, etc.) type(x) is a function that returns the type of its parameter. ­ You can convert information from one type to another using the built-in conversion functions: int(x), str(x), float(x), bool(x). These tend to fail for conversions that don't make sense, e.g. int("hello") crashes. ­ Every variable you create should have a meaning. Give your variables names that match their meaning: don't just name all your variables a, b, c (exception: if you're writing a quiz to test your students, only use names like a, b, c) Problem 1: Neophyte (hey, this was just 4 days ago) What is the output of the following code? Program Text: a = 5 b = a + 7 a = 10 print b
  • 2. Page 2 Output: 12 Problem 2: Type Theory What is the type of each of the following expressions (within the type function)? Program Text: Output: print type(5) int Program Text: Output: print type("abc") string Program Text: Output: print type(True) boolean Program Text: Output: print type(5.5) float Program Text: Output: print type(12/27) int Program Text: Output: print type(2.0/1) float Program Text: Output: print type(12 ** 3) int Program Text: Output: print type(5 == “5”) boolean Program Text: a = str((-4 + abs(-5) / 2 ** 3) + 321 - ((64 / 16) % 4) ** 2) print type(a) Output: string
  • 3. Page 3 Problem 3: Expressive Expressions What is the output of the following code? Program Text: Output: print 5 == 5.0 True1 Program Text: Output: print float(1/2) 0.0 Program Text: Output: print float(1)/2 0.5 Program Text: Output: print 5 == "5" false Program Text: Output: print "sdf" != "sdf" false Program Text: Output: print True and (False or not True) false Program Text: Output: print str(53) + str(True) 53true Program Text: a = 20 print 15-(a-15), “,”, a = 10 print 15-(a-15), Output: 10,20 Day 3: Conditionals Tips/Notes: ­ The if statement executes a sequence of statements only if some condition is true. This condition can be anything. 1 Scheme (the initial language taught at MIT before Python) took type to an extreme. 5.0 and 5 were not considered equal because one was an integer and the other was a float. You weren’t even allowed to do (4 + 6.0.) Python is more rational – it treats the two values as equal.
  • 4. Page 4 ­ elif / else is optional. Remember that at most one block of statements is executed. else occurs if none of the above conditions are satisfied. Problem 4: Basics Consider the following code Program Text: a = ? if a > 10 and a % 6 = 3: print "a", elif a > 10 and a < 20: print "b", else: print "c", Give a value for a that would produce the following outputs. If no value of a would produce that output, write none. Value of a: Output: none a b Value of a: Output: 15,21,27,… a Value of a: Output: 11,12,…,19 (except 15) b Value of a: Output: Any other c Value of a: Output: none victory is mine! Problem 5: Trickier Duet Removed due to time constraints.
  • 5. Page 5 Day 3: While loop Tips/Notes: ­ A while loop allows us to repeat a sequence of statements many times. ­ You can use almost anything for the condition. Not every while loop has to be a simple counter. Problem 6: This is not a loopy title What is the output of the following code? If the code does not terminate, write error. Program Text: a = 5 while a < 8: print "X", Output: Loops forever Program Text: a = -1 while a < 3: print "X", a = a + 1 Output: XXXX Program Text: a = 1 while a % 7 != 0: if a % 2 == 0: print "O" if a == 2: print "X" a = a + 1 Output: OXOO
  • 6. Page 6 Problem 7: Subtle variants We’re going to show you variants of the same code. Write the output of each code snippet. Program Text: keep_going = True a = 0 b = 0 while keep_going: print "O" a = a + 5 b = b + 7 if a + b >= 24: keep_going = False Output: OO We rearranged the code within the while loop here. Program Text: keep_going = True a = 0 b = 0 while keep_going: print "O" if a + b >= 24: keep_going = False a = a + 5 b = b + 7 Output: OOO The remaining two variants are duplicates of the first two with >= replaced by >. Program Text: keep_going = True a = 0 b = 0 while keep_going: print "O" a = a + 5 b = b + 7 if a + b > 24: keep_going = False
  • 7. Page 7 Output: OOO Program Text: keep_going = True a = 0 b = 0 while keep_going: print "O" if a + b > 24: keep_going = False a = a + 5 b = b + 7 Output: OOOO Day 3: Nested loops Tips/Notes: ­ This isn't anything new, but we can put loops inside other loops. We can also do fairly crazy things: nest a while in an if in a while in another while. ­ The break keyword exits the innermost loop. Problem 8: Freebie! What is the output of the following code? If the code does not terminate, write error. Program Text: a = 0 while a < 3: while True: print "X", break print "O", a = a + 1 Output: XOXOXO
  • 8. Page 8 Problem 9: (insert evil laugh) ..is what I’d like to say. Still not that bad, though What is the output of the following code? If the code does not terminate, write error. Program Text: a = 1 while a < 3: while a < 3: print "O", a = a + 1 Output: Loops forever Program Text: a = 1 while a < 3: if a % 2 == 0: b = 1 while b < 3: print "X", b = b + 1 print "O", a = a + 1 Output: OXXO Extra Credit (mainly due to time constraints.) Solve this if you finish early!: Program Text: a = 1 while a < 3: b = 1 while b < 3: if a == 2: print "X", print "O", b = b + 1 print "O", Output: Loops forever (due to typo.) Fixed, it would be oooxoxoo
  • 9. Page 9 Day 2: Functions Tips/Notes: ­ A function is just a named sequence of statements. We usually define functions at the beginning of code – definitions just associate the name with the sequence of statements. ­ Functions can take parameters (within the parenthesis suffix) and can return information via return ­ return is NOT a function. Like if, while, .. its a keyword: a basic command of the language. ­ You can find out more information about functions using the help(x) function, e.g. help(sqrt). Remember to write from math import * first. Problem 10: Sanity Check What is the output of the following code? If the code does not terminate, write error. Program Text: def f(a): a = a + 5 return a b = 0 f(b) print b, ",", b = f(b) print b Output: 0,5 Problem 11: Last but not least (somewhere in the middle) You know that functions can call other functions, right? Here’s an interesting fact – functions can call themselves! Program Text: def f(x): print "X", if x <= 1: return 1 else: return x+f(x-1)
  • 10. Page 10 Fill out the following table for the return value and output of each function call. Function call: Return value: Output: f(1) 1 X Function call: Return value: Output: f(2) 3 XX Function call: Return value: Output: f(3) 6 XXX Function call: Return value: Output: f(4) 10 XXXX
  • 11. Page 11 Extra stuff If you were reasonably comfortable with this test, here is some extra stuff that you might find useful (you can rip this page out if you like.) ­ Don’t forget about using # to write notes/comments in your code! ­ Instead of always writing a = a + 5 or a = a / 7, you can use the shorthand a += 5 and a /= 7. Be careful not to get confused by this notation: Program Text: ­ ­a = 5 ­b = a ­a += 3 ­print b #still 5 ­ String stuff � You can use either a single quotation mark (‘) or a double quotation mark for strings. The only difference is either one can contain the other (‘This is a “test”’ is valid, “This is a ‘test’” is valid, “This is a “test”” is not valid.) � You can use “n” to insert a newline (Enter key) in a string. � You can define multi-line strings using the triple-quotation """ operator. Program Text: ­ ­ print “““Thisis a sentence.nThis sentence is on the second line. ­ This sentenceis on the third line. ­This is on the fourth.””” ­ ­ You can write a description of a function by putting a string as the first line of the function. Program Text: ­ ­ def hypo(a,b): ­ """This function returns the length of the hypotenuse defined by ­ the right triangle with side lengths a,b""" ­ return sqrt(a*a + b*b) Try calling help(hypo) on the function you just wrote! ­ print is a keyword, not a function (like if, while, return.) There’s no particularly good reason why it’s a keyword – future versions of Python are changing it into a function.