Chapter 10
Task 2
- first_name asks for "Last name"
- last_name asks for "First name"
- last_name input is missing a bracket before the input string
- full_name variable uses non existent "First_name" variable rather than "first_name" variable
- full_name initialization uses "&" symbol instead of "+" symbol to concat strings
- Prin function has capital P where it shouldn't
- Prin function is misspelled, meant to be "print"
- full_name init does not use last_name variable but uses a string containing "lastname"
- full_name uses nonexistent variable "lastname" rather than "last_name" variable
- full_name forgets to close string literal 11. full_name forgets to close the string literal and concat last_name into the string 12. full_name has too many spaces between the beggining of the string and the "&" symbol
Part B
10.2: debugging.py
x = 1
first_name = "John"
last_name = "Doe"
full_name = f"{first_name} & {last_name}"
print("Enter your first name: " + first_name)
print("Enter your last name: " + last_name)
while (x < 10):
print(full_name)
x += 1
Output
>>> Enter your first name: John
>>> Enter your last name: Doe
>>> John & Doe
>>> John & Doe
>>> John & Doe
>>> John & Doe
>>> John & Doe
>>> John & Doe
>>> John & Doe
>>> John & Doe
>>> John & DoeTask 3
x at start of loop | number_int after calc | x at end of loop |
|---|---|---|
| 1 | 2 | 2 |
| 2 | 4 | 3 |
| 3 | 8 | 4 |
| 4 | 16 | 5 |
| 5 | 32 | 6 |
| 6 | 64 | 7 |
| 7 | 128 | 8 |
The following is the code that helped me get the above table
I used VSCode's built in debugger to debug the code, and get the values at each point.
Source: 10.3 numbers.py
number = 1
x = 1
while(x < 5):
number = number * 2
x = x + 1
print("Answer =", str(number))
I also improved upon that code as follows
Source: 10.3 numbers improved.py
from math import pow
print("Answer =", int(pow(2, 4)))
It yields the same output, except we have to use int to convert the float to an integer. Python really does work in mysterious ways
Output: 10.3 numbers improved.py
>>> Answer = 16Output: 10.3 numbers.py
>>> Answer = 16Task 4
This was the task where we added print statements to understand the values better at each point of execution
10.4: tracing.py
number = 1
x = 1
print("Enter an integer: " + str(number))
while(x < 5):
print(f"x at start of loop = {str(x)}")
print(f"number at start of loop = {str(number)}")
number = number * 2
x = x + 1
print(f"x at end of loop = {str(x)}\n")
print("Answer =", str(number))
Output
>>> Enter an integer: 1
>>> x at start of loop = 1
>>> number at start of loop = 1
>>> x at end of loop = 2
>>> x at start of loop = 2
>>> number at start of loop = 2
>>> x at end of loop = 3
>>> x at start of loop = 3
>>> number at start of loop = 4
>>> x at end of loop = 4
>>> x at start of loop = 4
>>> number at start of loop = 8
>>> x at end of loop = 5
>>> Answer = 16