Boston Python Workshop 3/Data types: Difference between revisions

From OpenHatch wiki
Content added Content deleted
imported>Jesstess
imported>Jesstess
No edit summary
Line 1: Line 1:
==Numbers: integers and floats==
==Numbers: integers and floats==


====Math: addition, subtraction, multiplication, division====
====Addition====


<b>addition</b>: 2 + 2<br />
<pre>
<b>subtraction</b>: 0 - 2<br />
>>> 2 + 2
<b>multiplication</b>: 2 * 3<br />
4
<b>division:</b><br />
</pre>

====Subtraction====

<pre>
>>> 0 - 2
-2
</pre>

====Multiplication====

<pre>
>>> 2 * 3
6
</pre>

====Division====


<pre>
<pre>
Line 38: Line 22:
>>> float(1) / 2
>>> float(1) / 2
0.5
0.5
</pre>

====Remainder====

<pre>
>>> 4 % 2
0
>>> 4 % 3
1
</pre>
</pre>


Line 88: Line 63:
>>> type("Hello")
>>> type("Hello")
<type 'str'>
<type 'str'>
</pre>

==Booleans==

<pre>
>>> True
True
>>> False
False
</pre>

==Containment==

>>> "H" in "Hello"
True
>>> "X" in "Hello"
>>> "a" in ["a", "b", "c"]
True
>>> "x" in ["a", "b", "c"]
False

<pre>
"a" not in "abcde"
</pre>

<pre>
"Perl" not in "Boston Python Workshop"
</pre>

==Equality==

>>> 0 == 0
True
>>> 0 == 1
False

<pre>
"a" != "a"
</pre>

<pre>
"a" != "A"
</pre>

<code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> have the same meaning as in math class:

<pre>
1 > 0
</pre>

<pre>
2 >= 3
</pre>

<pre>
-1 < 0
</pre>

<pre>
.5 <= 1
</pre>
</pre>

Revision as of 15:33, 12 June 2011

Numbers: integers and floats

Math: addition, subtraction, multiplication, division

addition: 2 + 2
subtraction: 0 - 2
multiplication: 2 * 3
division:

>>> 4 / 2
2
>>> 1 / 2
0

Integer divison produces an integer. You need a number that knows about the decimal point to get a decimal out of division:

>>> 1.0 / 2
0.5
>>> float(1) / 2
0.5

Types

>>> type(1)
<type 'int'>
>>> type(1.0)
<type 'float'>

Strings

>>> "Hello"
'Hello'

String concatenation

>>> print "Hello" + "World"
HelloWorld

Printing strings

>>> print "Hello"
Hello
>>> print "Hello", "World"
Hello World
>>> print "Hello", "World", 1
Hello World 1

Types

>>> type("Hello")
<type 'str'>

Booleans

>>> True
True
>>> False
False

Containment

>>> "H" in "Hello" True >>> "X" in "Hello" >>> "a" in ["a", "b", "c"] True >>> "x" in ["a", "b", "c"] False

"a" not in "abcde"
"Perl" not in "Boston Python Workshop"

Equality

>>> 0 == 0 True >>> 0 == 1 False

"a" != "a"
"a" != "A"

<, <=, >, and >= have the same meaning as in math class:

1 > 0
2 >= 3
-1 < 0
.5 <= 1