Python Forum

Full Version: Random selection from list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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 + string
Two 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
print() returns None, so p_ask = print() doesn't do anything useful
x = print('Hi')
print(x)
Output:
None
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))
Output:
['Do', 'Are']
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))
Output:
Does