In [1]:
a = 1 # Integer
a
Out[1]:
In [2]:
b = 2.0 # Float
b
Out[2]:
In [3]:
c = "A string" # String, single, double, and treble-double quotations marks are
# all accepted.
c
Out[3]:
In [4]:
d = 1+2j # Complex number
d
Out[4]:
In [5]:
e = True # Boolean
e
Out[5]:
In [6]:
a = 0.25
a.as_integer_ratio() # Calling a member function/method of object 'a'
Out[6]:
a
, and its value, 1
, you are asking for an "integer's worth" of memory and putting an integer representation of 1
at that memory location. Using the variable a
then queries the memory location to get the value stored at a
.int
and a specific value to be created, then to be given the label a
. Using the variable a
then tells the interpreter to return the object that a
points at.=
works.
In [7]:
a = 1
b = 2
print("id(a) =", id(a))
print("id(b) =", id(b))
b = a
print()
print("id(a) =", id(a))
print("id(b) =", id(b))
a
and b
. After asking for b = a
we can see that b
actually refers to the same object in memory as a
. Rather than having the value of a
copied into the memory of b
, as it would in C. In essence we have labelled the integer 1
with both variables a
and b
.id()
value. Because of this we can't get into trouble by forgetting this difference here. But the mutable types discussed later can get you into trouble if you don't remember what your variables are labelling.
In [8]:
a = b = c = 1 # Can assign multiple variables to the same object on one line
print(id(a))
print(id(b))
print(id(c))
In [9]:
a = 5.0
b = 2.0
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print()
print(a % b) # Modulus, divides left by right and returns remainder
print(a ** b) # Exponent, raises left value to the power of the right
print(a // b) # Floor division, divides left by right and removes any
# value after the decimal point
+
operator
In [10]:
a = "str"
b = "ing"
print(a + b)
=
operator in the following way (Note that in Python 3, division of two integers gives a float).
In [11]:
a = 1
a += 1 # Equivalent to a = a + 1
print(a)
b = 5
a /= b # Equivalent to a = a / b
print(a)
In [12]:
a = 1
b = 2
print(a == b)
print(a != b)
print(a < b) # Also <=
print(a > b) # Also >=
is
and not
keywords.
In [13]:
a = "abc"
b = "a"
b = b+"bc" # In notebooks/IPython we have to do this to force a and b to have
# different ids. Not necessary in normal Python scripts.
print(a==b)
print(a is b)
b = a
print(a is b)
print(a is not b)
In [14]:
# Define some numbers as strings
a = "3.0"
b = "-6.0"
print(a + b) # '+' operator simply concatenates strings
print(float(a) + float(b)) # Cast as floats before '+' evaluated
In [15]:
c = -4.0
str(c)+" is a string" # Can cast to strings
Out[15]:
In [16]:
int(float(a)) # Can chain together casting
Out[16]:
In [17]:
complex(1,2)
Out[17]: