Computer Lab 1: Introduction to Python

Size: px
Start display at page:

Download "Computer Lab 1: Introduction to Python"

Transcription

1 Computer Lab 1: Introduction to Python 1 I. Introduction Python is a programming language that is fairly easy to use. We will use Python for a few computer labs, beginning with this 9irst introduction. The goals of this 9irst lab is to: get you comfortable using Python in both the interactive shell and with a script learn some basic programming learn to program and use a function learn about for loops learn about conditional statements use built- in functions from numpy (Numerical Python) use arrays make a plot There are many online resources including personal.umich.edu/~mejn/computational- physics/ (This second link has an appendix on the difference between python versions.) II. Starting Python There are several ways to use Python. You may use it on your computer (the download is free) or on the computers in the Computer Lab (VAN 201). In the computer lab, after you have logged into one of the computers, open a web browser and set up a CLAS Linux account. Do this by going to Then use to sign in through the web and use the linux account. When you do this, you click the + sign for a new session, and I picked the MATE system tool. Then I was able to open a terminal window from the drop- down Applications menu (Konsole in the System Tools). On my laptop with Python installed, I just open a terminal window (I have a mac with Xquartz.) I then typed (the $ is the command line prompt) on my mac: $ python (On the MATE Konsole, the command line prompt is %, so it looks like % python.) On my mac computer, this results in the output: 1 By M. H. Reno and J. Unmuth- Yockey, version

2 Python (default, Jan , 08:29:18) [GCC Compatible Apple LLVM (clang )] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> The >>> means we are in interactive mode in Python, and the 9irst line says that I have Python 2.7. (There is also a version 3. You can use whatever version you want.) What we will the interactive mode here to begin, although in the last exercise, we will use a Python script instead. To get out of Python interactive mode, type the following (including the parentheses): >>> quit() There are several ways to proceed including: keep working in interactive mode, use IDLE (Integrated Development and Learning Environment) or the Wing IDE (Integrated Development Environment). The IDLE or IDE environment will allow you to save your work, while for the interactive mode, you will need to periodically copy and paste into a word document to show what you have done for the requested tasks. (The tasks are written in italics.) Which ever way you chose, you will print your commands and results to hand in for this lab. In IDLE you can save the 9ile with a.txt extension in text format which will allow you to print the text 9ile. Do this for the following exercises. To use IDLE, instead of typing $ python, type $ idle in the terminal window. This will open a new window, a Python shell with the >>> indicating it is ready to accept statements. Within IDLE, however, it is possible to open a 9ile, say a new 9ile from the drop- down menu in File, and write in the 9irst line print hello world Then save as test.py (9ile name test, 9ile type py for python). Now you have the option under the menu Run to Run Module which will then execute all the lines (of which there is one) in test.py, the output hello world will be in the shell window. You can save the shell window output by using the File menu save copy as testoutput.txt. 2

3 III. Basics Everything after the hashtag # is a comment, namely, nothing after # is executed. In the statements below, after the, type <return> to get the >>>. After <return> on the second line (print <return>), python returns the result (6), etc. >>> #This is a comment statement... >>> print >>> print 2*3 6 >>> print 2**3 #2 to the power 3 8 >>> 2*3**2 #the usual order of operations 18 >>> (2*3)**2 36 Assignment statements set or reset values of variables. Here we have variables a and b: >>> a=2 >>> b=3 >>> print a+b 5 >>> x=a+b >>> print x 5 Assignment statements are not equations. You can reassign values, using the old values. For example, here we have that x=5, and we can increase the value by one in the following way. >>> print x 5 >>> x=x+1 >>> print x 6 (Python also has a special way of writing this by combining + and =: >>> x = 5 >>> x += 1 >>> print x 6 >>> x += 2 >>> print x 8 3

4 but we will stay with the explicit assignment statement for now.) One feature of Python and many other computer programs is that integers are treated differently than real numbers. Look at the following in Python 2.7: >>> 1/2 0 >>> 1./2 0.5 >>> 1/ The 9irst expression 1/2 is the division of integer 1 by integer 2, and the result is the integer 0. If either numerator or denominator is real, then the result returned is real. You can make even the 9irst expression yield 0.5 with the following: >>> from future import division >>> 1/2 0.5 (Before and after future are two underscores.) You may wish to start every interactive session with this line to allow you to avoid getting 0 when you take 1/2. There is another useful symbol called modulo, %. Modulo returns the remainder between two numbers, like this. >>> 8 % 2 # remainder of 8 divided by 2 0 >>> 8 % 3 # remainder of 8 divided by 3 2 >>> 8 % 5 3 >>> 8 % 6 2 Alternatively, it s also like a clock, where counting from 0 to 8 brings you back to the start: >>> 2 % 8 2 >>> 6 % 8 6 >>> 8 % 8 0 >>> 9 % 8 1 >>> 10 % 8 4

5 2 From this you can see % gives the remainder of division between the two numbers. The wording associated with this symbol is like 8 mod 2 equals 0, or 3 mod 8 equals 3. Write some sample lines like the ones listed in this section to test out at least four simple arithmetic operations. Check to see if the case (upper or lower case) of the variable name is relevant in Python. What do you >ind? IV. Functions You can de9ine your own functions. In the code below from my copy and paste, the lines wrap they were all in one line in the terminal: >>> def myfunc(a,b):... """This function takes inputs a and b to form myfunc=(a +b)**2"""... #note that I need to indent four spaces for everything below def... y=(a+b)**2... return y... >>> # <return> after the last (empty) line... >>> a1 = 1 >>> b1 = 1.5 >>> z = myfunc(a1,b1) >>> print z 6.25 >>> a1=2 >>> b1=6 >>> z = myfunc(a1,b1) >>> print z 64 The variables a and b in myfunc are just stand- ins for the variables that you will input when you call the function (here I use a1 and b1). The triple quotes are a comment in the function. After the function is executed (to 9ind z here), the values of a,b and y in myfunc are lost. E.g., >>> print y Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'y' is not defined 5

6 For a function that you want to use in many places, you can save it (or multiple functions) in a 9ile in the same directory as where you start python (your working directory). Here is an example 9ile that I have called myfunctions.py, in which I have: def myfunc2(a,b): """ myfunc2 = (a+b)**2 """ y = (a+b)**2 return y def myfunc3(a,b): """ myfunc3 = (a+b)**3 """ y = (a+b)**3 return y In Python, I then execute the following commands to get results: >>> from myfunctions import myfunc2, myfunc3 >>> a1 = 2 >>> b1 = 3 >>> z = myfunc2(a1,b1) >>> print z 25 >>> z = myfunc3(a1,b1) >>> print z 125 Another way to get these functions to work is to do the following: >>> import myfunctions >>> a1=2 >>> b1=3 >>> z=myfunctions.myfunc2(a1,b1) >>> print z 25 I need myfunctions. before myfunc2 because myfunc2 resides in the myfunctions module. Yet another way to do this is to make a nickname (alias) for myfunctions (here called mf): >>> import myfunctions as mf >>> a1 = 2 >>> b1 = 3 >>> z = mf.myfunc2(a1,b1) >>> print z 25 I can 9ind the contents of myfunctions (nicknamed mf) by dir (mf): 6

7 >>> dir (mf) [' builtins ', ' doc ', ' file ', ' name ', ' package ', 'myfunc2', 'myfunc3'] Make up two functions of your own and try them out, by saving them in a >ile and importing them, to get results. Hand in both your functions and how they run in Python. V. `For loops Now we will learn the bread and butter of iterations. Whenever you want to iterate over data or have a task repeat you will use a `for loop. mini- section on `range function as part of the `for loops, one will often use the function `range. This function returns a list of numbers. >>> range(0, 5) [0, 1, 2, 3, 4] and it starts from zero and goes up to N- 1, for whatever N you put in. Here, N=5, so the list of 5 numbers goes from 0 to 4. Now lets see a for loop and range together: >>> for i in range(0, 5): >>> print i Here you can see in an example what the for loop does and how the range function is involved. for i in range(0, 5): means in english: for each thing that the range function makes: meaning for each number in the list [0, 1, 2, 3, 4]:. The print i means in english print the current thing, in this case print the current number. FYI using `i is not needed, the only words in this case that need to be there are for, and in, you could have wrote for x in range(0, 10): and then printed all the numbers from 0 to 9. Just like in function de9initions, everything you want to do for i in the range speci9ied you must put in lines indented the same way. Try to anticipate what the following code will do: >>> x = 0 >>> for i in range(0, 5): >>> x = x + i >>> print x 7

8 after thinking about it for a minute, run it and see what happens. Take one more minute to try and understand what happened > x was set to zero > we told the computer to loop through the numbers [0, 1, 2, 3, 4] using the variable i > the computer evaluates the right side of the equal sign (x + i), in this case (0 + 0), and assigns that value to x. > it then prints the value of x. > the computer evaluates the right side of the equal sign (x + i), in this case (0 + 1), and assigns that value to x. > it then prints the value of x. > the computer evaluates the right side of the equal sign (x + i), in this case (1 + 2), and assigns that value to x.... Make a for loop that prints 0, 2, 4, 6, 8, 10. Make another for loop that does what ever you want it to so long as it doesn t return an error and it does what you thought it would! VI. Conditional Statements Now we will use some logic with english words, in the form of conditional statements. This is done with the words if, elif, and else. We will use an example to show their use: >>> x = 4 # declare the value of x >>> if (x < 4): # test to see if x is less than four >>> print x is smaller than 4 >>> elif (x == 4): # test to see if x equals four >>> print x is 4! >>> else: # what to do if the other situations are false >>> print x must be larger than 4 x is 4! The computer goes through this line by line and checks the condition in each case. First it checks to see if x is less than 4, when that turns out to be false, it moves on without running the indented code below. Then on to the else- if statement and checks to see if x equals 4. That part turned out to be true and so it ran the code indented underneath. It never made it to the else part because one of the cases was true before getting there so it just skipped that part. You can include as many elif statements you want, or not at all. In fact you can just use only the if part if you want. 8

9 >>> x = 2 # declare the value of x >>> if (x < 12): # check to see if x is less than twelve >>> x = 5 # change the value of x to 5 >>> print x # print the value of x 5 Let me do one more example that is somewhat practical. I will make a function that is the square wave function. Here you can see the value of a function and using conditionals. def square_wave(t, period): # define the function, it s name and the arguments it has returns the value of the step function for any t. y = t % period # make a new variable in the interval of the period if (y <= period/2.): # check to see if the variable is less than or equal to half the period return 1.0 # if yes, return 1 else: return -1.0 # if not, return 0. Write your own conditional set-up, it can be anything you want as long as it doesn t return an error and it does what you wanted it to do! VII. Built-in Functions: numpy module Good news, there are many built in functions. To access basic functions like trigonometic functions and the square root, you need to import numpy (short for Numerical Python). You can 9ind the complete list of functions in numpy with the dir (numpy) command after you import it. A common nickname is np. We will use trigonometric functions. In the code below, I show that pi is de9ined in numpy, but that numpy must be identi9ied (with nickname np here) every time you use pi: use np.pi, not pi. >>> import numpy as np >>> print np.pi >>> x = np.sin(pi/2) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'pi' is not defined >>> print np.sin(np.pi/2) 1.0 Evaluate the cosine function at 30, 60 and 90 degrees. Note that the inputs to the trigonometric functions are in radians. Use Python to do all the conversions. VIII. Arrays 9

10 Numpy also allows for arrays. You can think of an array as a row or column vector (although whether it is a row or column is a little bit more technical), or n1 by n2 matrix for integers n1 and n2, etc. We will look at one- dimensional arrays. Since we will be looking at trig functions, let s call the array theta, and we will give it 21 values. For a start, we can set all the values to zero: >>> theta = np.zeros(21) >>> print theta [ ] or ones: >>> theta = np.ones(21) >>> print theta [ ] or 21 values equally spaced between pi and +pi: >>> theta = np.linspace(-np.pi,np.pi,21) >>> print theta [ ] The arrays start with the label 0: theta[0] is the first value, and this one ends with theta[20], so there are 21 values in all. We can print: >>> print theta[0] We can get the sine of theta for each of the 21 values with the following: >>> y = np.sin(theta) >>> print y [ e e e e e e e e e e e e e e e e e e e e e-16] Notice that the output is in scienti9ic notation: e.g., = 3.09e- 01, and there is 10

11 some round- off error so that y[0] is a number close to zero, but not exactly zero. For 25 equally spaced values of theta between pi and pi, use Python to evaluate cosine(theta). IX. Plotting Python has a particularly easy to use graphing module called matplotlib.pylab. Lets plot our sine function. First import matplotlib.pylab (nickname plt), then add a few commands. Using y=sin(theta) and theta from the previous section: >>> import matplotlib.pylab as plt >>> plt.plot(theta,y) [<matplotlib.lines.line2d object at 0x10c2e3750>] >>> plt.xlabel('angle [rad]') <matplotlib.text.text object at 0x10c260050> >>> plt.ylabel('sin(theta)') <matplotlib.text.text object at 0x10c273f50> >>> plt.axis('tight') ( , , -1.0, 1.0) >>> plt.show() The output from the last command appears in a new window as a.png 9ile. As you can see from the 9igure on the next page, the tight command presets the minimum and maximum values of the axes based on minimum and maximum x and y values. 11

12 Let s make this look a little nicer, and we can also plot the cosine function on the same 9igure. I can do this interactively (which I just tried to do, and made mistakes, so needed to redo) or this time, I will make a python script named sincos.py. The contents are below: # sincos.py # standard starting commands from future import division import numpy as np import matplotlib.pylab as plt theta = np.linspace(- np.pi,np.pi,21) y = np.sin(theta) z = np.cos(theta) plt.plot(theta,y,linestyle='- ',color='blue',label='sine') plt.plot(theta,z,linestyle='- - ',color='magenta',label='cosine') plt.axis([- np.pi,np.pi,- 1.1,1.1]) plt.xlabel('$\\theta$ [rad]') plt.ylabel('$f(\\theta)$') plt.legend(frameon=false) plt.show() 12

13 Then in the terminal command line (not in Python), I type the following to get the 9igure: $ python sincos.py You can see that I can get Greek letters, labeled lines, etc. The Greek letters come from using a computer typesetting program called LaTeX (see the Appendix). Sometimes Python gets confused with the backslash \ used in LaTeX because to continue a line in Python, a backslash is used. The double backslash \\ seems to work with LaTeX. Your exercises for this part are 1) to plot (sin(2 theta))**2 for the angle range of pi to pi, and 2) to make up another function f(x) to plot between x=1-100 on a log-log plot. You will need to look on the internet to see the commands to do a log-log plot. In the plot window for 2), use matplotlib commands to write the function that you used. Please hand a copy of the commands you use, plus the plot for each of these two exercises. X. Final Remarks 13

14 As you could see with the previous exercise, there are extensive online resources for Python with lots of sample code. Something you want to do? Search for some key words and then do it! Appendix. LaTeX LaTeX is a typesetting system that is used in the preparation of manuscripts. The American Physical Society journals require electronic submission, and manuscripts submitted in a form that they can use directly are eligible for a reduction of page charges. LaTeX is one of the formats. We use LaTeX here to generate Greek letters. In normal LaTeX, to get a symbol, one uses the $ to indicate the beginning of a math symbol (which Greek letters are) and another $ to indicate the end. The symbol for the Greek letter beta is \beta. In LaTeX, $\beta$ results in β. As mentioned above, Python gets confused with backslash \, so by using $\\beta$, Python will not get confused. In normal LaTeX, you can t use \\ for this. To lookup symbols in LaTeX use For more information about LaTeX, check out project.org/ 14

Python Programming Exercises 1

Python Programming Exercises 1 Python Programming Exercises 1 Notes: throughout these exercises >>> preceeds code that should be typed directly into the Python interpreter. To get the most out of these exercises, don t just follow them

More information

Starting. Read: Chapter 1, Appendix B from textbook.

Starting. Read: Chapter 1, Appendix B from textbook. Read: Chapter 1, Appendix B from textbook. Starting There are two ways to run your Python program using the interpreter 1 : from the command line or by using IDLE (which also comes with a text editor;

More information

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections

How To Think Like A Computer Scientist, chapter 3; chapter 6, sections 6.189 Day 3 Today there are no written exercises. Turn in your code tomorrow, stapled together, with your name and the file name in comments at the top as detailed in the Day 1 exercises. Readings How

More information

CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS First Name: Last Name: NetID:

CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS   First Name: Last Name: NetID: CS 1110, LAB 1: EXPRESSIONS AND ASSIGNMENTS http://www.cs.cornell.edu/courses/cs1110/2018sp/labs/lab01/lab01.pdf First Name: Last Name: NetID: Learning goals: (1) get hands-on experience using Python in

More information

Table of Contents EVALUATION COPY

Table of Contents EVALUATION COPY Table of Contents Introduction... 1-2 A Brief History of Python... 1-3 Python Versions... 1-4 Installing Python... 1-5 Environment Variables... 1-6 Executing Python from the Command Line... 1-7 IDLE...

More information

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

CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28)   First Name: Last Name: NetID: CS 1110 SPRING 2016: GETTING STARTED (Jan 27-28) http://www.cs.cornell.edu/courses/cs1110/2016sp/labs/lab01/lab01.pdf First Name: Last Name: NetID: Goals. Learning a computer language is a lot like learning

More information

Week - 01 Lecture - 04 Downloading and installing Python

Week - 01 Lecture - 04 Downloading and installing Python Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 04 Downloading and

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

CS 1110, LAB 3: MODULES AND TESTING   First Name: Last Name: NetID: CS 1110, LAB 3: MODULES AND TESTING http://www.cs.cornell.edu/courses/cs11102013fa/labs/lab03.pdf First Name: Last Name: NetID: The purpose of this lab is to help you better understand functions, and to

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

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

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types Introduction to Computer Programming in Python Dr William C Bulko Data Types 2017 What is a data type? A data type is the kind of value represented by a constant or stored by a variable So far, you have

More information

ERTH3021 Exploration and Mining Geophysics

ERTH3021 Exploration and Mining Geophysics ERTH3021 Exploration and Mining Geophysics Practical 1: Introduction to Scientific Programming using Python Purposes To introduce simple programming skills using the popular Python language. To provide

More information

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Programming for Engineers in Python. Autumn

Programming for Engineers in Python. Autumn Programming for Engineers in Python Autumn 2011-12 Plan Administration: Course site Homework submission guidelines Working environment Python: Variables Editor vs. shell Homework 0 Python Cont. Conditional

More information

Programming for Engineers in Python. Recitation 1

Programming for Engineers in Python. Recitation 1 Programming for Engineers in Python Recitation 1 Plan Administration: Course site Homework submission guidelines Working environment Python: Variables Editor vs. shell Homework 0 Python Cont. Conditional

More information

Choose the file menu, and select Open. Input to be typed at the Maple prompt. Output from Maple. An important tip.

Choose the file menu, and select Open. Input to be typed at the Maple prompt. Output from Maple. An important tip. MAPLE Maple is a powerful and widely used mathematical software system designed by the Computer Science Department of the University of Waterloo. It can be used for a variety of tasks, such as solving

More information

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing SECTION 1: INTRODUCTION ENGR 112 Introduction to Engineering Computing 2 Course Overview What is Programming? 3 Programming The implementation of algorithms in a particular computer programming language

More information

Lecture 3. Functions & Modules

Lecture 3. Functions & Modules Lecture 3 Functions & Modules Labs this Week Lab 1 is due at the beginning of your lab If it is not yet by then, you cannot get credit Only exception is for students who added late (Those students should

More information

Class #15: Experiment Introduction to Matlab

Class #15: Experiment Introduction to Matlab Class #15: Experiment Introduction to Matlab Purpose: The objective of this experiment is to begin to use Matlab in our analysis of signals, circuits, etc. Background: Before doing this experiment, students

More information

1 Introduction to Matlab

1 Introduction to Matlab 1 Introduction to Matlab 1. What is Matlab? Matlab is a computer program designed to do mathematics. You might think of it as a super-calculator. That is, once Matlab has been started, you can enter computations,

More information

The Very Basics of the R Interpreter

The Very Basics of the R Interpreter Chapter 2 The Very Basics of the R Interpreter OK, the computer is fired up. We have R installed. It is time to get started. 1. Start R by double-clicking on the R desktop icon. 2. Alternatively, open

More information

Statistical Data Analysis: Python Tutorial

Statistical Data Analysis: Python Tutorial 1 October 4, 2017 Statistical Data Analysis: Python Tutorial Dr A. J. Bevan, Contents 1 Getting started 1 2 Basic calculations 2 3 More advanced calculations 4 4 Data sets 5 4.1 CSV file input.............................................

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

Dr Richard Greenaway

Dr Richard Greenaway SCHOOL OF PHYSICS, ASTRONOMY & MATHEMATICS 4PAM1008 MATLAB 2 Basic MATLAB Operation Dr Richard Greenaway 2 Basic MATLAB Operation 2.1 Overview 2.1.1 The Command Line In this Workshop you will learn how

More information

Programming Fundamentals and Python

Programming Fundamentals and Python Chapter 2 Programming Fundamentals and Python This chapter provides a non-technical overview of Python and will cover the basic programming knowledge needed for the rest of the chapters in Part 1. It contains

More information

Variable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3.

Variable Definition and Statement Suppression You can create your own variables, and assign them values using = >> a = a = 3. MATLAB Introduction Accessing Matlab... Matlab Interface... The Basics... 2 Variable Definition and Statement Suppression... 2 Keyboard Shortcuts... More Common Functions... 4 Vectors and Matrices... 4

More information

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

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment Iteration 6.1. Multiple assignment As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop

More information

L A TEX Primer. Randall R. Holmes. August 17, 2018

L A TEX Primer. Randall R. Holmes. August 17, 2018 L A TEX Primer Randall R. Holmes August 17, 2018 Note: For this to make sense it needs to be read with the code and the compiled output side by side. And in order for the compiling to be successful, the

More information

9. Elementary Algebraic and Transcendental Scalar Functions

9. Elementary Algebraic and Transcendental Scalar Functions Scalar Functions Summary. Introduction 2. Constants 2a. Numeric Constants 2b. Character Constants 2c. Symbol Constants 2d. Nested Constants 3. Scalar Functions 4. Arithmetic Scalar Functions 5. Operators

More information

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications Hello World! Computer Programming for Kids and Other Beginners by Warren Sande and Carter Sande Chapter 1 Copyright 2009 Manning Publications brief contents Preface xiii Acknowledgments xix About this

More information

Lecture 3. Functions & Modules

Lecture 3. Functions & Modules Lecture 3 Functions & Modules Labs this Week Lab 1 is due at the beginning of your lab If it is not yet by then, you cannot get credit Only exception is for students who added late (Those students should

More information

Matlab Introduction. Scalar Variables and Arithmetic Operators

Matlab Introduction. Scalar Variables and Arithmetic Operators Matlab Introduction Matlab is both a powerful computational environment and a programming language that easily handles matrix and complex arithmetic. It is a large software package that has many advanced

More information

Scripting Languages. Python basics

Scripting Languages. Python basics Scripting Languages Python basics Interpreter Session: python Direct conversation with python (>>>) Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright",

More information

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52 Chapter 2 Python Programming for Physicists Soon-Hyung Yook March 31, 2017 Soon-Hyung Yook Chapter 2 March 31, 2017 1 / 52 Table of Contents I 1 Getting Started 2 Basic Programming Variables and Assignments

More information

: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics

: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics Assignment 1: Turtle Graphics Page 1 600.112: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics Peter H. Fröhlich phf@cs.jhu.edu Joanne Selinski joanne@cs.jhu.edu Due Date: Wednesdays

More information

VBScript: Math Functions

VBScript: Math Functions C h a p t e r 3 VBScript: Math Functions In this chapter, you will learn how to use the following VBScript functions to World Class standards: 1. Writing Math Equations in VBScripts 2. Beginning a New

More information

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1 Review Midterm Exam 1 Review Midterm Exam 1 Exam on Monday, October 7 Data Types and Variables = Data Types and Variables Basic Data Types Integers Floating Point Numbers Strings Data Types and Variables

More information

If Statements, For Loops, Functions

If Statements, For Loops, Functions Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements

More information

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore CS 115 Data Types and Arithmetic; Testing Taken from notes by Dr. Neil Moore Statements A statement is the smallest unit of code that can be executed on its own. So far we ve seen simple statements: Assignment:

More information

Interactive Mode Python Pylab

Interactive Mode Python Pylab Short Python Intro Gerald Schuller, Nov. 2016 Python can be very similar to Matlab, very easy to learn if you already know Matlab, it is Open Source (unlike Matlab), it is easy to install, and unlike Matlab

More information

Introduction to Python

Introduction to Python Introduction to Python CB2-101 Introduction to Scientific Computing November 11 th, 2014 Emidio Capriotti http://biofold.org/emidio Division of Informatics Department of Pathology Python Python high-level

More information

CS 112: Intro to Comp Prog

CS 112: Intro to Comp Prog CS 112: Intro to Comp Prog Importing modules Branching Loops Program Planning Arithmetic Program Lab Assignment #2 Upcoming Assignment #1 Solution CODE: # lab1.py # Student Name: John Noname # Assignment:

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

CMPS 12A Introduction to Programming Lab Assignment 7

CMPS 12A Introduction to Programming Lab Assignment 7 CMPS 12A Introduction to Programming Lab Assignment 7 In this assignment you will write a bash script that interacts with the user and does some simple calculations, emulating the functionality of programming

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

CSE 101 Introduction to Computers Development / Tutorial / Lab Environment Setup

CSE 101 Introduction to Computers Development / Tutorial / Lab Environment Setup CSE 101 Introduction to Computers Development / Tutorial / Lab Environment Setup Purpose: The purpose of this lab is to setup software that you will be using throughout the term for learning about Python

More information

Semester 2, 2018: Lab 1

Semester 2, 2018: Lab 1 Semester 2, 2018: Lab 1 S2 2018 Lab 1 This lab has two parts. Part A is intended to help you familiarise yourself with the computing environment found on the CSIT lab computers which you will be using

More information

Introduction to Python, Cplex and Gurobi

Introduction to Python, Cplex and Gurobi Introduction to Python, Cplex and Gurobi Introduction Python is a widely used, high level programming language designed by Guido van Rossum and released on 1991. Two stable releases: Python 2.7 Python

More information

>>> * *(25**0.16) *10*(25**0.16)

>>> * *(25**0.16) *10*(25**0.16) #An Interactive Session in the Python Shell. #When you type a statement in the Python Shell, #the statement is executed immediately. If the #the statement is an expression, its value is #displayed. #Lines

More information

JavaScript Basics. The Big Picture

JavaScript Basics. The Big Picture JavaScript Basics At this point, you should have reached a certain comfort level with typing and running JavaScript code assuming, of course, that someone has already written it for you This handout aims

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

Lab copy. Do not remove! Mathematics 152 Spring 1999 Notes on the course calculator. 1. The calculator VC. The web page

Lab copy. Do not remove! Mathematics 152 Spring 1999 Notes on the course calculator. 1. The calculator VC. The web page Mathematics 152 Spring 1999 Notes on the course calculator 1. The calculator VC The web page http://gamba.math.ubc.ca/coursedoc/math152/docs/ca.html contains a generic version of the calculator VC and

More information

Python for Scientists

Python for Scientists High level programming language with an emphasis on easy to read and easy to write code Includes an extensive standard library We use version 3 History: Exists since 1991 Python 3: December 2008 General

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

Copied from: https://www.cs.hmc.edu/twiki/bin/view/cs5/lab1b on 3/20/2017

Copied from: https://www.cs.hmc.edu/twiki/bin/view/cs5/lab1b on 3/20/2017 Hw 1, Part 2 (Lab): Functioning smoothly! Using built-in functions Copied from: https://www.cs.hmc.edu/twiki/bin/view/cs5/lab1b on 3/20/2017 First, try out some of Python's many built-in functions. These

More information

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts Simple Data Types There are a number of data types that are considered primitive in that they contain only a single value. These data

More information

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration STATS 507 Data Analysis in Python Lecture 2: Functions, Conditionals, Recursion and Iteration Functions in Python We ve already seen examples of functions: e.g., type()and print() Function calls take the

More information

Comp 151. More on Arithmetic and intro to Objects

Comp 151. More on Arithmetic and intro to Objects Comp 151 More on Arithmetic and intro to Objects Admin Any questions 2 The Project Lets talk about the project. What do you need A 'accumulator' variable. Start outside of the loop Lets look at your book's

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

CS 115 Lecture 4. More Python; testing software. Neil Moore

CS 115 Lecture 4. More Python; testing software. Neil Moore CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement

More information

Python Programming, bridging course 2011

Python Programming, bridging course 2011 Python Programming, bridging course 2011 About the course Few lectures Focus on programming practice Slides on the homepage No course book. Using online resources instead. Online Python resources http://www.python.org/

More information

S206E Lecture 19, 5/24/2016, Python an overview

S206E Lecture 19, 5/24/2016, Python an overview S206E057 Spring 2016 Copyright 2016, Chiu-Shui Chan. All Rights Reserved. Global and local variables: differences between the two Global variable is usually declared at the start of the program, their

More information

Part II Composition of Functions

Part II Composition of Functions Part II Composition of Functions The big idea in this part of the book is deceptively simple. It s that we can take the value returned by one function and use it as an argument to another function. By

More information

MAT 275 Laboratory 1 Introduction to MATLAB

MAT 275 Laboratory 1 Introduction to MATLAB MATLAB sessions: Laboratory 1 1 MAT 275 Laboratory 1 Introduction to MATLAB MATLAB is a computer software commonly used in both education and industry to solve a wide range of problems. This Laboratory

More information

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners Getting Started Excerpted from Hello World! Computer Programming for Kids and Other Beginners EARLY ACCESS EDITION Warren D. Sande and Carter Sande MEAP Release: May 2008 Softbound print: November 2008

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

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han Lab 1: Course Intro, Getting Started with Python IDLE Ling 1330/2330 Computational Linguistics Na-Rae Han Objectives Course Introduction http://www.pitt.edu/~naraehan/ling1330/index.html Student survey

More information

An Introduction to Maple This lab is adapted from a lab created by Bob Milnikel.

An Introduction to Maple This lab is adapted from a lab created by Bob Milnikel. Some quick tips for getting started with Maple: An Introduction to Maple This lab is adapted from a lab created by Bob Milnikel. [Even before we start, take note of the distinction between Tet mode and

More information

AP Calculus AB Summer Review Packet

AP Calculus AB Summer Review Packet AP Calculus AB Summer Review Packet Mr. Burrows Mrs. Deatherage 1. This packet is to be handed in to your Calculus teacher on the first day of the school year. 2. All work must be shown on separate paper

More information

Sets. Sets. Examples. 5 2 {2, 3, 5} 2, 3 2 {2, 3, 5} 1 /2 {2, 3, 5}

Sets. Sets. Examples. 5 2 {2, 3, 5} 2, 3 2 {2, 3, 5} 1 /2 {2, 3, 5} Sets We won t spend much time on the material from this and the next two chapters, Functions and Inverse Functions. That s because these three chapters are mostly a review of some of the math that s a

More information

CS403: Programming Languages. Assignment 1. Version 2a

CS403: Programming Languages. Assignment 1. Version 2a CS403: Programming Languages Assignment 1 Version a Preliminary information This is your first Scam assignment. To run your code, use the following command: or scam FILENAME scam -r FILENAME where FILENAME

More information

Math Day 2 Programming: How to make computers do math for you

Math Day 2 Programming: How to make computers do math for you Math Day 2 Programming: How to make computers do math for you Matt Coles February 10, 2015 1 Intro to Python (15min) Python is an example of a programming language. There are many programming languages.

More information

Introduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn

Introduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn Introduction to Machine Learning Useful tools: Python, NumPy, scikit-learn Antonio Sutera and Jean-Michel Begon September 29, 2016 2 / 37 How to install Python? Download and use the Anaconda python distribution

More information

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB:

Variables are used to store data (numbers, letters, etc) in MATLAB. There are a few rules that must be followed when creating variables in MATLAB: Contents VARIABLES... 1 Storing Numerical Data... 2 Limits on Numerical Data... 6 Storing Character Strings... 8 Logical Variables... 9 MATLAB S BUILT-IN VARIABLES AND FUNCTIONS... 9 GETTING HELP IN MATLAB...

More information

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS 1439-1440 1 Outline 1. Introduction 2. Why Python? 3. Compiler and Interpreter 4. The first program 5. Comments and Docstrings 6. Python Indentations

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG 1 Notice Reading Assignment Chapter 1: Introduction to Java Programming Homework 1 It is due this coming Sunday

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

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

Computer and Programming: Lab 1

Computer and Programming: Lab 1 01204111 Computer and Programming: Lab 1 Name ID Section Goals To get familiar with Wing IDE and learn common mistakes with programming in Python To practice using Python interactively through Python Shell

More information

Lab 1 Intro to MATLAB and FreeMat

Lab 1 Intro to MATLAB and FreeMat Lab 1 Intro to MATLAB and FreeMat Objectives concepts 1. Variables, vectors, and arrays 2. Plotting data 3. Script files skills 1. Use MATLAB to solve homework problems 2. Plot lab data and mathematical

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

Programming with Python

Programming with Python Programming with Python EOAS Software Carpentry Workshop September 21st, 2016 https://xkcd.com/353 Getting started For our Python introduction we re going to pretend to be a researcher studying inflammation

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

Introduction to Python Programming

Introduction to Python Programming advances IN SYSTEMS AND SYNTHETIC BIOLOGY 2018 Anna Matuszyńska Oliver Ebenhöh oliver.ebenhoeh@hhu.de Ovidiu Popa ovidiu.popa@hhu.de Our goal Learning outcomes You are familiar with simple mathematical

More information

Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python

Lecture 3: Functions & Modules (Sections ) CS 1110 Introduction to Computing Using Python http://www.cs.cornell.edu/courses/cs1110/2019sp Lecture 3: Functions & Modules (Sections 3.1-3.3) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner,

More information

STAT 113: R/RStudio Intro

STAT 113: R/RStudio Intro STAT 113: R/RStudio Intro Colin Reimer Dawson Last Revised September 1, 2017 1 Starting R/RStudio There are two ways you can run the software we will be using for labs, R and RStudio. Option 1 is to log

More information

(DRAFT) PYTHON FUNDAMENTALS II: NUMPY & MATPLOTLIB

(DRAFT) PYTHON FUNDAMENTALS II: NUMPY & MATPLOTLIB (DRAFT) PYTHON FUNDAMENTALS II: NUMPY & MATPLOTLIB TROY P. KLING Contents 1. Importing Libraries 1 2. Introduction to numpy 2 3. Introduction to matplotlib 5 4. Image Processing 8 5. The Mandelbrot Set

More information

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 2: Data, Classes, and Modules January 22, 2007 http://www.seas.upenn.edu/~cse39904/ Administrative things Teaching assistant Brian Summa (bsumma @ seas.upenn.edu)

More information

python 01 September 16, 2016

python 01 September 16, 2016 python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7

More information

Python for Astronomers. Week 1- Basic Python

Python for Astronomers. Week 1- Basic Python Python for Astronomers Week 1- Basic Python UNIX UNIX is the operating system of Linux (and in fact Mac). It comprises primarily of a certain type of file-system which you can interact with via the terminal

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

Applied Calculus. Lab 1: An Introduction to R

Applied Calculus. Lab 1: An Introduction to R 1 Math 131/135/194, Fall 2004 Applied Calculus Profs. Kaplan & Flath Macalester College Lab 1: An Introduction to R Goal of this lab To begin to see how to use R. What is R? R is a computer package for

More information

Limits. f(x) and lim. g(x) g(x)

Limits. f(x) and lim. g(x) g(x) Limits Limit Laws Suppose c is constant, n is a positive integer, and f() and g() both eist. Then,. [f() + g()] = f() + g() 2. [f() g()] = f() g() [ ] 3. [c f()] = c f() [ ] [ ] 4. [f() g()] = f() g()

More information

15-122: Principles of Imperative Computation, Fall 2015

15-122: Principles of Imperative Computation, Fall 2015 15-122 Programming 5 Page 1 of 10 15-122: Principles of Imperative Computation, Fall 2015 Homework 5 Programming: Clac Due: Thursday, October 15, 2015 by 22:00 In this assignment, you will implement a

More information

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment

PIC 10A. Lecture 3: More About Variables, Arithmetic, Casting, Assignment PIC 10A Lecture 3: More About Variables, Arithmetic, Casting, Assignment Assigning values to variables Our variables last time did not seem very variable. They always had the same value! Variables stores

More information

Not-So-Mini-Lecture 6. Modules & Scripts

Not-So-Mini-Lecture 6. Modules & Scripts Not-So-Mini-Lecture 6 Modules & Scripts Interactive Shell vs. Modules Launch in command line Type each line separately Python executes as you type Write in a code editor We use Atom Editor But anything

More information

CS1 Lecture 3 Jan. 22, 2018

CS1 Lecture 3 Jan. 22, 2018 CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow

More information

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window. EE 350L: Signals and Transforms Lab Spring 2007 Lab #1 - Introduction to MATLAB Lab Handout Matlab Software: Matlab will be the analytical tool used in the signals lab. The laboratory has network licenses

More information

The Python interpreter

The Python interpreter The Python interpreter Daniel Winklehner, Remi Lehe US Particle Accelerator School (USPAS) Summer Session Self-Consistent Simulations of Beam and Plasma Systems S. M. Lund, J.-L. Vay, D. Bruhwiler, R.

More information