Skip to content

Commit cc96971

Browse files
committed
why we use types task
1 parent b5089a2 commit cc96971

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

sprint-5/why_we_use_types.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#=================================================================================
2+
# Exercise 1: Predict what double("22") will do. Then run the code and check.
3+
# Did it do what you expected? Why did it return the value it did?
4+
#=================================================================================
5+
def double(value):
6+
return value * 2
7+
8+
# Prediction:
9+
# double("22") will return "2222" because when you multiply a string by
10+
# an integer in Python, it concatenates the string that many times.
11+
# So "22" * 2 will result in "22" + "22", which is "2222".
12+
13+
print("Exercise 1: double('22') =", double("22"))
14+
15+
# Actual output: double('22') = 2222
16+
17+
#=================================================================================
18+
# Identify the bug in double()
19+
#=================================================================================
20+
def double_bug(number):
21+
# Bug: This function is called "double" but multiplies the input by 3 instead of 2.
22+
# This is a logic error, not a type error
23+
return number * 3
24+
25+
print("Exercise 2:", double_bug(10))
26+
27+
#=================================================================================
28+
# About half(), double(), second()
29+
#=================================================================================
30+
def half(value):
31+
return value / 2
32+
33+
def double(value):
34+
return value * 2
35+
36+
def second(value):
37+
return value[1]
38+
# Prediction and explanation:
39+
40+
# half(22) --> 11.0
41+
# half("hello") --> TypeError, because you cannot divide a string by a number.
42+
# half("22") --> TypeError, because you cannot divide a string by a number.
43+
44+
# double_correct(22) --> 44
45+
# double_correct("hello") --> "hellohello", because multiplying a string by an integer concatenates it.
46+
# double_correct("22") --> "2222"
47+
48+
# second(22) --> TypeError, because you cannot index an integer.
49+
# second(0 x 16) --> TypeError, because you cannot index an integer.
50+
# second("hello") --> "e", because it returns the second character of the string.
51+
# second("22") --> "2", because it returns the second character of the string.
52+

0 commit comments

Comments
 (0)