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
Related
My goal is to take two user inputs on a loop, save them in a dictionary, and when the user ends the loop, to have the save the dictionary.
# ------ Global Variables -------
user_cont = True
# ------- Functions -------
def get_Product():
while user_cont:
# get product code
get_ProductCode()
# get product number
get_ProductNum()
# save to dict
create_ProductDict()
# ask to continue
user_continue()
# save dict to file
def get_ProductCode(): works
def get_ProductNum(): works
def user_continue(): works but now is not getting prompted
What I'm currently trying to fix:
# save to dictionary
def create_ProductDict():
product_Dict = {}
productCode = get_ProductCode()
productNum = get_ProductNum()
print(product_Dict)
By my understanding on each loop, it should be receiving the returned productCode and productNum, and storing them? But now it won't ask the user to continue and end the loop so I can view the dictionary before I attempt to have the user save it.
In addition, I need to have the user choose a filename for the data.
As always, help is much appreciated!
There are two problems here. First issue is that your dictionary is being destroyed once the create_ProductDict() function ends, since the dictionary is created within the scope of the function.
One way to get around this would be to declare the dictionary in the global scope as a global variable. This way, the dictionary will persist as more items are added to it.
Next, your input variables currently aren't being used and the dictionary isn't being added to. The syntax for this is as follows:
productDict[productCode] = productNumber
So assuming that your input functions are equivalent to python's input() function, a solution that solves both of these issues would look something like this:
products = {}
def create_product_dict():
code = input("Enter Code: ")
num = input("Enter Number: ")
products[code] = num
create_product_dict()
create_product_dict()
print(products)
The output of this would be:
Enter Code: 123
Enter Number: 456
Enter Code: abc
Enter Number: 596
{'123': '456', 'abc': '596'}
Hope this is helpful :)
Try this:
def get_Product():
user_cont = True
while user_cont:
get_ProductCode()
get_ProductNum()
create_ProductDict()
user_cont = user_continue()
def user_continue():
ip = input('Enter Yes to Continue: ').lower()
return True if ip == 'yes' else False
Here is my finished main function after everything above pointed me in the direction I needed, but was not able to answer my questions entirely. My key finding was updating the dictionary before I asked to continue, and then adding the saving of the dictionary at the end. (The additional functions not included here as did not pertain to question/solution. Thank you!
user_cont = True
while user_cont:
# get product code
productCode = get_ProductCode()
# get product number
productNum = get_ProductNum()
# print(productCode, productNum)
# save to dict
products[productCode] = productNum
# debug to ensure dictionary was saving multi lines
# print(products)
# ask to continue
user_cont = user_continue()
for productCode, productNum in products.items():
formproducts = (productCode + ", " + productNum)
# print test
# print(formproducts)
# save dict to file
FILENAME = input(str("Please enter a file name: "))
file = open(FILENAME, "w")
file.write( str(products) )
file.close()
print("File saved.")
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.
How cab I repeat the raw_input sentence because every time I or the user answers the question written the python say press any key to continue but I want to repeat the question to know if the user want to do any thing else using the programme I wish you can help me.
You can use this simple code for that
x = raw_input("Enter a command or q to quit")
while ( x != 'q' ) :
## your code goes.
x = raw_input("Enter a command or q to quit")
This will recursively ask the user for input until he decides to quit.
You mean something as follows?
bool = True
while bool:
input = raw_input(query) #Get raw_input
if condition: #check if you should end the loop or ask again
bool = False #end loop
#your code here
bool is used as a boolean to check if the condition has happened, should call it something else such as run_loop or something like that.
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