35.9k views
5 votes
1. In Python syntax, create a list of 10 numbers (any numbers). Create your list 3 times, each time using a different syntax to define the list.

1. Write a while loop that prints the numbers from 1 to 10.
2. Convert your previous loop into a for loop.
3. Rewrite your for loop to only have one number in the range.
4. Write a for loop to print out each item of your list of 10 numbers, all on the same line, separated by & (ampersand).
In the previous question, you may notice that your line of numbers ends with the &. See if you can change this to only print the last number instead of the &. Hint: You’ll need to be clever about printing the last number from within the loop to make this work.

1 Answer

3 votes

Final answer:

This answer provides Python code to create and manipulate lists of numbers, and demonstrates the use of while and for loops.

Step-by-step explanation:

In Python syntax, create a list of 10 numbers (any numbers). Create your list 3 times, each time using a different syntax to define the list.

  1. Using square brackets:
  2. my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  3. Using the list() function:
  4. my_list = list(range(1, 11))
  5. Using a loop:
  6. my_list = []

  7. for i in range(1, 11):

  8. my_list.append(i)

1. Write a while loop that prints the numbers from 1 to 10.

i = 1
while i <= 10:
print(i)
i += 1

2. Convert your previous loop into a for loop.

for i in range(1, 11):
print(i)

3. Rewrite your for loop to only have one number in the range.

for i in range(0, 1):
print(my_list[i])

4. Write a for loop to print out each item of your list of 10 numbers, all on the same line, separated by & (ampersand).

for i in range(len(my_list)):
print(my_list[i], end='')
if i != len(my_list) - 1:
print('&', end='')

5. See if you can change this to only print the last number instead of the &.

for i in range(len(my_list)):
print(my_list[i], end='')
if i == len(my_list) - 2:
print(my_list[i+1], end='')

User Dbgrman
by
7.5k points