19/11/2013 Intro. To Python Session 2 • Simple data types • Wri<ng programs • Selec<on (if statements) Copyright © 2013 Newcastle University 1 Simple data types Strings (str in python) • A string of 1 or more characters – 'single' or "double" quoted – Can use one type of quote to include the other in a string • "Nick's laptop" • 'Say "goodbye"' • Use the + operator to add strings together • Use \n to include a new line in a string • Use str() to cast (or convert) another type to a string Copyright © 2013 Newcastle University 2 Numbers • Integers (whole numbers) – Use int() to cast (or convert) to an integer – Using int() on a floa<ng point number gives the whole part part of the number • Floats – Floa<ng point number or decimal – Division / of two numbers results in a float – Use // for integer division (% gives the remainder) – Use float()to cast to a floa<ng point number • Long – For large integers Copyright © 2013 Newcastle University 3 1 19/11/2013 Boolean • True or False (note capitals) • Use booleans in logical tests – To make decisions e.g.: • A person must be over 21 and have a full licence to hire a car • What two true/false ques<ons can we ask? • Like 20 ques<ons (with yes/no, true/false answers) – Boolean expressions are either true or false • Use bool() to cast to a boolean – bool(1) is true and bool(anythingButZero) is true – bool(0) is false, bool(0.0) is false Copyright © 2013 Newcastle University 4 Comments • Use comments to document your code • Comments are not executed – they are ignored when a program is executed • Use # for inline or single line comments # this is a comment print('No comment') # print statement • Use triple quotes for mul<-­‐line comments """ This is a comment And so is this """ Copyright © 2013 Newcastle University 5 Two useful library func<ons • Use time.sleep() to pause a program import time time.sleep(10) # pause for 10 seconds • Use random.randint() to generate a random number import random # generate random int between 0 and 100 i = random.randint(0, 100) Copyright © 2013 Newcastle University 6 2