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.")
Related
I have a dictionary of names {first : last}, and I am looking to take in a user input to cross reference the keys in that dictionary, while using an if/else statement. At one point it was working as intended but after running it multiple times to test something further down in the code, it randomly stopped working, despite it being in a separate function.
Code:
def find_tech():
t2techs = {'FirstName1': 'LastName1', 'FirstName2': 'LastName2'}
t1techs = {
'FirstName3': 'LastName3',
'FirstName4': 'LastName4',
'FirstName5': 'LastName5',
'FirstName6': 'LastName6',
'FirstName7': 'LastName7',
'FirstName8': 'LastName8'
}
all_techs = t2techs.copy()
all_techs.update(t1techs)
print('Who was your support tech today? \n')
for key, value in all_techs.items():
print(key)
x = input('\nTech: ')
if x is key in all_techs.keys():
print('Thanks.\n')
else:
print('Invalid selection \n') + find_tech()
find_tech()
Note: FirstName# and LastName# are string values, actual names are hidden for confidentiality.
All inputs loop the else statement.
students = {}
grade_collect = False
id_collect = True
while id_collect == True:
ID = input(str('What is your student ID?'))
students[ID] = {}
students[ID]['Name'] = input(str('What is the student\'s name?'))
decision = input('Would you like to enter another student? (y/n)')
if decision == 'y':
continue
else:
number = input('How many assignments were given?')
id_collect = False
grade_collect = True
break
while grade_collect == True:
for x in range(int(number)):
x = input('Please enter the scores for ' + students[ID]['Name'])
print(x)
I am trying to write a program that stores Student IDs, Names, grades, and scores that are inputted by the user; and eventually printing out the average scores for each student.
Because I have the keys for the dictionary as a variable 'ID' I cannot figure out how to get the program to prompt for the grades of more than one student; it just repeats itself. In the first part of my code, I can get the dictionary to store all of the names and IDs, but when I need to go through the students by their IDs to ask the user what the grades on each assignment are, it only asks the most recent student ID in the dictionary.
I hope this is clear, thanks for any help.
Edit for clarification: By 'when the key is a variable' I meant that the variable ID is the key to each value.
ex.
{'1245': {'Name': 'Connor'}, '6789': {'Name': 'Josh'}}
The IDs aren't hard-coded, they are user input so they are a variable in the code itself. That is the part that is confusing me. Sorry for the confusion.
Since you have already created a dictionary of students ID, you technically do not need another while loop. You can simply do the following to grab each users score.
for id in students:
score = input("Please enter the scores for " + students[id]["Name"])
students[id]["Score"] = score
If there are multiple assignments, then another while-loop would be appropriate.
You can loop over all IDs using:
for id in students:
#now in each iteration, 'id' points to one of the IDs in the keys
#whatever you want to do with students[id]...
try:
for s in list(students):
students[s]
Edited to better address the question.
I am running with some issue. I will like to view the number of times a user has delete a value from a key even if the user exits the program, it will still retain that number. So that in future if the user will to delete any values again, it will use the existing number and add on from there.
edited: Just to add. All the dict will be store on a .txt file
dict= {} #start off with an empty list
key_search = ("Enter to find a key")
if options_choose == 2:
c = input('Which value would you like to change? ')
c = change.lower()
if change in list_of_value:
loc = list_of_value.index(c)
list_of_value.remove(c)
correction = input("Enter correction: ")
correction = correction.lower()
print(f"value(s) found relating to the key '{key_search}' are:")
list_of_value.insert(loc, correction)
list_of_value = dict[key_search]
for key, value in enumerate(list_of_value, 1):
print(f"{key}.) {value}")
else:
print('Entry invalid')
As you can see in the below screenshot I have exited and re-entered the program with the same counter.
You can adapt this to fit the features of your program. Since it seems like the code you provided is incomplete, I have substituted it with an example of dictionary modification to show how you can store and read a value after program termination.
You have to have a folder with test.py and modification.value.txt inside. Write "0" inside the text file.
ex_dict= {'example_entry':1}
#Read in the value stored into the text file.
with open('modification_value.txt','r') as file:
counter = int(file.readline()) #counter value imported from file.
print('Counter: ', counter)
modify_dict = True #boolean to check when user wants to stop making changes
while modify_dict == True:
for key in ex_dict:
dict_key = key
new_value = input('Enter value for new key.\n')
ex_dict[dict_key] = new_value
counter+=1
print('New dictionary: ', ex_dict, '\n')
response = input("Do you still want to modify Y/N?\n")
if (response =='Y'):
continue
elif(response =='N'):
modify_dict=False
#Write the value of the counter recorded by the program to the text file so the program can access it when it is run again after termination.
with open('modification_value.txt','w+') as file:
file.write(str(counter))
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.
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