handin21
before Saturday nightfor
loopsBefore Wednesday, all of our programs were sequential - with one line of code following the other. Often, we need to repeat a task several times. If we know the number of times, we use definite loops which are called for loops in Python. The syntax is:
for VAR in SEQUENCE:
BODY
for i in range(5):
print(n-i)
This semester, you will see many different kinds of for loops. We hope to give you some more experience/practice with for loops today.
A very common use of loops is to aggregate, or combine, the result of a repetitive set of steps. For example, we may want to sum the numbers from 1 to n. To create an accumulator pattern, we should first answer these questions to help us code the solution:
Together, we will show in avg.py
how to use an accumulator pattern to average a series of numbers entered by a user.
Work with a neighbor and sketch out your solution to calculating the factorial of a number. Do not start to code until you have answered all of the questions above for designing an accumulation pattern. Your program should ask the user for a number (integer) and calculate the factorial. The factorial of a number is n!=n * (n − 1)*(n − 2)*...*2 * 1 e.g., 5!=5 * 4 * 3 * 2 * 1. Begin by answer the questions above and then start to write your program in factorial.py
.
You've seen several instances of strings already this semester, and you've likely used string concatenation to build up a string. There are many other useful string operations. Here are some highlights:
len
command e.g. len("cs21") = 4
name="Joshua"
, then name[1] = "o"
.+
operator. "hello" + "world" == "helloworld"
print()
. Alternatively, use \n
to get a line break. The print command gives you a line break for free, so print("I like blank lines!\n")
will produce a blank line after "I like blank lines"Open str_practice.py
to complete four tasks and a couple of extensions if you desire. Be sure to incrementally develop---complete one task, run your program to see if that tasks works, and then move onto the next. Tasks 4 and bonus will require for loops and accumulators.
$ python3 str_practice.py
Task 1:
Enter first name: Joshua
Enter last name: Brody
Welcome Joshua Brody
Task 2:
There are 11 characters in your name
Task 3:
Initials: J.B.
BONUST:
Last initials: a.y.
Task 4:
J
o
s
h
u
a