Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

LAB

Objectives

  • becoming familiar with the concept of storing and working with different data types in Python
  • experimenting with Python code.

Scenario

Here is a short story:

Once upon a time in Appleland, John had three apples, Mary had five apples, and Adam had six apples. They were all very happy and lived for a long time. End of story.

Your task is to: 

  • create the variables: john, mary, and adam
  • assign values to the variables. The values must be equal to the numbers of fruit possessed by John, Mary, and Adam respectively
  • having stored the numbers in the variables, print the variables on one line, and separate each of them with a comma
  • now create a new variable named total_apples equal to addition of the three former variables
  • print the value stored in total_apples to the console
  • experiment with your code: create new variables, assign different values to them, and perform various arithmetic operations on them (e.g., +, /, // , etc. ). Try to print a string and an integer together on one line, e.g., "Total number of apples:" and total_apples.

Shortcut operators

It's time for the next set of operators that make a developer's life easier.

Very often, we want to use one and the same variable both to the right and the left sides of the = operator.

For example, if we need to calculate a series of successive values of powers of 2, we may use a piece like this:

x = x * 2

You may use an expression like this if you can't fall asleep and you're trying to deal with it using some good, old-fashioned methods:

sheep = sheep + 1

Python offers you a shortened way of writing operations like these, which can be coded as follows: 

x *= 2

sheep += 1

Let's try to present a general description for these operations. 

If op is a two-argument operator (this is a very important condition) and the operator is used in the following context:

variable = variable op expression

it can be simplified and shown as follows:

variable op= expression

Take a look at the examples below. Make sure you understand them all. 

i = i + 2 * j ⇒ i += 2 * j

var = var / 2 ⇒ var /= 2

rem = rem % 10 ⇒ rem %= 10

j = j - (i + var + rem) ⇒ j -= (i + var + rem)

x = x ** 2 ⇒ x **= 2

LAB

David Khieu
Module by David Khieu, updated more than 1 year ago

Description

LAB
No tags specified