Hi I have to create a simple For Loop but i’m having trouble knowing
where to start, this is the program I have to create
We try not to do homework, but are happy to offer advice and answer
specific questions. Some advice follows. Ideally, if you still want
help, come back with the programme you have written, however incomplete,
Create a new program called Lab3A2
Probably means make a file calls Lab3A2.py
that will ask the user to enter an integer
There’s a builtin input() function which issues a prompt and reads a
line of text. Note that it returns a string (str) which needs to be
converted to what you want, such as an integer (int).
- The program should use a for loop to:
a. Add all the numbers between 1 and the input number.
b. Count all the numbers between 1 and the input number.
I’m assuming that means the values from 1 through to n (the input
number), not 2 to n-1 (which is what between tends to actually mean).
So this is asking you to write a for-loop which produces every value
from 1 through to n inclusive, and does stuff inside the loop for each
such value. A for-loop has the form:
for i in "some iterable thing":
... do something with "i" ...
Note the indentation: the code indented below the loop is what happens
inside the loop, once per iteration.
The name “i” can be anything, but when you’re looping over integers “i”
is not a bad name. So what remains is the iterable thing which produces
the values you want. Python comes with a builtin function called range()
which produces values like what you want.
Have a look in the Python docs for the input() function and range()
function: 3.9.7 Documentation
I find the index (link at top right) a good place to go to find
arbitrary things like input and range.
Inside the loop you use the value in “i” to compute the sum in step (1)
above and to advance a counter as in step(2). For (1), set some variable
maybe named “total” to 0 before the loop, and add to it inside the loop.
- After the loop has completed, calculate the average of all the numbers between 1 and the input
The average can be computed from the total. What is the formula for the
average? use that.
- Print the sum and average with labels.
The print() function is your friend here. You can find that in the index
of the Python docs above as well.
Cameron Simpson firstname.lastname@example.org