I want to create a list from a user's input and then return a random value from that list.
This is what I have so far for the code but I can't figure out how to get input for the array.
import random
movie_array = ["movieA", "movieB", "movieC"]
print(random.choice(movie_array))
I know about the input function but I'm not sure how to use it to create an array/list. I tried the following but it didn't work
movie_array = input()
but when I run the random.choice on that it only selects an individual character.
You can do it like this:
>>> import random
>>> movie_array = [input("Input a movie: ") for i in range(3)]
Input a movie: movieA
Input a movie: movieB
Input a movie: movieC
>>> print(random.choice(movie_array))
movieC
Use a loop.
In the body of the loop prompt the user to enter a movie title, or 'q' to quit. Append each entry to your movie list. When finished select a random movie from the movie list:
import random
movies = []
while True:
entry = input('Enter a movie title (q to quit): ')
if entry.lower() == 'q':
break
movies.append(entry)
if movies:
print(random.choice(movies))
Hopefully your users do not want to enter the movie entitled "Q" (1982). It might be better to use an empty entry as the sentinel, like this:
entry = input('Enter a movie title (<Enter> to quit): ')
if entry == '':
break
You can read movies in a single line separated by commas and then split it into array.
movie_array=raw_input("Enter Movies").split(',')
If it is python 3.x
movie_array=input("Enter Movies").split(',')
Just want to clarify why your solution attempt didnt work IE this:
movie_array = input()
It's because the input returns a string I.E a list of substrings so
you can seemovie_array = 'test' asmovie_array = ['t','e','s','t']
print(movie_array[1])
>>>'e'
in order to solve your problem I would recommend #mhawke answer (using a while loop)
By using a while loop you can retrieve multiple inputs and store each of them in a list. Be aware though that a while loop has to be able to "END" or it can cause problems. Therefore you have to have a break somewhere in the while loop.
Otherwise the program would be run indefinetly until you either forced it to shutdown or until it crashes.
Further information about this can be read here:
Tutorialspoint (Strings)
Tutorialspoint (Whileloop)
also checkout the official wiki for strings and control flow.
You can give it like this.
movie_array = [b for b in input().split()]
And then you can get input from user like this,
movieA movieB movieC
Related
Clarification: The user needs to specify an ID from a displayed list of ID's, how can I simplify the process by numbering the ID's so that the user just has to specify a simple number instead of the whole ID
I have a list ID = ['ekjgnrg','lrkjnk','etc..'] that I need to interact with by inputting the ID later on. The issue is it's a little tedious to type it in. (Copy-pasting would solve this but it doesn't work on mobile due to the way the message with the list is displayed.)
How can I assign a number to each string in the list so that the user can enter '1' instead of 'ekjgnrg' for simplicity? The list gets longer and shorter occasionally, so how can I make it scale to the size of the list?
Not sure how you present to user, but, you can do something like:
ID = ['ekjgnrg', 'lrkjnk', 'etc..']
print('Choose one of:')
for n,item in enumerate(ID):
print(f'{n}: {item}')
n = int(input('Enter ID number: '))
print(f'You choose number "{n}" which is "{ID[n]}".')
This really needs error checking, like gracefully handling if someone enters invalid data like "foo" or "1000"...
Results in:
Choose one of:
0: ekjgnrg
1: lrkjnk
2: etc..
Enter ID number: 1
You choose number "1" which is "lrkjnk".
You can access the Nth item using my_list[n] (in your case my_list is ID).
I suggest you to read: Python - Access List Items - W3Schools to understand how to work with list or other data structure in Python.
is this what you mean? if not, please elaborate more.
ID = ['ekjgnrg','lrkjnk','etc..']
print(ID)
needed_id = int(input("What item do you want from the above list?"))
needed_id -= 1 # since lists start at 0.
print(ID[needed_id])
when run:
['ekjgnrg', 'lrkjnk', 'etc..']
What item do you want from the above list?1
ekjgnrg
Just learning in Python 3, doing function building. I have a set of functions that take in multiple elements from the user and output the unique elements. I'm wondering if I can improve the program appearance because if there are large number of inputs they chain together, one after the next, each on a new line. Ideally, every time a user hits enter the input line takes the element and the same line resets for the next value.
Here's what I have:
userlist = []
uniquelist = []
def make_list(list): #function to assign only unique list values
for u in userlist:
if u not in uniquelist: #only append element if it already appears
uniquelist.append(u)
else:
pass
print("The unique elements in the list you provided are:", uniquelist)
def get_list(): #get list elements from user
i = 0
while 1:
i += 1 #start loop in get values from user
value = input("Please input some things: ")
if value == "": #exit inputs if user just presses enter
break
userlist.append(value) #add each input to the list
make_list(userlist)
get_list()
The output (in Jupyter Notebook) adds a Please input some things: line for each element a user inputs. 50 inputs, 50 lines; looks sloppy. I cannot find a way to have the function just use a single line, multiple times.
You just need to use the map function to take input in a single line and then split every data and then typecast it to form a map object and then pass it to the list function which would return a list in the variable like this:
var = list(map(int,input().split()))
Do you want to clear the text in the console after each input? Then you could use os.system('CLS') on Windows or os.system('clear') on Unix systems:
import os
os.system('CLS')
user_input = ''
while user_input != 'quit':
user_input = input('Input something:')
os.system('CLS') # Clear the console.
# On Unix systems you have to use 'clear' instead of 'CLS'.
# os.system('clear')
Alternatively, I think you could use curses.
I am currently writing a code for my GCSE coursework and I am kind of stuck with my for loop which also contains an if-else statement.
I have done a code similar to this earlier in the program and it works perfectly fine but for some reason this part doesn't and I was wondering if someone could help me.
What I am trying to do is make a quiz type program and the part that I need help with is choosing the subject that the user wants to do.
The user has to type in their preferred subject but if they type the subject in wrong, or type in something invalid, then the program should allow the user to type it in again.
So far, if you type in a subject correctly the first time, the program will proceed to the next stage.
However, if you type it incorrectly the first time, it will ask the user to try again. But if you type it in correctly the second time, it will again ask the user to try again. Instead of having the program make the user type the subject again, even though it should've been valid the when they typed it in correctly, I want the program to proceed to the next stage.
Available subjects:
subjects = []
algebra = ("algebra")
computing = ("computing")
subjects.append(algebra)
subjects.append(computing)
Part that I need help with:
with open("student_file.csv", "a+") as studentfile:
studentfileReader = csv.reader(studentfile, delimiter = ',')
studentfileWriter = csv.writer(studentfile, delimiter = ',')
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
ChosenSubject.lower()
for i in range(2):
if ChosenSubject in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject == input("What subject would you like to do?")
ChosenSubject.lower()
if ChosenSubject in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
In the else block, perhaps you'd want to replace the '==' with '='.
Also do you want to give the user just two tries or keep asking them until they answer correctly? (The latter is what I inferred from your question, for that I'd recommend using continue)
The for loop just iterates over a collection of objects. Consider a list my_list = ['a', 'b', 'c']. On each iteration over my_list using for loop, it fetches one of the elements in order without repetition. range(2) is equivalent to [0, 1].
Try this:
print("Available subjects:\n-Algebra\n-Computing\n")
for i in range(2):
# `i` is 0 on first iteration and 1 on second. We are not using `i` anywhere since all we want is to loop :)
chosen_subject = input("What subject would you like to do? ")
if chosen_subject.lower() in subjects:
print("\n")
break
if chosen_subject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This is not an optimal solution, but since your learning I will try to keep it as close as your solution. Your problem is that calling ChosenSubject.lower() does not change the actual value in ChosenSubject.
Here is a working example:
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
subjects = ["algebra", "computing"]
for i in range(2):
if ChosenSubject.lower() in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject = input("What subject would you like to do?") #not '=='
if ChosenSubject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This from the doc:
This method returns a copy of the string in which all case-based
characters have been lowercased.
Hi so I am new to python and I am creating this program where the user puts something in with the input function and if that input is equal to a variable something happens. My question is can you create a variable with a list of choice in the variable. Something I tried earlier and it did not work is down below.
vol_cube = ["CV" , "cv", "Cube_vol"]
So this did not work and my question is how do I have something similar to this.
Try this:
vol_cube = ["CV" , "cv", "Cube_vol"] # creates the list
while True: # loops until the user gives a correct input
user_input = input('Please enter something: ')
if user_input in vol_cube: # if their input is a value stored in vol_cube
break # breaks the loop
community,
I' m a total noob concerning python and I would like to create a little name-statistic with the program.
my code (I am using python 3.4.0):
while True:
eingabe = input ('Please enter a name: ')
print (eingabe)
if eingabe == '':
break
so now I would like to store the user input in a list. How can I do this?
Kind regards,
Lisa
Just define a list and then add new values to it with .append().
names = [] # Here we define an empty list.
while True:
eingabe = input('Please enter a name: ')
if not eingabe:
break
names.append(eingabe)
print(names) # it worked for me when I used "names" to print (since I want to print the list of all the values). Using "eingabe" did not work for me (but I may have had other conditions)