0% found this document useful (0 votes)
43 views

Lab 1

The document provides an introduction to Python programming concepts including data types, variables, operators, flow control, and efficiency. It demonstrates how to use print statements, variables, mathematical and comparison operators, conditional statements, loops, and type conversions. It also compares the efficiency of different solutions to counting the number of zeros in a number.

Uploaded by

m.o.ren.je.n.l.y
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Lab 1

The document provides an introduction to Python programming concepts including data types, variables, operators, flow control, and efficiency. It demonstrates how to use print statements, variables, mathematical and comparison operators, conditional statements, loops, and type conversions. It also compares the efficiency of different solutions to counting the number of zeros in a number.

Uploaded by

m.o.ren.je.n.l.y
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1 Print function

Print function prints a textual representation to the console

In [35]: print("Hello world!")

Hello world!

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

Hello world!

2 Variables, types
2.1 int - integers: ..., -3, -2, -1, 0, 1, 2, 3, ...
In [1]: 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'>

2.2 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'>

1
2.3 str - character strings, text: "CS562", ’python’
In [2]: x = "CS462.py"
y = 'I like python'
print(x, type(x))
print(y, type(y))

CS462.py <class 'str'>


I like python <class 'str'>

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

<class 'int'> <class 'float'> <class 'str'>

2.4 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'>

3 Operators
3.1 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:

2
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

3.2 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'

3
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'

3.3 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

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

3.4 Logical operators


• not:

In [83]: print(not True)


a = 2 == 5
print(not a)

False
True

• and:

5
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

4 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'

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

5 Flow control
5.1 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 [9]: today = "Friday" # change to other days and test
strike = "N"
my_lecture = "Monday"

if today == "Sunday":
print("Today is Sunday")
if strike == "Y":
print("Stay home")
else:
print("Go out!")
elif today == "Wednesday":
print("lecture in Artificial Intelligence!")
elif today == my_lecture:
print("Go to class!")
elif today == "Monday" or today == "Tuesday" or today == "Thursday" or \
today == "Friday" or today == "Saturday":
print("No AI Class")
else:
print("Not a day")
no AI Class

7
5.2 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)

• 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)

Builtin solution:

8
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 [3]: %%timeit
num = 2**100
count = 0
for digit in str(num):
if digit == "0":
count = count + 1

100000 loops, best of 3: 2.29 µs 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.

6.0.1 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

You might also like