Python lab session 1

Similar documents
Programming with Python

Using IDLE for

Types, lists & functions

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Lecture 1: Hello, MATLAB!

Department of Electrical Engineering and Computer Science MASSACHUSETTS INSTITUTE OF TECHNOLOGY

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

UCT Algorithm Circle: Number Theory

CS1110 Lab 1 (Jan 27-28, 2015)

Boolean Logic & Branching Lab Conditional Tests

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

6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1

Creating a new data type

C++ Support Classes (Data and Variables)

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

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

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Lab 7: OCaml 12:00 PM, Oct 22, 2017

Downloaded from Chapter 2. Functions

CSCE 110 Programming I

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

Our Strategy for Learning Fortran 90

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

Python Programming Exercises 1

Introduction to Scientific Computing

Text Input and Conditionals

Introduction to: Computers & Programming: Review prior to 1 st Midterm

CS1110 Lab 6 (Mar 17-18, 2015)

Basic Data Types and Operators CS 8: Introduction to Computer Science, Winter 2019 Lecture #2

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

Introduction to MATLAB

CPSC 121 Some Sample Questions for the Final Exam Tuesday, April 15, 2014, 8:30AM

ECE G205 Fundamentals of Computer Engineering Fall Exercises in Preparation to the Midterm

Condition Controlled Loops. Introduction to Programming - Python

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) First Name: Last Name: NetID:

Fundamentals: Expressions and Assignment

An Introduction to MATLAB

CHAPTER 4 FUNCTIONS. Dr. Shady Yehia Elmashad

Introduction to Python. Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas

x= suppose we want to calculate these large values 1) x= ) x= ) x=3 100 * ) x= ) 7) x=100!

Lecture 6: Arithmetic and Threshold Circuits

The Very Basics of the R Interpreter

Calculations with Sig Figs

Module 10: Imperative Programming, Modularization, and The Future

CMSC 201 Spring 2017 Lab 05 Lists

Course Outline Introduction to C-Programming

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

Organisation. Assessment

Com S 127x - Lab 6 1. READING FLOWCHARTS WITH CONDITIONAL ACTIONS!

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >:

15-122: Principles of Imperative Computation, Fall 2015

Hello, World! An Easy Intro to Python & Programming. Jack Rosenthal

UNIVERSITY OF ENGINEERING & MANAGEMENT, KOLKATA C ASSIGNMENTS

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Divisibility Rules and Their Explanations

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

Lecture Notes for Chapter 2: Getting Started

Introduction to Computer Programming for Non-Majors

PROGRAMMING IN C AND C++:

Get to Know Your Calculator!

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

CSci 1113, Spring 2018 Lab Exercise 3 (Week 4): Repeat, Again and Again

Week - 03 Lecture - 18 Recursion. For the last lecture of this week, we will look at recursive functions. (Refer Slide Time: 00:05)

Introduction to Computer Programming for Non-Majors

1) Log on to the computer using your PU net ID and password.

Lecture 3. Input, Output and Data Types

Intro. Scheme Basics. scm> 5 5. scm>

CMSC 201 Spring 2019 Lab 06 Lists

CS : Computer Programming, Spring 2000 Programming Project #1: Thinking of a Number Due in class Thursday 27 January 2000

If Statements, For Loops, Functions

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Lecture Numbers. Richard E Sarkis CSC 161: The Art of Programming

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

2.Simplification & Approximation

CMSC 201 Spring 2017 Lab 12 Recursion

3+2 3*2 3/2 3^2 3**2 In matlab, use ^ or ** for exponentiation. In fortran, use only ** not ^ VARIABLES LECTURE 1: ARITHMETIC AND FUNCTIONS

Content Design Structure, Scope & Sequence of Mathematics Content Addressed Within Numbers Up! Volcanic Panic

Part 1. Summary of For Loops and While Loops

Lecture Notes, CSE 232, Fall 2014 Semester

LAB 1 Binary Numbers/ Introduction to C. Rajesh Rajamani. ME 4231 Department of Mechanical Engineering University Of Minnesota

Fall 2018 Lecture 1

Week 1: Introduction to R, part 1

Python for Astronomers. Week 1- Basic Python

Testing. UW CSE 160 Winter 2016

Modular Arithmetic. Marizza Bailey. December 14, 2015

CS 1110, LAB 10: ASSERTIONS AND WHILE-LOOPS 1. Preliminaries

Scientific Computing: Lecture 1

CSE 115. Introduction to Computer Science I

Computational Modelling 102 (Scientific Programming) Tutorials

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

Excel Basics Rice Digital Media Commons Guide Written for Microsoft Excel 2010 Windows Edition by Eric Miller

Introduction to MATLAB

CMSC 201 Fall 2016 Lab 13 More Recursion

ASCII Art. Introduction: Python

n! = 1 * 2 * 3 * 4 * * (n-1) * n

Introduction to Computer Programming for Non-Majors

Variables and Typing

Transcription:

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 and password ˆ You have a CD with portable Python on it. This should work on all Windows computers, so you should be able to use this on your laptops or at home as well If you have any trouble with this, ask one of the demonstrators. As you go through this lab script, you ll see tasks to complete in these boxes. Each week, create a new Word document to write your answers in. Put your answer to each task in a different section. At the end of each lab session, email this document to phys-python@york.ac.uk If you have problems at any point, or don t understand anything in this lab script then please ask one of the demonstrators. Each section is independent, so if you get stuck with one problem you can try another one and come back to it later. Getting started Start by creating a new folder called python in your My Documents directory, where you can put all your Python programs. From now on I ll refer to this as your python directory. Put the Python CD in the drive, and double-click on SPE-portable. SPE is a socalled Integrated Development Environment, which allows you to write and run Python programs interactively, and gives you help on functions and finding mistakes. It is possible to use something like Notepad to write Python programs, but using programs like SPE make programming easier and quicker. 1

Python lab 1 2 As is traditional, we ll start with a Hello, World! program. In the editing window on the right, enter the following: print Hello, World! Save this file as hello.py in your python directory (using the usual File Save As menu). Note: All python files should end in.py to avoid any problems. This just makes it clear to the computer that it s a Python program and not just an ordinary text document. To run this program, press Ctrl-Shift-R. At the bottom of the window, you should see the program run and print out Hello, World!. Congratulations! You ve written your first Python program. As you go through this lab script, you should create a new python file for each task. Calculations Python includes the following basic operations Power A ** B A B Multiply A * B A B Divide A / B A/B Add A + B A + B Subtract A B A B Task 1 Calculations (15%) Write programs to read in a value of x, then calculate the following expressions: (a) x 2 x 2 + 1 (b) 2 x+1 (c) x 2x For each program, you can start with the following code x = 1.638453 print ##### where you need to replace ##### with your code. Copy and paste your 3 programs into your lab document, and give the result for each one.

Python lab 1 3 Task 2 Create a function (15%) Create a function ctof which converts temperature from Celsius to Fahrenheit using F = 9 5 C + 32 Check that ctof(21.) produces the result 69.8. Start with the following incomplete code: def c t o f (C) : return # Missing print c t o f ( 2 1. ) code Copy and paste your program into your lab document. One of the advantages of using functions is that once we ve got it working once, we can reuse it many times. Task 3 Looping (20%) Write a program which uses your ctof function to print out a table of Fahrenheit and Celsius. Starting at 0 o C, go up in steps of 10 o C to 100 o C. Print out column headers so your output looks something like Celsius Fahrenheit 0.0 32.0 10.0 50.0 (don t worry about getting the columns to line up) Copy and paste your program and output table into your lab document.

Python lab 1 4 Recursive functions We can call functions to get results, but functions can also call themselves. These are then called recursive functions, and are often a concise way to define functions. If a function is calling itself, then it needs some way to stop: otherwise the function will just keep calling itself forever. We therefore need to define some cases which can be calculated without calling itself. For example, the function for calculating the factorial was: def f a c t o r i a l (N) : i f N < 2 : return 1 else return N * f a c t o r i a l (N 1) Here we first say that the factorial of any number less than 2 is 1. We can then define all the other results in terms of these cases. This is very similar to proof by induction in mathematics. Another example of a problem which can be solved elegantly using recursive functions involves the Fibonacci sequence of numbers. This is F = 1,1,2,3,5,8,13,21,34,55,... The first two are defined as 1, but then all others are the sum of the two before it: { 1 if N < 3, f (N) = f (N 1) + f (N 2) otherwise Task 4 Fibonacci sequence (15%) a) Write a function called fibonacci to calculate the N th Fibonacci number. Use it to calculate the 10th, 20th and 30th Fibonacci number and put those (along with your program) into your lab document. b) Why is the recursive method not very efficient for this problem? Write your answer in your lab document

Python lab 1 5 Prime numbers In addition to the operations **, *, /, + and -, Python has another operation on numbers: the remainder or modulus. When you divide one integer by another, you get an integer result, so 7/3 gives the result 2, with remainder 1 (since 7 = 2 3 + 1). To get this remainder in Python, you can use the % operation, so 7 % 3 gives the remainder 1. One use for this is to test if x is a multiple of y, because this only happens when the remainder is zero. A prime number is one which can only be divided by 1 and itself. The following flow chart gives an algorithm for checking if a number is prime or not. i i + 1 No Input N i = 2 i 2 N? Yes N%i = 0? No return True Yes return False In Python, we can use True and False as values. When we have an if statement like i f A > 4 : print A i s g r e a t e r than 4 what happens is that Python compares A against 4 to calculate (A>4). This produces a result True or False. The if statement runs the following commands only if it is given True. Therefore, we could write i f True : print This code w i l l always run The if statement just needs a True or False value, but this could also come from a function. Therefore we could also write def t e s t ( number ) : i f number > 4 : return True else return False i f t e s t (A) : print A p a s s e s the t e s t

Python lab 1 6 Since the result of number > 4 is True or False, we could even write this as def t e s t ( number ) : return number > 4 i f t e s t (A) : print A p a s s e s the t e s t Task 5 Prime number function (15%) Write a function to implement the algorithm above: given a number N, return either True or False. You can start with the following def isprime (N) : ##### i = 2011 i f isprime ( i ) : print Prime number else : print Not a prime number Is 2011 a prime number or not? Answer in lab document along with your program

Python lab 1 7 Divide and conquer In the problem sheet, the following method was used to guess a number m between 1 and N. find m s = 1, f = N g = (s + f) /2 g == m? Yes Answer g No s = g Yes m > g? f = g No This works by searching for an answer between s and f. Each time around the loop, it looks at the half-way point g = (s + f) /2. If this number is too high, then the result must be in the lower half of the range, and if it s too low then the answer must be in the upper half of the range. The range s f is adjusted and the loop begins again. Task 6 Square root function (10%) Adapt the above search algorithm to find the square root x of a number x i.e the number g which satisfies g 2 = x. The size of the range (f s) is the error in the result; keep searching until this error is less than 10 5. Write this as a function sqrt which takes a number as input and returns the result. You should start with the following code: def s q r t ( x ) : ##### x = 42.4242 print square root o f x i s, s q r t ( x ) Copy and paste the program and the answer into your lab document

Python lab 1 8 The function you have just written can be generalised to find the y th root of a number i.e. the number r such that r y = x. This needs to be a function of two parameters (x and y). Task 7 General root function (10%) Adapt your square root function to calculate the y th root of x. You should start with the following code: def root ( x, y ) : ##### x = 53.936 y = 3 r = root ( x, y ) print the %f t h root o f %f i s %f % ( y, x, r ) Note that we ve used a slightly different way to print out our results. We could have written it by separating the numbers and text with commas: print the, y, th root o f, x, i s, r This is good for small number of outputs, but can become difficult to read. The alternative format uses a %f to mean a floating point number, and takes them in order from the brackets at the end of the line. Hence the first %f is replaced with y, the second with x, and the third with r. Both formats for printing output are valid, it s just a matter of personal preference which you use. In general the % method allows more control over what the output looks like. For example you can use %.2f to print only 2 decimal places, and %E to print in scientific notation (e.g. 1.32e-2).