Introduction to Programming
Python Lab 2: Variables
8 October 2019 or 24 January 2020
1
PythonLab2 lecture slides.ppt Ping Brennan (p.brennan@bbk.ac.uk)
Introduction to Programming Python Lab 2: Variables PythonLab2 - - PowerPoint PPT Presentation
Introduction to Programming Python Lab 2: Variables PythonLab2 lecture slides.ppt 1 8 October 2019 or Ping Brennan (p.brennan@bbk.ac.uk) 24 January 2020 Getting Started Create a new folder in your disk space with the name PythonLab2
8 October 2019 or 24 January 2020
1
PythonLab2 lecture slides.ppt Ping Brennan (p.brennan@bbk.ac.uk)
2
3
4
## # This program computes the volume (in litres) of a six-pack of soda # cans and the total volume of a six-pack and a two-litre bottle. # # Litres in a 12-ounce can and a two-litre bottle. CAN_VOLUME = 0.355 BOTTLE_VOLUME = 2.0 # Number of cans per pack. cansPerPack = 6 # Calculate total volume in the cans. totalVolume = cansPerPack * CAN_VOLUME print("A six-pack of 12-ounce cans contains", totalVolume, "litres.") # Calculate total volume in the cans and a 2-litre bottle. totalVolume = totalVolume + BOTTLE_VOLUME print("A six-pack and a two-litre bottle contain", totalVolume, "litres.") 5
6
cansPerPack = 6
7
1. Declare and initialize two new variables, unitPrice and quantity : unitPrice - contains the price of a single 2-litre bottle in dollars quantity
Use reasonable initial values for the two variables, for example, quantity = 2 2. Calculate and print the total purchase price for the bottles. Use the formula below as the argument for the function print() : unitPrice * quantity
8
mystery = 1 # line 1 mystery = 1 - 2 * mystery # line 2 mystery = mystery + 1 # line 3
1. Print the initial value of the variable mystery after line 1 in the above code. 2. Print the final value of the variable mystery after line 3 in the above code.
9
# Initialize x x=1.0 print("x*x:", x*x) # First iteration delta = (1/x)-x/2 x = x+delta print("x*x:" , x*x) # Second iteration delta = (1/x)-x/2 x = x+delta print("x*x:", x*x)
10
1. Add a third iteration to determine the new delta and x values, and then print the square of x (i.e. x*x) 2. Add a fourth iteration to determine the new delta and x values, and then print the square of x (i.e. x*x)
11
12
13