SharedSession 2.2.ipynbOpen in CoCalc
ATT Code Lab Session 2.2

# ATT Code Lab¶

## Session 2¶

Welcome to the second Code Lab for Applied Algorithmic Thinking! In this Lab, you will work with a colleague or two to work through a series of scaffolded problems to build knowledge and gain confidence in your programming skills. Take the time to work through each of the problems in order with your partner(s). Be sure that everyone understands each part of the code. Take turns explaining the concepts to each other; this is a great way to check your understanding. Work through as many problems as you can in this first session. After 20 minutes, you will come back to the whole class for a brief discussion of key concepts. Then you will go into new groups for a second 15 minute breakout session to continue the work. When the second session begins, introduce yourself to your partner(s), then take a moment to ask (and try to answer) any remaining questions, then continue working through the notebook. Then, then discuss how far each of you got through the workbook in the first breakout and pick up where you left off to continue through the workbook. Happy coding!

# Section A: Review and Debugging¶

#### A.1¶

Another friend of yours has written some programs with errors. He collected the birthdates of his classmates in a list and is trying to print their ages.

years = [1996, '1997', 1998, '1999', 2000, 1996, "1994"
for birthdate in range(years):
age = 2018 - birthdate
print(age)

 File "<ipython-input-10-83ecab997ae3>", line 1 try = [Integer(1996), '1997', Integer(1998), '1999', Integer(2000), Integer(1996), "1994"] ^ SyntaxError: invalid syntax 

#### A.2¶

Your friend is now trying to help you calculate the average of your grades for different exams. He writes the following code that is supposed to take as input the grades for three different exams and return the average.

exam_one = str(input("Input exam grade one: "))

exam_two = str(input("Input exam grade two: "))

exam_three = str(input("Input exam grade three: "))

sum = 0

avg = int(sum / len(grades)) # len(List) returns the length of the list which is the number of elements in that list

print(avg)



#### A.3¶

The following code should take as input a list of the hourly salary of workers and return their yearly salary. What's wrong? Fix it up.

list = str(input("enter the list of the hourly salary"))
hours = int(input("enter number of hours"))
for i in list:
s =  #fill this line to calculate the yearly salary
print(s)


 File "<ipython-input-1-d77badf3fc13>", line 4 s = #fill the code ^ SyntaxError: invalid syntax 

#### A.4¶

The following code should take as input a list and return the length of the list.

List = str(input("please enter a list of numbers")) # the input should be a list like [1,2,3,4,5]

count = 0

for i in range(List):
count = count - 1
print(count)


please enter a list of numbers

#### A.5¶

The following code should take as input a list of numbers and return the sum of all the numbers

List = str(input(please enter the list of numbers))

count = 0
for i in range(List):
count = count + count

print(count)

please enter the list of numbers
6

# Section B: Control Flow and Conditional Branching¶

How does Python know which line of code to execute next? Well, isn't it obvious that it should start at the first line, and then go to the second, and so on? While that's the general idea, we've already seen that Python does something different with loops. With the loops we've seen so far, it runs a group of lines repeatedly before progressing to the next line. Loops are one way of changing the flow of control from just going from top to bottom. In this section we will learn about how to make control flow branch based on the answer to a question.

#### B.1¶

In the last class we learned a bit about the == operator and other comparison operators. These operators compare two values and produce a value of True or False depending on whether the comparison is valid. The following comparisons are all True. Select a different value for x to make them all False.

x = 6
print(4+2 == x)
print(x * x > 30)
print(x / 2 != 2)
print(x >= 5)


True True True True

#### B.2¶

We can think of these True and False values (known as Boolean values after logician George Boole) as the answers to our questions. When we write 4+2 == x what it means is "4+2 equals the value stored in the variable x?" The result is our answer: True if x is 6 and False otherwise. We can make use of these answers to have our programs do something different depending on the answers. For instance, we might want to do one thing if 4+2 does equal x and another thing if it does not. To do this in python we use if statements.

Consider the following code. What does it do? Think about what input values you should try to explore the possible behaviors.

age = int(input("What is your age? "))

print("Bus tickets cost $2.50.") if age < 12: print("You qualify for a discounted bus ticket for only$0.50!")

Bus tickets cost $2.50. You qualify for a discounted bus ticket for only$0.50!

#### B.3¶

Suppose that the rules for bus tickets say that you get a discounted bus ticket if you are 12 or under. Is the above code a correct implementation? If not, how can you fix it?

age = int(input("What is your age? "))

print("Bus tickets cost $2.50.") if age < 12: print("You qualify for a discounted bus ticket for only$0.50!")


#### B.4¶

You've done such a great job fixing the bus ticket app that the city wants more of your expertise. They also have a discount for teens (age 18 and under) but the coder who worked on it was unable to implement it. Here is the code that she produced. Can you explain what's going wrong and why? What input values demonstrate the problem?

age = int(input("What is your age? "))

print("Bus tickets cost $2.50.") if age <= 12: print("You qualify for a discounted bus ticket for only$0.50!")
if age <= 18:
print("You qualify for a teen discount bus ticket for only $1.00.")  What is your age? Bus tickets cost$2.50. You qualify for a discounted bus ticket for only $0.50! You qualify for a teen discount bus ticket for only$1.00.

#### B.5¶

One way to fix the problem above is with more specific constraints in the Boolean expression to the if. Three other useful Boolean operators--and, or, and not--take Boolean expressions as inputs and combine them to produce a Boolean result. When you use the boolean operators and, or, and not you should be sure that the expression that you give to them are Boolean type expressions. (Note: Though Python will let you use Boolean operators on other types of values, it is bad style to do so as the code will be hard to understand.)

Guess what each of the following expressions will evaluate to before you run the code.

print(True and True)
print(True and False)
print(False and False)

print(True or True)
print(True or False)
print(False or False)

print(not True)
print(not False)

x = 6
y = 4

print(x > 5 and y > 5)
print(x > 5 or y > 5)
print(x > 5 and not y > 5)


True False False True True False False True False True True

#### B.6¶

Can you use these new operators to fix the bus ticket code so it only prints one, accurate discount message for people 12 and under? Hint: Try modifying the boolean expression of the second if.

age = int(input("What is your age? "))

print("Bus tickets cost $2.50.") if age <= 12: print("You qualify for a discounted bus ticket for only$0.50!")
if age <= 18:
print("You qualify for a teen discount bus ticket for only \$1.00.")


#### B.7¶

In the last problem you could fix it by modifying your conditions, but sometimes you want your code to take one action if a condition is true and another action if it is false. To handle this situation, Python (and most other programming languages) provide a way to specify actions when the condition is false, called an else clause. Here's a simple example:

x = int(input("enter a number"))

if x >= 0:
print("it is positive")
else:
print("it is negative")


It turns out that people are getting confused about whether their bus tickets cost $2.50 or$0.50 because it prints both messages. The city decides to make all bus tickets either full price ($2.50) or discounted ($0.50). So now all people 18 or under and all people 65 or over get discounted tickets and everyone else gets full price tickets. They ask you to rewrite the program so that it just prints out one line of text giving the ticket price. If the user is, say, 15 or 75, the program should print "Bus tickets cost $0.50". If the user is say, 35, the program should print "Bus tickets costs$2.50". All these changes are a great way to practice your coding, so you take on the challenge. Can you write the code using Python's if/else?




# Section C: Iteration Iteration Iteration¶

### 1. Game of 21¶

Write a program that uses a while loop to get integer inputs from the user until the sum of all the inputs is greater than or equal to 21.

sum = 0
while sum < 21:
x = input()
sum = sum + x


### 2. Empty Box¶

Design and algorithm and write a program that takes a side length (between 4-10) from the user and uses nested for loops to print an empty box.

### 3. Times Table¶

Design an algorithm and write a program that prints out a multiplication table with column and row headers for the numbers 1-10 and interior values that are the product of their column and row headers.




# Section D: Problem Solving¶

#### add interesting problems to solve here involving iteration!


## Fibonacci series¶

Write a Python program to print the Fibonacci series between 0 to 50.

Note : The Fibonacci Sequence is a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.

#your code here


Write a python program that takes the user name as input and then output the name reversed. for example, if the input is John, the output should be nhoJ

#your code here


### Sorting¶

Write a python program that takes a list of numbers and return the list sorted.

#your code here


### Challenge* Palindrome Detection¶

Write a program that checks whether the given input is a palindrome or not. "Feel free to check online what a palindrome is"

#your code here