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.
Related
I am writing a English dictionary using python 2. I created a dictionary. for example, "home" and "horse" in the dictionary's key. If the user types "ho", "home" and "horse" will come. I put these in the bottom line. But when the user selects word 1, I want to call the key and value in the dictionary that I set first. How can I do it?
myEngDict = {"horse": "The horse (Equus ferus caballus) is one of two extant subspecies of Equus ferus","home": "the place where one lives permanently, especially as a member of a family or household."}
def Words():
word_List = []
count = 0
search_words = raw_input("Please enter a search term: ")
for i in myEngDict.keys():
if i.startswith(search_words):
count+=1
word_List.append(i)
print "{}{}{}".format(count,".", i)
else:
pass
choose = input("Which one?")
For example, if "home" comes out first, user choose 1:
Program display:
home: the place where one lives permanently, especially as a member of a family or household.
First, you should use raw_input in that final line. Then you need to look up the provided in the word_List.
while True:
try:
choose = int(raw_input("Which one?"))
# Keep the key as a separate variable for faster reference
key = word_List[choose - 1]
# Use labels with the format function. It's easier to read and understand
print '{label}: {text}'.format(label=key, text=myEngDict[key])
# Be sure to have a break or return on success.
return
except ValueError:
# If someone provides 'cat', it will raise an error.
# Inform the user and go back to the start.
print 'Please provide an integer'
except IndexError:
# The user has provided a value above the length of word_List or
# less than one. Again, inform the user and go back to start.
print 'You must enter a number between 1 and {c}'.format(c=len(word_List))
By not changing to much your code, you can just add a print statement after choose in your function at the same identation:
print ("%s : %s"%(word_List[choose-1], myEngDict[word_List[choose-1]]))
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
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
Forgive me if this comes out a bit scatter-brained, I'm not exaggerating when I say I've been working on this program for over 13 hours now and I am seriously sleep deprived. This is my 4th revision and I honestly don't know what to do anymore, so if anyone can help me, it would be greatly appreciated. My introduction to programming teacher wanted us to make a "flash card" study program from his template. I am using Idle 3.3.3 on a windows 7 machine.
#Flash Cards
#Uses parallel arrays to store flash card data read from file
#Quizzes user by displaying fact and asking them to give answer
import random
def main():
answer = [] #array to store answer for each card
fact = [] #array to store fact/definition for each card
totalTried = 0 #stores number of cards attempted
totalRight = 0 #stores number of correct guesses
loadCards(answer, fact) #call loadcards() and pass it both arrays
numCards = len(answer) #find number of cards loaded
keepGoing = "y"
while keepGoing == "y" or keepGoing == "Y":
#Enter your code below this line
# 2a. Pick random integer between 0 and numCards and store the
# number in a variable named randomPick.
randomPick = random.randint (0, numCards)
# 2b. Add one to the totalTried accumulator variable.
totalTried = totalTried + 1
# 2c. Print element randomPick of the fact array. This shows the
# user the fact/definition for this flashcard.
print (fact [randomPick] )
# 2d. Prompt the user to input their guess and store the string they
# enter in a variable named "userAnswer"
userAnswer = input ('What is your answer?' )
# 2e. Compare the user's guess -userAnswer- to element
# -randomPick- of the answer array.
if userAnswer == (answer [randomPick]):
# 2e-1 If the two strings are equal, tell the user they
# guessed correctly and add 1 to the totalRight
# accumulator variable.
print ('That is correct.')
totalRight == totalRight + 1
# 2e2. If the two strings are not equal, tell the user they guessed
# wrong and display the correct answer from the answer array.
else:
print ('That is incorrect.')
print (answer [randomPick])
#2f. Prompt the user the user to see if they want to continue and
#store their response in the keepGoing variable.
keepGoing = input ('Would you like to continue?')
#Enter your code above this line
print("You got", totalRight, "right out of", totalTried, "attempted.")
def loadCards(answer, fact):
#Enter your code below this line
# 1a. Open flashcards.txt in read mode & assign it var name "infile"
infile = open('flashcards.txt', 'r')
# 1b. Read 1st line from file and store in var. name "line1"
line1 = infile.readline ()
# 1c. Use while loop to make sure EoF has not been reached.
while line1 != '':
# 1c1. Strip newline escape sequence (\n)from variable's value.
line1 = line1.rstrip ('\n')
# 1c2. Append string to answer array.
answer.append (line1)
# 1c3. Read next line from file and store in var. name "line2"
line2 = infile.readline ()
# 1c4. Strip newline escape sequence (\n) from variable's value.
line2 = line2.rstrip ('\n')
# 1c5. Append the string to the fact array.
fact.append (line2)
# 1c6. Read next line from file and store it in var. name "line3".
line3 = infile.readline ()
# 1d. Close file.
infile.close()
#Enter your code above this line
main()
When I run the program nothing actually happens, but when I try to close the shell window afterwards, it tells me that the program is still running and asks if I want to kill it.
Debugger shows me no information when I try to check it, also.
However, if I copy the code into the shell and run it from there, I get "SyntaxError: multiple statements found while compiling a single statement". Neither file has changed, but earlier it was telling me there was a problem with "import random".
Thanks in advance for any help.
I took a quick look and it mostly seems okay to me. I changed input() to raw_input() (two of them in your code) and noticed you had a double equals when you probably meant a single one
line 36:
totalRight == totalRight + 1
changed to
totalRight = totalRight + 1
which fixes your correct answer counter and line 68:
line3 = infile.readline ()
changed to
line1 = infile.readline ()
else it gets caught in your while loop forever. And I just copied line 54:
line1 = infile.readline ()
and pasted it so it is there twice to add another readline() call, just a lazy way of skipping the first line in your text file, since it seems to be a comment and not part of the answers and questions. You probably don't want to do that and just remove the comment from your text file. =b
With those changes, it seems to work fine for me.
Since this is for a class (and I can't only comment, I can just answer) I want to add that there actually is such a thing as too many comments
These comments (and to be honest, most of your comments) are distracting and unnecessary
answer = [] #array to store answer for each card
fact = [] #array to store fact/definition for each card
totalTried = 0 #stores number of cards attempted
totalRight = 0 #stores number of correct guesses
loadCards(answer, fact) #call loadcards() and pass it both arrays
numCards = len(answer) #find number of cards loaded
Also, the whole point of putting your program inside of a function called main is so you can run that function only if you are calling that file directly and you should probably put
if __name__ == '__main__':
main()
at the bottom of your code instead of just
main()
Use of input() is generally considered dangerous (unless you're using Python3 or later where it is the same as raw_input()) due to the fact that it evaluates the input. You should handle the type yourself with something like, if you want an integer,
foo = int(raw_input('Input a number: '))
(Note that the return of raw_input is a string, so if you want a string you don't have to do anything)
i have a programm that generate the list and then i ask them to tell me what they want to do from the menu and this is where my problem start i was able to get the input form the user to different function but when i try to use the if else condition it doesn't check, below are my code
def menu(x,l):
print (x)
if x == 1:
return make_table(l)
if x == 2:
y= input("enter a row (as a number) or a column (as an uppercase letter")
if y in [ "1",'2','3']:
print("Minmum is:",minimum(y,l))
if x== 3:
print ('bye')
def main():
bad_filename = True
l =[]
while bad_filename == True:
try:
filename = input("Enter the filename: ")
fp = open(filename, "r")
for f_line in fp:
f_str=f_line.strip()
f_str=f_str.split(',')
for unit_str in f_str:
unit=float(unit_str)
l.append(unit)
bad_filename = False
except IOError:
print("Error: The file was not found: ", filename)
#print(l)
condition=True
while condition==True:
print('1- open\n','2- maximum')
x=input("Enter the choice")
menu(x,l)
main()
from the bottom function i can get list and i can get the user input and i can get the data and move it in second function but it wont work after that.thank you
I think your problem is simple, and has nothing to do with how you're passing values between functions.
In main, you're reading a value from the user like this:
x=input("Enter the choice")
The input function:
… reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
So, if the user types 1 at the prompt, you get back the string "1".
Now, you pass that value—perfectly correctly—to menu.
In menu, you then try to compare it to various numbers, like this:
if x == 1:
But this will never be true. A string, like "1", is never equal to a number, like 1. They're not even the same kind of value, much less the same value.
So, you need to do one of two things:
Convert the input to an number. For example, change menu(x,l) to menu(int(x), l). OR…
Write menu to expect strings. For example, change if x == 1: to if x == "1":.
You may be wondering why that print (x) didn't help you debug the problem.
print(x) prints out the end-user-friendly string representation of whatever you give it. That is, it automatically calls the str function for you. For debugging purposes, you often want to use repr instead of str, to get the programmer-friendly string representation instead of the end-user-friendly string representation.
For example, print(str("10")) will print out 10—just like print(str(10)), so you can't tell them apart. But print(repr("10")) will print out '10', unlike print(repr(10)), while prints 10, so you can tell them apart. repr can also help you spot things like strings with invisible characters in them, having special "node" objects from a parser instead of just strings, etc.