In: Computer Science
1. Write Python code to -
(a) ask user to enter a list of animals, one item at a time, until
“done” to terminate input
(b) randomly display a selected item from the list, starting with
“I like ______”.
When run, the output should look something like
this:
Enter an item; 'done' when finished: cats
Enter an item; 'done' when finished: dogs
Enter an item; 'done' when finished: guinea pigs
Enter an item; 'done' when finished: done
You are done entering items.
I like guinea pigs
2. Given the following two strings:
str_1 = "the rain! in Spain falls mainly on the plains"
str_2 = "cats don't like dogs and mice. What a day."
Implement logic to produce the following output by manipulating str_1 and str_2.
# Output ---> rain! What a day.
1)
Python code:
from random import randint
#initializing lis
lis=[]
#accepting animal name
item=input("Enter an item; 'done' when finished: ")
#looping till done is entered
while(item!="done"):
#adding it to lis
lis.append(item)
#accepting next item
item=input("Enter an item; 'done' when finished:
")
#printing done entering items
print("You are done entering items.")
#printing a random item from list
print("I like",lis[randint(0,len(lis)-1)])
Screenshot:
Input and Output:
2)
Python code:
#initializing str_1
str_1="the rain! in Spain falls mainly on the plains"
#initializing str_2
str_2="cats don't like dogs and mice. What a day."
#printing rain! from str_1 and What a day from str_2
print(str_1[4:10]+str_2[-11:-1])
Screenshot:
Output: