CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.

Slides:



Advertisements
Similar presentations
Fundamentals of Python: From First Programs Through Data Structures Chapter 2 Software Development, Data Types, and Expressions.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
Python Programming: An Introduction to Computer Science
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
Data types and variables
Introduction to C Programming
Chapter 3 Computing with Numbers
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers.
Python Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 2/e1.
Objectives You should be able to describe: Data Types
Vahé Karamian Python Programming CS-110 CHAPTER 3 Computing with Numbers.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
CS190/295 Programming in Python for Life Sciences: Lecture 2 Instructor: Xiaohui Xie University of California, Irvine.
1 IPC144 Session 11 The C Programming Language. 2 Objectives To format a #define statement correctly To use a #define statement in a C program To construct.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Introduction to Python
 Pearson Education, Inc. All rights reserved Formatted Output.
Fundamentals of Python: First Programs
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Input, Output, and Processing
Chapter 2: Using Data.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
CS190/295 Programming in Python for Life Sciences: Lecture 4 Instructor: Xiaohui Xie University of California, Irvine.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Chapter 3 – Variables and Arithmetic Operations. Variable Rules u Must declare all variable names –List name and type u Keep length to 31 characters –Older.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 9, 2005 Lecture Number: 6.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
1 09/27/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
1 Types of Programming Language (1) Three types of programming languages 1.Machine languages Strings of numbers giving machine specific instructions Example:
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
ENGINEERING 1D04 Tutorial 2. What we’re doing today More on Strings String input Strings as lists String indexing Slice Concatenation and Repetition len()
String and Lists Dr. José M. Reyes Álamo.
C Formatted Input/Output
Topics Designing a Program Input, Processing, and Output
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Topics Introduction to File Input and Output
INPUT & OUTPUT scanf & printf.
CS190/295 Programming in Python for Life Sciences: Lecture 4
CS190/295 Programming in Python for Life Sciences: Lecture 2
Topics Designing a Program Input, Processing, and Output
CS190/295 Programming in Python for Life Sciences: Lecture 3
Topics Designing a Program Input, Processing, and Output
15-110: Principles of Computing
Topics Introduction to File Input and Output
Topics Designing a Program Input, Processing, and Output
Primitive Types and Expressions
月夜憶舍弟 戍鼓斷人行,邊秋一雁聲。 露從今夜白,月是故鄉明。 有弟皆分散,無家問死生。 寄書長不達,況乃未休兵。 杜甫
Topics Introduction to File Input and Output
Introduction to C Programming
Presentation transcript:

CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine

Announcements The enrollment max cap for CS295 has been increased to 45. Homework assignment #2 will be posted online by 5pm Friday, which will be due Jan 16 (Thur) before class.

Computing with Numbers

Numeric Data Types Example output:

Numeric Data Types Whole numbers are represented using the integer data type (int for short).Values of type int can be positive or negative whole numbers. Numbers that can have fractional parts are represented as floating point (or float) values. The data type of an object determines what values it can have and what operations can be performed on it. The float type only stores approximations. There is a limit to the precision, or accuracy, of the stored values. By contrast, the int type is exact.

Numeric Data Types Notice how operations on floats produce floats, and operations on ints produce ints.

Using the Math Library Python provides many other useful mathematical functions in a special math library. A library is just a module that contains some useful definitions. Example: find the roots of ax 2 +bx+c =0

Using the Math Library Python provides many other useful mathematical functions in a special math library. A library is just a module that contains some useful definitions.

Accumulating Results: Factorial In mathematics, factorial is often denoted with an exclamation (“!”). The factorial of a whole number is defined as n!=n(n-1)(n-2)…(1). This happens to be the number of distinct arrangements for n items. Given six items, we compute 6! =720 possible arrangements. Write a program that will compute the factorial of a number entered by the user. The basic outline of our program follows an Input-Process-Output pattern. Basic strategy: do repeated multiplications, use an accumulator variable + a loop structure Input number to take factorial of, n Compute factorial of n, fact Output fact Initialize the accumulator variable Loop until final result is reached update the value of accumulator variable

Accumulating Results: Factorial Initialize the accumulator variable Loop until final result is reached update the value of accumulator variable For example, suppose we want to calculate 5!=5*4*3*2*1 We define a variable and initialize it to be 1 fact = 1 for factor in [2,3,4,5] fact = fact * factor

Python range() function range(n) : produce a sequence of numbers starting with 0 and continuing up to, but not including n range(start, n) : produce a sequence of numbers starting with start and continuing up to, but not including n range(start, n, step) : produce a sequence of numbers starting with start and continuing up to, but not including n, and using step as the increment between numbers Examples: >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5,10) [5, 6, 7, 8, 9] >>> range(5,10,3) [5, 8]

Accumulating Results: Factorial n!=n(n-1)(n-2)…(1). Write a program that will compute the factorial of a number entered by the user.

The limits of int ( Note that in python 2.7 or later can handle this error by automatically changing the data type.)

Handling Large Numbers: Long Ints Python provides a better solution for large, exact values in the form of a third numeric type long int. A long int is not a fixed size, but expands to accommodate whatever value it holds. To get a long int, you put an “L” suffix on a numeric literal.

Accumulating Results: Factorial n!=n(n-1)(n-2)…(1). Write a program that will compute the factorial of a number entered by the user.

Type Conversions Note that the value is truncated, not rounded when using int() or long()

Computing with Strings

The String Data Type A string is a sequence of characters

The String Data Type A string is a sequence of characters Remember that the input statement treats whatever the user types as an expression to be evaluated

Indexing of the String A string is a sequence of characters Individual characters can be accessed through the operation of indexing. The general form for indexing is [ ].

Slicing of the String A string is a sequence of characters Access a contiguous sequence of characters or substring from a string is called slicing. The general form for slicing is [ : ]. Both start and end should be int-valued expressions. A slice produces the substring starting at the position given by start and running up to, but not including, position end.

The string data type is immutable

Operations for putting strings together + concatenation * repetition

Summary of basic string operations

Example: single string processing

String Representation How does a computer represent strings? Each character is translated into a number, and the entire string is stored as a sequence of (binary) numbers in computer memory. It doesn’t really matter what number is used to represent any given character as long as the computer is consistent about the encoding/decoding process. One important standard, called ASCII, uses the numbers 0 through 127 to represent the characters typically found on a computer keyboard. For example, the capital letters A–Z are represented by the values 65–90, and the lowercase versions have codes 97–122. UniCode is an extended standard to include characters of other written languages

The String Library split - This function is used to split a string into a sequence of substrings. By default, it will split the string wherever a space occurs

The String Library

The eval() function eval - This function takes any string and evaluates it as if it were a Python expression.

Converting Numbers to Strings

String Formatting Notice that the final value is given as a fraction with only one decimal place. How to output something like $1.50 ? You can do this by using the string formatting operator:

String Formatting The string formatting operator is used like this: % ( ) % signs inside the template-string mark “slots” into which the values are inserted. There must be exactly one slot for each value. Each of the slots is described by a format specifier that tells Python how the value for that slot should appear. A formatting specifier has this general form: %.  type-char: decimal, float, or string  width: how many spaces are used to display the value? If a value requires more room than is given in width, Python will just expand the width so that the value fits.  precision: used with floating point values to indicate the desired number of digits after the decimal.

String Formatting

Multi-Line Strings Special characters: ’\n’ - newline (as if you are typing key on your keyboard ’\t’ -

File Processing Three Key steps of file-processing in all programming languages: 1.Associate a file on disk with a variable in a program. This process is called opening a file. Once a file has been opened, it is manipulated through the variable we assign to it. 2.Define a set of operations that can manipulate the file variable. At the very least, this includes operations that allow us to read the information from a file and write new information to a file. 3.When we are finished with a file, it is closed. Closing a file makes sure that any bookkeeping that was necessary to maintain the correspondence between the file on disk and the file variable is finished up. (For example, if you write information to a file variable, the changes might not show up on the disk version until the file has been closed.)

File Processing: open a file Associate a file on disk with a variable in a program. This process is called opening a file. = open(, ) mode: “r” for read, “w” for write Example: infile = open(“numbers.data”,”r”) Now we can use the variable inflie to read the contents of numbers.data from the disk.

File Processing: read Once a file is open, Python provides three related operations for reading information from a file:.read() –Returns the entire contents of the file as a single string. If the file contains more than one line of text, the resulting string has embedded newline characters between the lines.readline() –read one line from a file (read all the characters up through the next newline character); the string returned by readline will always end with a newline character.readlines() o returns a sequence of strings representing the lines of the file

File Processing: read

File Processing: write Open a file for output: Outfile = open(“mydata.out”, “w”) A word of warning: if a file with the given name does exist, Python will delete it and create a new, empty file. Put data into a file using the write operation:.write( )

Coming Attraction: Objects Notice the operations of the file processing are in the format of: –infile.read() –infile.close() which are different from the normal function applications such as abs(x) In Python, a file is an example of an object. Objects combine both data and operations together. An object’s operations, called methods, are invoked using the dot notation. Notice that strings are also objects in Python. You can invoke methods of strings: myString.split() Is equivalent to string.split(myString)