10
Week 4

Week 4. >>> Overview * if else * returns * input

Embed Size (px)

Citation preview

Page 1: Week 4. >>> Overview * if else * returns * input

Week 4

Page 2: Week 4. >>> Overview * if else * returns * input

>>> Overview

* if else* returns* input

Page 3: Week 4. >>> Overview * if else * returns * input

>>> if

Like many things in the transition from Java to Python, curly braces are replaced with colons and whitespace, the parentheses are dropped and &&, || and ! change.

// 1 for english// 2 for germanint translator = 1;if (translator == 1) {

english();} else if (translator == 2) {

german();} else {

System.out.println("None");}

Translator.java12345678910

translator = 1if translator == 1:

english()elif translator == 2:

german()else:

print "None"

translator.py

12345

<><=>===!=orandnot

<><=>===!=||&&!

Java python

Notice: "else if" becomes "elif"

Page 4: Week 4. >>> Overview * if else * returns * input

s = "wow" s = "wow" s = "wow" s = "wow" s = "wOw" s = "wOw" s = "hmmm" s = " ack " s = "wOw" s = "wow"

string methods

>>> stringsJust like in Java, strings are objects. Lets look at different things that we can do with them:

s.capitalize() => "Wow"s.endswith("w") => Trues.find("o") => 1s.islower() => Trues.isupper() => Falses.lower() => "wow"s.startswith("hm") => Trues.strip() => "ack"s.swapcase() => "WoW"s.upper() => "WOW"

Page 5: Week 4. >>> Overview * if else * returns * input

>>> strings as sequencesLike arrays in Java, strings have zero-based indexes, and we can access parts of them with square brackets instead of using Java's substring() and charAt() methods.

Lets look at things we can do if we have the string

s = "shocking"

s[<index>] s[3] => "c" s[-1] => "g"s[<start>:<end>] s[4:] => "king" s[3:5] => "ck" s[-3:] => "ing"len(s) len(s) => 8

sequence operations

"shocking"-8 -7 -6 -5 -4 -3 -2 -1

0 1 2 3 4 5 6 7from the front

from the back

Indexing

example: s[2:-4] => "oc"

Page 6: Week 4. >>> Overview * if else * returns * input

>>> returnReturns in python are straightforward. Simply "return <value>" instead of "return <value>;" and forget about the types.

def f_to_c(degreesF):degreesC = 5.0 / 9.0 * (degreesF – 32)return degreesC

#maintemp = f_to_c(68)print ("Temperature is: " + str(temp))

degrees.py

1234567

def slope(x1, y1, x2, y2):return (y2 - y1) / (x2 - x1)

#mainslope = slope(0, 0, 5, 5)print ("Slope is: " + str(slope))

slope.py

1234567

Page 7: Week 4. >>> Overview * if else * returns * input

>>> math in pythonMost of the math functions are the same in python. Here is a list with a short description.

In order to use them, we have to import math

The constants are the same as Java, except lower case.

math.pi = 3.1415926...math.e = 2.7182818..

Random comes from its own class:import randomrandom.random()

math functions

ceil(x)fabs(x)floor(x)exp(x)log(x,[base])log10(x)pow(x, y)sqrt(x)cos(x)hypot(x, y)sin(x)tan(x)degrees(x)radians(x)

Page 8: Week 4. >>> Overview * if else * returns * input

>>> input() vs. raw_input()

There are two ways of getting input. The first is input(). It takes in input until enter is hit and then tries to interpret it into python. However, this way only works well for numbers.

The second way is to use raw_input() which returns the entire line as a string. Once this is done, the string can be split into smaller strings and changed to the desired type.

>>> x = input("yes? ")yes? yTraceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module>NameError: name 'y' is not defined>>> x = input("yes? ")yes? 2>>> print x2>>> x = input("num? ")num? 2.0>>> print x2.0

#take a number inx = input("x? ")print x

#take a sentence to tokenize itsent = raw_input("sentence: ")for w in sent.split(" "):

print "word: " + w

inputs.py

12345678910

Page 9: Week 4. >>> Overview * if else * returns * input

>>> hours worked// Marty Stepp, CSE 142, Autumn 2007// This program reads the hours worked by two employees and// outputs the total hours for each and for both employees.

import java.util.*; // so that I can use Scanner

public class Hours { public static void main(String[] args) { Scanner console = new Scanner(System.in); int totalHours = 0; totalHours = totalHours + processEmployee(console, 1); totalHours = totalHours + processEmployee(console, 2); System.out.println("Total hours for both = " + totalHours); } // This method reads the hours worked by one employee // and returns the total hours. public static int processEmployee(Scanner console, int num) { System.out.print("Employee " + num + ": How many days? "); int days = console.nextInt(); // cumulative sum for hours worked each day int sum = 0; for (int i = 1; i <= days; i++) { System.out.print("Hours? "); int hours = console.nextInt(); sum += Math.min(8, hours); // cap to 8 hours in one day } System.out.println("Employee " + num + "'s total hours = " + sum); return sum; }}

Employee 1: How many days? 3Hours? 1Hours? 2Hours? 9Employee 1's total hours = 11Employee 2: How many days? 2Hours? 8Hours? 10Employee 2's total hours = 16Total hours for both = 27

Sample output:

Page 10: Week 4. >>> Overview * if else * returns * input

Except where otherwise noted, this work is licensed under http://creativecommons.org/licenses/by-nc-sa/3.0

© 2007 Scott Shawcroft, Some Rights Reserved

Python® and the Python logo are either a registered trademark or trademark of the Python Software Foundation. Java™ is a trademark or registered trademark of Sun Microsystems, Inc.

in the United States and other countries.