(2½ hours) Total Marks: 75

Size: px
Start display at page:

Download "(2½ hours) Total Marks: 75"

Transcription

1 (2½ hours) Total Marks: 75 N. B.: (1) All questions are compulsory. (2) Make suitable assumptions wherever necessary and state the assumptions made. (3) Answers to the same question must be written together. (4) Numbers to the right indicate marks. (5) Draw neat labeled diagrams wherever necessary. (6) Use of Non-programmable calculators is allowed. Note : 1. The answers given here are just a guidance and the teachers must give consideration to any other logic[for theory and code snippets] used by the student in framing the same. 2. Make necessary changes in answers if necessary. I have tried to give the answers after executing each code. 1. Attempt any three of the following: 15 a. Python programs are executed by an interpreter. There are two ways to use the interpreter. What are they? There are two ways to use the interpreter: interactive mode and script mode. In interactive mode, you type Python programs and the interpreter displays the result: >>> The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you type 1 + 1, the interpreter replies 2. Alternatively, you can store code in a file and use the interpreter to execute the contents of the file, which is called a script. By convention, Python scripts have names that end with.py. To execute the script, you have to tell the interpreter the name of the file. b. When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. The acronym PEMDAS is an useful way to remember the rules. Explain the same with a Python expression. Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even if it doesn t change the result. Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and 3*1**3 is 3, not 27. Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5, not 4, and / 2 is 8, not 5. Operators with the same precedence are evaluated from left to right (except exponentiation). So in the expression degrees / 2 * pi, the division happens first and the result is multiplied by pi. To divide by 2π, you can use parentheses or write degrees / 2 / pi.

2 c. The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a numerical approximation of 1/π: 1 π = (4k)! ( k) (k!) k k=0 Write a function called estimate_pi that uses this formula to compute and return an estimate of π. It should use a while loop to compute terms of the summation until the last term is smaller than 1e-15 (Python notation for ). d. Write the output for the following: i) >>> print('a', 'b', 'c', sep = ', ', end=' ') ii) >>> 4 * '-' iii) >>> 'GC' * 0 #This is GC * zero iv) >>> x = 3 >>> 1 < x <= 5 v) >>> 3 < 5!= False vi) >>> 'abc' < 'abcd' vii) >>> 'Jan' in '01 Jan 1838'

3 viii) >>> ' ' in 'abc' ix) >>> ' ' in ' ' x) >>> len(' \' ') >>> len(' it\'s ') e. A triple of numbers (a,b,c) is called a Pythagorean triple if a * a + b * b = c * c. In this question, you will be given three numbers. You have to output 1 if the three numbers form a Pythagorean triple. Otherwise, you have to output 0. Note that the inputs may not be given in order: you may have to try all possible orderings of the three numbers to determine whether they form a Pythagorean triple.

4 f. Explain for loop in Python with an example code to print Fibonacci series up to 10 terms. Note: For loop to be explained with this example as theory. Output 2. Attempt any three of the following: 15

5 a. i) Name the following code and explain the same: def recurse(): recurse() Infinite recursion If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. This is known as infinite recursion, and it is generally not a good idea. In most programming environments, a program within finite recursion does not really run forever. Python reports an error message when the maximum recursion depth is reached: ii) def countdown(n): if n <= 0: print ('Blastoff!') else: print( n) countdown(n-1) What will happen if we call this function as seen below? >>> countdown(3) Blastoff! iii) Fermat s Last Theorem says that there are no positive integers a, b, and c such that a n +b n = c n for any values of n greater than 2. Write a function named check_fermat that takes four parameters a, b, c and n and that checks to see if Fermat s theorem holds. If n is greater than 2 and it turns out to be true that a n +b n = c n the program should print, Holy smokes, Fermat was wrong! Otherwise the program should print, Fermat s Theorem holds. Write a function that prompts the user to input values for a, b, c and n, converts them to integers, and uses check_fermat to check whether they violate Fermat s theorem.

6 b. Write a Python program to list all the factorial numbers less than or equal to an input number n. A number N is called a factorial number if it is the factorial of a positive integer. For example, the first few factorial numbers are 1, 2, 6, 24, 120,... Note: We do not list the factorial of 0. Input: A positive integer, say n. All factorial numbers less than or equal to n. Use recursive function to calculate factorial.

7 c. i) Write the output for the following if the variable fruit = 'banana' : >>> fruit[:3] >>> fruit[3:] >>> fruit[3:3] >>> fruit[:] ii) What is the reason for the error seen here? >>> greeting = 'Hello, world!' >>> greeting[0] = 'J' TypeError: 'str' object does not support item assignment The reason for the error is that strings are immutable, which means you can t change an existing string. iii) Explain any 2 methods under strings in Python with suitable examples. >>> word = 'banana' >>> new_word = word.upper() >>> print new_word BANANA >>> word = 'banana' >>> index = word.find('a') >>> print index >>> word.find('na') 2 d. i) Write a function in_both(string1, string2) that does the following: >>> in_both('apples', 'oranges') a

8 e s ii)write a function is_reverse(string1, string2) to return true if string1 is reverse of string2: >>> is_reverse('pots', 'stop') True e. Write a Python code to check whether the given number is a strong number. Strong Numbers are numbers whose sum of factorial of digits is equal to the original number (Example: 145 = 1! +4! + 5!).

9 f. The Ackermann function, A(m,n), is defined: Write a recursive function named ackermann that evaluates Ackermann s function. 3. Attempt any three of the following: 15 a. i) Write the output for the following: 1) >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> print c 2) >>> [1, 2, 3] * 3

10 3) >>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> t[1:3] = ['x', 'y'] >>> print t ii) Explain any 2 methods under lists in Python with examples. Python provides methods that operate on lists. For example, append adds a new element to the end of a list: >>> t = ['a', 'b', 'c'] >>> t.append('d') >>> print t ['a', 'b', 'c', 'd'] extend takes a list as an argument and appends all of the elements: >>> t1 = ['a', 'b', 'c'] >>> t2 = ['d', 'e'] >>> t1.extend(t2) >>> print t1 ['a', 'b', 'c', 'd', 'e'] This example leaves t2 unmodified. sort arranges the elements of the list from low to high: >>> t = ['d', 'c', 'e', 'b', 'a'] >>> t.sort() >>> print t ['a', 'b', 'c', 'd', 'e'] iii) Write the function tail(l) to get the following output: >>> letters = ['a', 'b', 'c'] >>> rest = tail(letters) >>> print rest ['b', 'c'] Output :

11 b. i) What is meant by Variable-length argument tuples? Explain with an example. Functions can take a variable number of arguments. A parameter name that begins with *gathers arguments into a tuple. For example, printall takes any number of arguments and prints them: def printall(*args): print args The gather parameter can have any name you like, but args is conventional. Here s how the function works: >>> printall(1, 2.0, '3') (1, 2.0, '3') The Complement of gather is scatter. If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the * operator. For example, divmod takes exactly two arguments; it doesn t work with a tuple: >>> t = (7, 3) >>> divmod(t) TypeError: divmod expected 2 arguments, got 1 But if you scatter the tuple, it works: >>> divmod(*t) (2, 1) ii) Replace the following set of statements with a tuple assignment. >>> temp = a >>> a = b >>> b = temp a, b = b, a iii) Explain any 3 methods associated with files in Python. Any 3 methods to be explained in one line or with a small code snippet. Open() - The open() function is used to open files in our system Write() - Used to write a fixed sequence of characters to a file Read() - Reads at most size bytes from the file Close() - When you re done with a file, use close() to close it and free up any system resources taken up by the open file Seek() - Sets the file's current position Tell() - Returns the file's current position c. i) What is the significant difference between list and dictionary? A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dictionary they can be (almost) any type. ii) Write a Python code to get the following dictionary as output : {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

12 iii) What is the output of the code given below: >>> squares = {1:1, 2:4, 3:9, 4:16, 5:25} >>> print(squares[5]) >>> print(squares[6]) d. List and explain any five exceptions in Python. NameError: You are trying to use a variable that doesn t exist in the current environment. Remember that local variables are local. You cannot refer to them from outside the function where they are defined. TypeError: There are several possible causes: You are trying to use a value improperly. Example: indexing a string, list, or tuple with something other than an integer. There is a mismatch between the items in a format string and the items passed for conversion. This can happen if either the number of items does not match or an invalid conversion is called for. You are passing the wrong number of arguments to a function or method. For methods, look at the method definition and check that the first parameter is self. Then look at the method invocation; make sure you are invoking the method on an object with the right type and providing the other arguments correctly. KeyError: You are trying to access an element of a dictionary using a key that the dictionary does not contain. AttributeError: You are trying to access an attribute or method that does not exist. If an AttributeError indicates that an object has NoneType, that means that it is None. One common cause is forgetting to return a value from a function; if you get to the end of a function without hitting a return statement, it returns None. Another common cause is using the result from a list method, like sort, that returns None. IndexError: The index you are using to access a list, string, or tuple is greater than its length minus one. e. Given a dictionary d and a key k, it is easy to find the corresponding value v = d[k]. This operation is called a lookup. But what if you have v and you want to find k? What is this operation called? Explain the same by writing a Python code. Reverse Lookup

13 Output Successful reverse lookup: Unsuccessful reverse lookup: f. Explain the following statements: Note: Explanation is necessary for each sub question i) >>> a, b = 1, 2, 3 ValueError: too many values to unpack ii) >>> addr = 'monty@python.org' >>> uname, domain = addr.split('@') The return value from split is a list with two elements; the first element is assigned to uname, the second to domain. >>> print uname monty >>> print domain python.org iii) >>> t = divmod(7, 3) >>> print( t) (2, 1) iv) >>> s = 'abc' >>> t = [0, 1, 2] >>> zip(s, t) {('c', 2), ('a', 0), ('b', 1)} list of tuples v) for index, element in enumerate('abc'): print( index, element)

14 4. Attempt any three of the following: 15 a. Explain the role of the Regular Expressions in the following snippets: i) >>> p = re.compile('\d+') >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping') ii) >>> p = re.compile('ca+t') >>> p.findall('ct cat caaat caaaaaat caaat ctttt cccttt') iii) >>> p = re.compile('ca*t') >>> p.findall('ct cat caaat caaaaaat caaat ctttt cccttt') iv) >>> p = re.compile('a/{1,3}b') >>> p.findall('a/b a//b a///b a/////b ab') v) >>> result=re.findall(r'\w*','av is largest Analytics community of India') >>> print (result) b. Explain Class inheritance in Python with an example. Note : Explanation of the concept along with a sample code is a must. class Person: def init (self, first, last): self.firstname = first self.lastname = last def Name(self): return self.firstname + " " + self.lastname class Employee(Person): def init (self, first, last, staffnum): Person. init (self,first, last) self.staffnumber = staffnum def GetEmployee(self):

15 return self.name() + ", " + self.staffnumber x = Person("Marge", "Simpson") y = Employee("Homer", "Simpson", "1007") print(x.name()) print(y.getemployee()) c. i) How is method overriding implemented in Python? Note : Explanation of the concept along with a sample code is a must. class Parent(object): def init (self): self.value = 5 def get_value(self): return self.value class Child(Parent): def get_value(self): return self.value + 1 c=child() print(c.get_value()) 6 ii) Which methods of Python are used to determine the type of instance and inheritance? Two built-in functions isinstance() and issubclass() are used to check inheritances. Function isinstance() returns True if the object is an instance of the class or other classes derived from it. Each and every class in Python inherits from the base class object. d. Name and explain the magic methods of Python that are used in the initialization and deletion of class objects with the help of a code snippet. i) The method used for initialization is called init, which is a special method. When we call the class object, a new instance of the class is created, and the init method on this new object is immediately executed with all the parameters that we passed to the class object. The purpose of this method is thus to set up a new object using data that we have provided. self is the first parameter, and we use this variable inside the method bodies but we don t appear to pass this parameter in. This is because whenever we call a method on an object, the object itself is automatically passed in as the first parameter. This gives us a way to access the object s properties from inside the object s methods. ii) For deleting objects: class FooType(object): def init (self, id): self.id = id print (self.id, 'born') def del (self):

16 print( self.id, 'died') def make_foo(): print ('Making...') ft = FooType(1) print ('Returning...') return ft print ('Calling...') ft = make_foo() print( 'End...') Calling... Making... 1 born Returning... End... 1 died e. Name the methods in Python Multithreaded Programming. Also mention the module necessary for each of the method. i) A method to spawn another thread thread.start_new_thread() ii) A method to return the number of thread objects that are active threading.activecount() iii) A method that waits for threads to terminate join() iv) A method that returns the name of the thread getname() v) A method that checks whether a thread is still executing. isalive() List and explain the methods used under synchronization of threads. The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock. The acquire(blocking) method of the new lock object is used to force threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock. If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released. The release() method of the new lock object is used to release the lock when it is no longer required. f. Create a module armprime that has two functions, one to check whether the given number is an Armstrong number and the other to check whether the given number is a prime number. Import the above created module in a.py file and show the use of the two functions.

17 5. Attempt any three of the following: 15 a. Write a Python code to create the following GUI:

18 b. Write a Python code to show the following types of message boxes:

19 c. Write a Python code to create the following menu bar : d. Explain the Scrolled text widget in Python. Note : Explanation for each command is necessary. e. Write a Python code to do the following: i) Create a table STUDENT with columns Id (integer, not null, primary key), RollNo (integer, not null), Name (not null, varchar), Class (not null, varchar) and Grade (not null, varchar) in MySQL and insert 4 rows of data. ii) Retrieve the rows where Grade = O

20 f. Write a Python code to do the following:

21 i) Create a table EMPLOYEE with columns Id (integer, not null, primary key), AdhaarNo (integer, not null), Empname (not null, varchar), Empdept (not null, varchar) and Empage (not null, integer) in MySQL and insert 5 rows of data. ii) Update the respective rows to Empdept = ERP where Empage is >=40. Answer

22

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

Algorithms and Programming I. Lecture#12 Spring 2015

Algorithms and Programming I. Lecture#12 Spring 2015 Algorithms and Programming I Lecture#12 Spring 2015 Think Python How to Think Like a Computer Scientist By :Allen Downey Installing Python Follow the instructions on installing Python and IDLE on your

More information

CSC326 Python Sequences i. CSC326 Python Sequences

CSC326 Python Sequences i. CSC326 Python Sequences i CSC326 Python Sequences ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ iii Contents 1 Agenda 1 2 while Statement 1 3 Sequence Overview 2 4 String 2 5 Lists 4 6 Dictionary 5 7 Tuples

More information

Introduction to Python

Introduction to Python Introduction to Python Development Environments what IDE to use? 1. PyDev with Eclipse 2. Sublime Text Editor 3. Emacs 4. Vim 5. Atom 6. Gedit 7. Idle 8. PIDA (Linux)(VIM Based) 9. NotePad++ (Windows)

More information

CGI Architecture Diagram. Web browser takes response from web server and displays either the received file or error message.

CGI Architecture Diagram. Web browser takes response from web server and displays either the received file or error message. What is CGI? The Common Gateway Interface (CGI) is a set of standards that define how information is exchanged between the web server and a custom script. is a standard for external gateway programs to

More information

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

More information

[CHAPTER] 1 INTRODUCTION 1

[CHAPTER] 1 INTRODUCTION 1 FM_TOC C7817 47493 1/28/11 9:29 AM Page iii Table of Contents [CHAPTER] 1 INTRODUCTION 1 1.1 Two Fundamental Ideas of Computer Science: Algorithms and Information Processing...2 1.1.1 Algorithms...2 1.1.2

More information

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

Fundamentals of Programming (Python) Getting Started with Programming

Fundamentals of Programming (Python) Getting Started with Programming Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

ENVIRONMENT DIAGRAMS AND RECURSION 2

ENVIRONMENT DIAGRAMS AND RECURSION 2 ENVIRONMENT DIAGRAMS AND RECURSION 2 COMPUTER SCIENCE 61A February 4, 2016 1 Environment Diagrams An environment diagram keeps track of all the variables that have been defined and the values they are

More information

Compound Data Types 2

Compound Data Types 2 Compound Data Types 2 Chapters 10, 11, 12 Prof. Mauro Gaspari: gaspari@cs.unibo.it Objects and Values We know that a and b both refer to a string, but we don t know whether they refer to the same string.

More information

PYTHON MULTITHREADED PROGRAMMING

PYTHON MULTITHREADED PROGRAMMING PYTHON MULTITHREADED PROGRAMMING http://www.tutorialspoint.com/python/python_multithreading.htm Copyright tutorialspoint.com Running several threads is similar to running several different programs concurrently,

More information

Table of Contents. Preface... xxi

Table of Contents. Preface... xxi Table of Contents Preface... xxi Chapter 1: Introduction to Python... 1 Python... 2 Features of Python... 3 Execution of a Python Program... 7 Viewing the Byte Code... 9 Flavors of Python... 10 Python

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

Compound Data Types 1

Compound Data Types 1 Compound Data Types 1 Chapters 8, 10 Prof. Mauro Gaspari: mauro.gaspari@unibo.it Compound Data Types Strings are compound data types: they are sequences of characters. Int and float are scalar data types:

More information

Variables, expressions and statements

Variables, expressions and statements Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna -

Iteration. Chapter 7. Prof. Mauro Gaspari: Mauro Gaspari - University of Bologna - Iteration Chapter 7 Prof. Mauro Gaspari: gaspari@cs.unibo.it Multiple assigments bruce = 5 print bruce, bruce = 7 print bruce Assigment and equality With multiple assignment it is especially important

More information

Chapter 4. Conditionals and recursion. 4.1 The modulus operator. 4.2 Conditional execution

Chapter 4. Conditionals and recursion. 4.1 The modulus operator. 4.2 Conditional execution Chapter 4 Conditionals and recursion 4.1 The modulus operator The modulus operator works on integers (and integer expressions) and yields the remainder when the first operand is divided by the second.

More information

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

More information

Here n is a variable name. The value of that variable is 176.

Here n is a variable name. The value of that variable is 176. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence

More information

Functional Programming in Haskell for A level teachers

Functional Programming in Haskell for A level teachers Functional Programming in Haskell for A level teachers About this document Functional Programming is now part of the A level curriculum. This document is intended to get those who already have some programming

More information

INTERNATIONAL INDIAN SCHOOL, RIYADH XI XII BOYS SECTION

INTERNATIONAL INDIAN SCHOOL, RIYADH XI XII BOYS SECTION INTERNATIONAL INDIAN SCHOOL, RIYADH XI XII BOYS SECTION Grade- XI COMPUTER SCIENCE Unit I Programming and Computational Thinking 1. What are the functions of computer? 2. Briefly explain the basic architecture

More information

Functions and Recursion

Functions and Recursion Functions and Recursion Chapter 5 Prof. Mauro Gaspari: gaspari@cs.unibo.it Example import math def area(radius): temp = math.pi * radius**2 return temp # or def area(radius): return math.pi * radius**2

More information

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu) I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

INTERNATIONAL INDIAN SCHOOL, RIYADH XI XII BOYS SECTION. Subject- Informatics Practices

INTERNATIONAL INDIAN SCHOOL, RIYADH XI XII BOYS SECTION. Subject- Informatics Practices Grade- XI INTERNATIONAL INDIAN SCHOOL, RIYADH XI XII BOYS SECTION Unit 1 Programming and Computational Thinking Chapter 1 Introduction to Computer Systems 1. What are the functions of computer? 2. What

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 60 20 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E I SEMESTER GE85- Problem Solving and Python Programming Regulation 207 Academic

More information

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

Built-in Types of Data

Built-in Types of Data Built-in Types of Data Types A data type is set of values and a set of operations defined on those values Python supports several built-in data types: int (for integers), float (for floating-point numbers),

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Fall 2016 Structure and Interpretation of Computer Programs Final INSTRUCTIONS You have 3 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

More information

Some material adapted from Upenn cmpe391 slides and other sources

Some material adapted from Upenn cmpe391 slides and other sources Some material adapted from Upenn cmpe391 slides and other sources History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Subject: Computer Science

Subject: Computer Science Subject: Computer Science Topic: Data Types, Variables & Operators 1 Write a program to print HELLO WORLD on screen. 2 Write a program to display output using a single cout statement. 3 Write a program

More information

RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012

RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012 RECURSION 7 COMPUTER SCIENCE 61A October 15, 2012 1 Recursion We say a procedure is recursive if it calls itself in its body. Below is an example of a recursive procedure to find the factorial of a positive

More information

Python Programming: Lecture 2 Data Types

Python Programming: Lecture 2 Data Types Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania Last Week s Quiz 1..pyc files contain byte code 2. The type of math.sqrt(9)/3 is float 3. The type of isinstance(5.5, float)

More information

CITS2401 Computer Analysis & Visualisation

CITS2401 Computer Analysis & Visualisation FACULTY OF ENGINEERING, COMPUTING AND MATHEMATICS CITS2401 Computer Analysis & Visualisation SCHOOL OF COMPUTER SCIENCE AND SOFTWARE ENGINEERING Topic 3 Introduction to Matlab Material from MATLAB for

More information

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013 University of Washington CSE 140 Introduction to Data Programming Winter 2013 Midterm exam February 6, 2013 Name: Solutions UW Net ID (username): This exam is closed book, closed notes. You have 50 minutes

More information

CS 234 Python Review Part 2

CS 234 Python Review Part 2 CS 234 Python Review Part 2 Recap import function: define, return boolean, conditional, branching loop: for, range, while file: open, close, readlines string: split Classes Define blueprint for a custom

More information

OOP and Scripting in Python Advanced Features

OOP and Scripting in Python Advanced Features OOP and Scripting in Python Advanced Features Giuliano Armano Emanuele Tamponi Advanced Features Structure of a Python Script More on Defining Functions Default Argument Values Keyword Arguments Arbitrary

More information

Introduction to Python

Introduction to Python Introduction to Python خانه ریاضیات اصفهان فرزانه کاظمی زمستان 93 1 Why Python? Python is free. Python easy to lean and use. Reduce time and length of coding. Huge standard library Simple (Python code

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1

More information

(f) d={ alchemist :( a, t ), shaman : ( s, n ), wizard : ( w, z )} d[ shaman ][1]

(f) d={ alchemist :( a, t ), shaman : ( s, n ), wizard : ( w, z )} d[ shaman ][1] CSCI1101 Final Exam December 18, 2018 Solutions 1. Determine the value and type of each of the expressions below. If the question has two lines, assume that the statement in the first line is executed,

More information

Bulgarian Math Olympiads with a Challenge Twist

Bulgarian Math Olympiads with a Challenge Twist Bulgarian Math Olympiads with a Challenge Twist by Zvezdelina Stankova Berkeley Math Circle Beginners Group September 0, 03 Tasks throughout this session. Harder versions of problems from last time appear

More information

Introduction to Python

Introduction to Python Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

Creating a new data type

Creating a new data type Appendix B Creating a new data type Object-oriented programming languages allow programmers to create new data types that behave much like built-in data types. We will explore this capability by building

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Programming in Python

Programming in Python 3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want

More information

cs1114 REVIEW of details test closed laptop period

cs1114 REVIEW of details test closed laptop period python details DOES NOT COVER FUNCTIONS!!! This is a sample of some of the things that you are responsible for do not believe that if you know only the things on this test that they will get an A on any

More information

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS (download slides and.py files and follow along!) 6.0001 LECTURE 7 6.0001 LECTURE 7 1 WE AIM FOR HIGH QUALITY AN ANALOGY WITH SOUP You are making soup but bugs

More information

Python lab session 1

Python lab session 1 Python lab session 1 Dr Ben Dudson, Department of Physics, University of York 28th January 2011 Python labs Before we can start using Python, first make sure: ˆ You can log into a computer using your username

More information

Decisions, Decisions. Testing, testing C H A P T E R 7

Decisions, Decisions. Testing, testing C H A P T E R 7 C H A P T E R 7 In the first few chapters, we saw some of the basic building blocks of a program. We can now make a program with input, processing, and output. We can even make our input and output a little

More information

UNIVERSITÀ DI PADOVA. < 2014 March >

UNIVERSITÀ DI PADOVA. < 2014 March > UNIVERSITÀ DI PADOVA < 2014 March > Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. Easy-to-read: Python code is much more clearly defined and visible

More information

Formulas and Functions

Formulas and Functions Conventions used in this document: Keyboard keys that must be pressed will be shown as Enter or Ctrl. Controls to be activated with the mouse will be shown as Start button > Settings > System > About.

More information

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1

A First Look at ML. Chapter Five Modern Programming Languages, 2nd ed. 1 A First Look at ML Chapter Five Modern Programming Languages, 2nd ed. 1 ML Meta Language One of the more popular functional languages (which, admittedly, isn t saying much) Edinburgh, 1974, Robin Milner

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Fall 206 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

Python Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ]

Python Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ] Python Lists Chapter 8 Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution.0 License. http://creativecommons.org/licenses/by/.0/. Copyright 2010,

More information

Iterators & Generators

Iterators & Generators Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:

More information

CS150 - Sample Final

CS150 - Sample Final CS150 - Sample Final Name: Honor code: You may use the following material on this exam: The final exam cheat sheet which I have provided The matlab basics handout (without any additional notes) Up to two

More information

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2 Basic Concepts Computer Science Computer - Science - Programming history Algorithms Pseudo code 2013 Andrew Case 2 Basic Concepts Computer Science Computer a machine for performing calculations Science

More information

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python About Python Python course is a great introduction to both fundamental programming concepts and the Python programming language. By the end, you'll be familiar with Python syntax and you'll be able to

More information

Computer Programming C++ (wg) CCOs

Computer Programming C++ (wg) CCOs Computer Programming C++ (wg) CCOs I. The student will analyze the different systems, and languages of the computer. (SM 1.4, 3.1, 3.4, 3.6) II. The student will write, compile, link and run a simple C++

More information

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Basics of Python Summer 2012 Instructor: Hassan Khosravi Python A simple programming language to implement your ideas Design philosophy emphasizes code readability Implementation of Python was

More information

Introduction to MATLAB

Introduction to MATLAB Introduction to MATLAB The Desktop When you start MATLAB, the desktop appears, containing tools (graphical user interfaces) for managing files, variables, and applications associated with MATLAB. The following

More information

a b c d a b c d e 5 e 7

a b c d a b c d e 5 e 7 COMPSCI 230 Homework 9 Due on April 5, 2016 Work on this assignment either alone or in pairs. You may work with different partners on different assignments, but you can only have up to one partner for

More information

CSI Lab 02. Tuesday, January 21st

CSI Lab 02. Tuesday, January 21st CSI Lab 02 Tuesday, January 21st Objectives: Explore some basic functionality of python Introduction Last week we talked about the fact that a computer is, among other things, a tool to perform high speed

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

RECURSION, RECURSION, (TREE) RECURSION! 2

RECURSION, RECURSION, (TREE) RECURSION! 2 RECURSION, RECURSION, (TREE) RECURSION! 2 COMPUTER SCIENCE 61A February 5, 2015 A function is recursive if it calls itself. Below is a recursive factorial function. def factorial(n): if n == 0 or n ==

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

More information

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,

More information

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

CPD for GCSE Computing: Practical Sheet 6 February 14

CPD for GCSE Computing: Practical Sheet 6 February 14 Aims Programming Sheet 6 Arrays in Python Section Aim 1 Arrays A variable with many values Understand the idea of an array as a way to combine many values that are assigned to as single variable. 2 While

More information

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

Excerpt from Art of Problem Solving Volume 1: the Basics 2014 AoPS Inc. Chapter 5 Using the Integers In spite of their being a rather restricted class of numbers, the integers have a lot of interesting properties and uses. Math which involves the properties of integers is

More information

1ο Φροντιστήριο Τεχνητής Νοημοσύνης. Διαδικαστικά και εισαγωγή στην Python

1ο Φροντιστήριο Τεχνητής Νοημοσύνης. Διαδικαστικά και εισαγωγή στην Python 1ο Φροντιστήριο Τεχνητής Νοημοσύνης Διαδικαστικά και εισαγωγή στην Python Διαδικαστικά (1) Διαλέξεις: Τετάρτη 11:00-14:00 στην αίθουσα Α1 Φροντιστήρια: Τρίτη 15:00-16:00 στην αίθουσα Α2 Σελίδα μαθήματος:

More information

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling COMP1730/COMP6730 Programming for Scientists Exceptions and exception handling Lecture outline * Errors * The exception mechanism in python * Causing exceptions (assert and raise) * Handling exceptions

More information

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Some material adapted from Upenn cmpe391 slides and other sources Invented in the Netherlands,

More information

Programming with Python

Programming with Python Programming with Python Dr Ben Dudson Department of Physics, University of York 21st January 2011 http://www-users.york.ac.uk/ bd512/teaching.shtml Dr Ben Dudson Introduction to Programming - Lecture 2

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Discussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage:

Discussion 2C Notes (Week 5, February 4) TA: Brian Choi Section Webpage: Discussion 2C Notes (Week 5, February 4) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Recursion A recursion is a function-writing technique where the function

More information

Use recursion to write a function that duplicates the following function: (def (f L) (map (lambda (x) (+ (sqr x) x)) L))

Use recursion to write a function that duplicates the following function: (def (f L) (map (lambda (x) (+ (sqr x) x)) L)) Write a function (multiply-each L n). It consumes a (listof Num) and a Num, and returns the list containing all the values in L, each multiplied by n. (multiply-each (list 2 3 5) 4) => (list 8 12 20) Write

More information

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu) I. INTERACTIVE MODE VERSUS SCRIPT MODE There are two ways to use the python interpreter: interactive mode and script mode. 1. Interactive Mode (a) open a terminal shell (terminal emulator in Applications

More information

EASY

EASY Downloaded from: justpaste.it/hsfm ------------------------------- EASY ------------------------------- NUMBERS Even or Odd Write a program that accepts a number and returns whether the number is equal

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Summer 2014 Structure and Interpretation of Computer Programs Final Solutions INSTRUCTIONS ˆ You have 3 hours to complete the exam. ˆ The exam is closed book, closed notes, and closed electronics,

More information

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0 INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0 OCTOBER 2014 Python Selection and Conditionals 1 SELECTION AND CONDITIONALS WHAT YOU MIGHT KNOW ALREADY You will probably be familiar

More information

Classes and Objects 1

Classes and Objects 1 Classes and Objects 1 Built-in objects You are already familiar with several kinds of objects: strings, lists, sets, tuples, and dictionaries An object has two aspects: Some fields (or instance variables)

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

RECURSION, RECURSION, (TREE) RECURSION! 3

RECURSION, RECURSION, (TREE) RECURSION! 3 RECURSION, RECURSION, (TREE) RECURSION! 3 COMPUTER SCIENCE 61A September 18, 2013 A function is recursive if it calls itself. Below is recursive factorial function. def factorial(n): if n == 0 or n ==

More information

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

CMSC 201 Fall 2016 Lab 09 Advanced Debugging CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working

More information

Midterm Exam 2B Answer key

Midterm Exam 2B Answer key Midterm Exam 2B Answer key 15110 Principles of Computing Fall 2015 April 6, 2015 Name: Andrew ID: Lab section: Instructions Answer each question neatly in the space provided. There are 6 questions totaling

More information