Random selection from list - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Random selection from list (/thread-25471.html) |
Random selection from list - Mohsky - Mar-31-2020 Hi everyone, This is not homework per se, but I am teaching myself(as everyone else has done before) python by taken courses, books, and online practices. Here is a very basic exercise with the solution: Quote:19. Write a Python program to get a new string from a given string where "Is" has been added to the front. If the given string already begins with "Is" then return the string unchanged. string = input('Type words here:') def new_str(string): if len(string) >= 2 and string[:2] == 'Is': # string[:2] index for the first word == Is return str return 'Is ' + string print(new_str(string))Nothing too fancy about this! I found that I learn by expanding on basic exercises, so what I want to do is instead of just indexing 'Is' create a list and select randomly from the list. import random string = input('Type your stantance ') ask = ['Is', 'Do', 'Does', 'Are'] # this is a list and need to be string or tuple st_ask = ''.join(ask) p_ask = print(random.choices(st_ask)) def new_str1(string): if string.startswith(st_ask): return string else: return p_ask + stringTwo problems here: What code to use get the (random. )function to select from the list as in ask? Apparently, I can not return p_ask + string and concatenate with a string RE: Random selection from list - deanhystad - Mar-31-2020 print() returns None, so p_ask = print() doesn't do anything useful x = print('Hi') print(x) Your use of random.choices was correct until you joined all the ask elements into a string.import random ask = ('Is', 'Do', 'Does', 'Are') print(random.choices(ask, k=2)) My guess though is that you didn't want a list of choices, but a single choice:import random ask = ('Is', 'Do', 'Does', 'Are') print(random.choice(ask))
|