Write a program that has a loop to read in ten strings and put them into a list. Write a second loop to print the strings in the reverse order. This is an exercise in indexing, so do not use the reverse() method of list. Print the index in the following format. The actual strings you read in are arbitrary. Example format when running q1.py:
Enter string 0/10: the blue moon
Enter string 1/10: the red guitar
Enter string 2/10: go home
Enter string 3/10: spill the beans
Enter string 4/10: winter in Oklahoma
Enter string 5/10: Baltimore
Enter string 6/10: very, very strange
Enter string 7/10: Jerimiah
Enter string 8/10: I believe it was July.
Enter string 9/10: We opened our doors.
String 9/10: We opened our doors.
String 8/10: I believe it was July.
String 7/10: Jerimiah
String 6/10: very, very strange
String 5/10: Baltimore
String 4/10: winter in Oklahoma
String 3/10: spill the beans
String 2/10: go home
String 1/10: the red guitar
String 0/10: the blue moon
this is my code solution but it doesnt work can someone help me :
def function1():
list = []
for i in range(10):
x = str(input('Enter a string' '(i)' '/10:'))
list.append(i)
for i in range(9, -1, -1):
print("String",i,"/10:",list[i])
addition i cant get my code to be in the same format as the output strings which is
Enter string 4/10: winter in Oklahoma
&
String 4/10: winter in Oklahoma
CodePudding user response:
lst = []
for i in range(1,11):
x = input(f'Enter a string {i}/10: ')
lst.append(x)
for i,j in enumerate(lst[::-1]):
print(f'String {10-i}/10: {j}')
I've made some changes to your code, don't overwrite keywords (list)
, you meant to append the input value x
but append the iteration count i
, to reverse a list you can use slice notation
with a step of -1
and you can use f strings
instead of concatenating strings.
CodePudding user response:
Do not use keywords as variable names, such as list
, int
, str
, and so on.
Append the x
variable instead of i
:
your_list = []
for i in range(10):
x = str(input(f'Enter a string {i}/10:'))
your_list.append(x)
for j in range(len(your_list)-1,-1,-1):
print(f"String {j}/10:{your_list[j]}")
CodePudding user response:
Firstly, you are appending the wrong thing into the list, you are appending i whereas you should be appending x.
Secondly, do not name your variables as the keywords that are used in python.
Lastly, the solution to get the exact output you want is -
string_list = []
# Loop 1
for i in range(10):
string = input(f'Enter string {i 1}/10: ')
string_list.append(string)
# Loop 2
for i in range(9,-1,-1):
print(f'String {i 1}/10: {string_list[i]}')