CS1001.py

Extended Introduction to Computer Science with Python, Noshirvani University, winnter 2015

Python general comments

  1. Course site at http://tau-cs1001-py.wikidot.com
  2. Programming language -> Interpreter -> Machine language
  3. IDLE (editor + interpreter), see site for installation instructions
  4. Interactive mode vs. Script mode
  5. Python version 3.2
  • print function - prints a textual representation to the console

In [9]:
from pprint import pprint
x=['z','a','w']
print(x)
x.sort()
print (x)


[1, 10, 5]
[1, 5, 10]

In [36]:
print("Hello", "world!")


Hello world!

Variables, types

  • int - integers: ..., -3, -2, -1, 0, 1, 2, 3, ...

In [37]:
x=5
y=-3
print(x, type(x))
print(y, type(y))


5 <class 'int'>
-3 <class 'int'>

In [38]:
x = 5.5
print(type(x))


<class 'float'>
  • float - floating point numbers, decimal point fractions: -3.2, 1.5, 1e-8, 3.2e5

In [39]:
x=5.0
y=-3.2
z=2.2e6
print(x, type(x))
print(z, type(z))


5.0 <class 'float'>
2200000.0 <class 'float'>
  • str - character strings, text: "intro2CS", 'python'

In [40]:
x = "CS1001.py"
y = 'I love python'
print(x, type(x))
print(y, type(y))


CS1001.py <class 'str'>
I love python <class 'str'>

In [41]:
print(type(4), type(4.0), type("4"))


<class 'int'> <class 'float'> <class 'str'>
  • bool - boolean values: True and False

In [42]:
i_love_python = True
python_loves_me = False
print(i_love_python, type(i_love_python))
print(python_loves_me, type(python_loves_me))


True <class 'bool'>
False <class 'bool'>

Operators

Mathematical operators

Addition:


In [45]:
4 + 5


Out[45]:
9

In [46]:
x = 5
4 + x


Out[46]:
9

In [47]:
x = 4.0 + 5
print(x, type(x))


9.0 <class 'float'>

Subtraction:


In [48]:
x - 3


Out[48]:
6.0

Multiplication:


In [49]:
x * 3


Out[49]:
27.0

Division - float and integral with / and //:


In [50]:
10 / 3, 10 // 3


Out[50]:
(3.3333333333333335, 3)

Power:


In [52]:
2 ** 3, 2 ** 3.0, 3 ** 2


Out[52]:
(8, 8.0, 9)

Modolu:


In [53]:
10 % 3


Out[53]:
1

String operators

String concatenation using +:


In [55]:
"Hello" + " World"


Out[55]:
'Hello World'

String duplication using *:


In [58]:
"Bye" * 2


Out[58]:
'ByeBye'

Strings vs. numbers:


In [59]:
4 + 5


Out[59]:
9

In [60]:
"4" + "5"


Out[60]:
'45'

In [61]:
"4" + 5


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-61-f945f8c7e111> in <module>()
----> 1 "4" + 5

TypeError: Can't convert 'int' object to str implicitly

In [62]:
4 + "5"


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-62-871c0c3bbca2> in <module>()
----> 1 4 + "5"

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Comparisons


In [63]:
5 < 4


Out[63]:
False

In [64]:
5 > 4


Out[64]:
True

In [65]:
5 >= 4


Out[65]:
True

In [66]:
4 >= 4


Out[66]:
True

In [73]:
4 <= 3


Out[73]:
False

In [67]:
5 == 4


Out[67]:
False

In [68]:
5 == 5.0


Out[68]:
True

In [69]:
5 == "5"


Out[69]:
False

In [70]:
5 != 4


Out[70]:
True

In [71]:
2 + 2 == 4


Out[71]:
True

In [72]:
2 => 3


  File "<ipython-input-72-76c8f045e4cf>", line 1
    2 => 3
       ^
SyntaxError: invalid syntax

In [77]:
x = 1 / 3 
print(x)
x == 0.3333333333333333


0.3333333333333333
Out[77]:
True

Logical operators

  • not:

In [83]:
print(not True)
a = 2 == 5
print(not a)


False
True
  • and:

In [84]:
True and True


Out[84]:
True

In [85]:
True and False


Out[85]:
False

In [86]:
False and False


Out[86]:
False
  • or:

In [87]:
True or True


Out[87]:
True

In [88]:
True or False


Out[88]:
True

Conversions

Use the functions int(), float(), and str() to convert between types (we will talk about functions next time):


In [91]:
x = "6"
print(x, type(x))
x = int("6")
print(x, type(x))


6 <class 'str'>
6 <class 'int'>

In [92]:
float("1.25")


Out[92]:
1.25

In [93]:
str(4)


Out[93]:
'4'

In [94]:
int("a")


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-94-91097a4105a2> in <module>()
----> 1 int("a")

ValueError: invalid literal for int() with base 10: 'a'

In [98]:
course = "intro" + str(2) + "cs"
print(course)
print("intro", 2, "cs", sep='')


intro2cs
intro2cs

Flow control

Conditional statements

The if condition formula - replace conditions and statements with meaningful code:

if *condition*:
    *statement*
    *statement*
    ...
elif *condition*: # 0 or more elif clauses
    *statement*
    *statement*
    ...    
else:             # optional
    *statement*
    *statement*

Example:


In [101]:
today = "Monday"
strike = "N"
my_recitation = "Monday"

if today == "Sunday":
    print("Shvizut Yom Alef")
    if strike == "Y":
        print("Stay home")
    else:
        print("Lecture in intro to CS!")
elif today == "Wednesday":
    print("Another lecture in intro to CS!")
elif today == my_recitation:
    print("Go to recitation!")
elif today == "Monday" or today == "Tuesday" or today == "Thursday" or \
                    today == "Friday" or today == "Saturday":
    print("no intro to CS")
else:
    print("Not a day")


Go to recitation!

Loops

  • While:
while *condition*:
    *statement*
    *statement*

Example - count how many times 0 appears in an integer number:


In [102]:
num = 2**100
print(num)


1267650600228229401496703205376

In [103]:
count = 0

while num > 0:   #what if we changed to >=0?
    if num % 10 == 0:
        count = count + 1
    num = num // 10

print(count)


6
  • For:
for *variable* in *iterable*:
    *statement*
    *statement*

Example - solve the same problem with a str type instead of int:


In [105]:
num = 2**100
count = 0
for digit in str(num):
    #print(digit, type(digit))
    if digit == "0":
        count = count + 1

print(count)


6

Builtin solution:


In [106]:
num = 2**100
count = str.count(str(num), "0")

print(count)


6

Efficiency

We can measure which solution is faster:


In [108]:
%%timeit
num = 2**100
count = 0
while num>0:   #what if we changed to >=0?
    if num % 10 == 0:
        count = count + 1
    num = num // 10


10000 loops, best of 3: 37.4 us per loop

In [109]:
%%timeit 
num = 2**100
count = 0
for digit in str(num):
    if digit == "0":
        count = count + 1


100000 loops, best of 3: 8.76 us per loop

In [110]:
%%timeit 
num = 2**100
count = str.count(str(num), "0")


100000 loops, best of 3: 2.82 us per loop

The builtin solution is 4 times faster than the for solution which is 3 times faster than the while solution.

Other notes

  • The while solution will not work for num <= 0
  • The while solution will not work for non-numerals (e.g, num = "Cola 0 is awesome!")
  • The builtin solution is implemented with C and that is why it is faster

Fin

This notebook is part of the Extended introduction to computer science course at Tel-Aviv University.

The notebook was written using Python 3.2 and IPython 0.13.1.

The code is available at https://raw.github.com/yoavram/CS1001.py/master/recitation1.ipynb.

The notebook can be viewed online at http://nbviewer.ipython.org/urls/raw.github.com/yoavram/CS1001.py/master/recitation1.ipynb.

The notebooks is also available as a PDF at https://github.com/yoavram/CS1001.py/blob/master/recitation1.pdf?raw=true.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.