I want to pass a dictionary between two functions, but how to do this without using a global variable?
I'm trying to pass the dictionary that is in my "fileProcessing" function into the "swappingKandV_PrintingResults" function without having a global variable being modified.
dictionary = dict()
fileinputname = input("Please Input File Name: ")
try:
filehandling = open(fileinputname)
except:
print("Invalid Entry")
quit()
rawfile = filehandling.readlines()
def fileProcessing(rawfile):
for iteration in(range(len(rawfile))):
rawfile[iteration] = rawfile[iteration].lower()
for line in rawfile:
line.rstrip()
line.split()
for words in line:
letter = words.split()
for iteration in letter:
if iteration.isalpha() :
dictionary[iteration] = dictionary.get(iteration, 0) + 1
def swappingKandV_PrintingResults(dictionary):
finalresults = []
for (k,v) in dictionary.items():
newtuple = (v, k)
finalresults.append(newtuple)
finalresults = sorted(finalresults, reverse=True)
for iteration in finalresults:
print(iteration)
fileProcessing(rawfile)
swappingKandV_PrintingResults(dictionary)
By making the first function create and return the dictionary. Then pass that returned dictionary to the second function.
fileinputname = input("Please Input File Name: ")
try:
filehandling = open(fileinputname)
except:
print("Invalid Entry")
quit()
rawfile = filehandling.readlines()
def fileProcessing(rawfile):
dictionary = {}
for iteration in(range(len(rawfile))):
rawfile[iteration] = rawfile[iteration].lower()
for line in rawfile:
line.rstrip()
line.split()
for words in line:
letter = words.split()
for iteration in letter:
if iteration.isalpha() :
dictionary[iteration] = dictionary.get(iteration, 0) + 1
return dictionary
def swappingKandV_PrintingResults(dictionary):
finalresults = []
for (k,v) in dictionary.items():
newtuple = (v, k)
finalresults.append(newtuple)
finalresults = sorted(finalresults, reverse=True)
for iteration in finalresults:
print(iteration)
swappingKandV_PrintingResults(fileProcessing(rawfile))
From the way you phrased the question, it seems you have some confusion on how to work with passing arguments to functions and how to handle scope. I would suggest having at look at what a variable is in Python to begin with and then what passing it to a function means.
You can accomplish this task in 2 ways:
1. Nested Function Call :
If you want to necessarily call 2nd function after 1st, just write -
'swappingKandV_PrintingResults(dictionary)' as the ending line in the fileProcessing function.
2. Accepting Return from 1st and Passing as Argument to 2nd :
As insisted by #Reti43 too, just write -
'return dictionary' as the ending line in the fileProcessing function and replace your last 2 lines of code by -
Dict = fileProcessing(rawfile)
swappingKandV_PrintingResults(Dict)
Related
I want to use a dictionary to call functions with arguments, ie this simple program. I'm a very novice coder in python. what am I doing wrong?
output:
what name? : s
what name? : f
f
s
want to write or read? w/r:
w
want singers or band members? s/b:
s
1
code:
def addToFile(filename, lineString):
file = open(filename,"a")
file.write(lineString + "\n")
file.close()
return 1
def readFile(filename):
file = open(filename)
for line in file:
print(line)
file.close()
return 2
whatToDo = {
"ws": addToFile("band.txt",input("what name? : ")),
"wb": addToFile("singers.txt",input("what name? : ")),
"rs": readFile("singers.txt"),
"rb": readFile("band.txt")
}
def promptWrite():
print("want to write or read? w/r: ")
choice = str(input())
print("want singers or band members? s/b: ")
choice += str(input())
val = whatToDo[choice]
print(val)
promptWrite()
I didn't know If I needed to have a value or something, so I put the returns in the functions and had val. That isn't nessisary, I just drafted this up as an example program.
I know that you can have a dictionary with the names of the functions and call
dictionaryName[whateverthing]() to run the function, but I don't know how to have the arguments vary in that
You're calling the functions when you create the dictionary, not when you access the dictionary. Use lambda to create anonymous functions, then add () when you fetch from the dictionary to call it.
def addToFile(filename, lineString):
file = open(filename,"a")
file.write(lineString + "\n")
file.close()
return 1
def readFile(filename):
file = open(filename)
for line in file:
print(line)
file.close()
return 2
whatToDo = {
"ws": lambda: addToFile("band.txt",input("what name? : ")),
"wb": lambda: addToFile("singers.txt",input("what name? : ")),
"rs": lambda: readFile("singers.txt"),
"rb": lambda: readFile("band.txt")
}
def promptWrite():
print("want to write or read? w/r: ")
choice = input()
print("want singers or band members? s/b: ")
choice += input()
val = whatToDo[choice]()
print(val)
promptWrite()
You can't set functions with parameters to be executed in a dictionary, but you can store functions to call them after, with the corresponding dict key and parenthesis. Example:
my_dict['write_output'] = print
my_dict['write_output']('hello from my key')
IMHO, storing your functions in dict keys is a design incosistency. Dicts are mutable objects, then someone could overwrite your keys without any restriction and mess up your code everywhere. Not a good idea at all.
EOF error is occurring in this step method, val = input().split(' ') value error occurs when I remove the try block
from collections import deque
n = int(input())
d = deque()
for _ in range(n):
try:
method, val = input().split(' ')
if method == 'append':
d.append(val)
if method == 'appendleft':
d.appendleft(val)
except ValueError:
a = input()
if str(a) == 'pop':
d.pop()
else:
d.popleft()
print(d)
Input given is :
6
append 1
append 2
append 3
appendleft 4
pop
popleft
You have problem because you use input() inside except so in one loop it reads two lines - first in try and next in except - so finally you have less lines.
Error ValueError is raised by method, val = ... which is executed after input() - so this line is already removed from buffer and you have less lines in buffer. And when you runs next input() in except then it doesn't read the same line but next line - so you get too many lines in one loop.
You should first read line and assign to single variable and later you should try to split it into two variables.
line = input()
try:
method, val = line.split(' ')
# ... code ...
except ValueError:
method = line
# ... code ...
Instead of try/except you could first split line and assing to single variable
#args = input().strip().lower().split(' ')
args = input().split(' ')
and later check len(args)
args = input().strip().lower().split(' ')
if len(args) == 2:
method = args[0]
val = args[1]
# ... code ...
elif len(args) == 1:
method = args[0]
# ... code ...
else:
print('Wrong number of arguments')
I have been working on this code for a couple of hours now, and I am rather unsure what the problem is.
import random#imports random
import os#Imports os
print("Welcome to the maths quiz") # Welcomes user to quiz
score = (0)
def details():
plr_name = input ("Please Input Name:") # Asks user for name
plr_class = input("Input class number: ") # Asks the user for class numer
return (plr_name, plr_class)
def Q():
while qno < 10: # loops while qno is under 10
ran_num1 = random.randint(1,99) # Generates the first random number
ran_num2 = random.randint(1,99) # Generates the second random number
ran_fun = random.choice("X-+") # Picks a random function
print(ran_num1,ran_fun,ran_num2,"=") # Prints the Sum for the user
if ran_fun == "X":
sum_ans = ran_num1 * ran_num2 # Does the sum if it is a multiplication
if ran_fun == "+":
sum_ans = ran_num1 + ran_num2 # Does the sum if it is a addition
if ran_fun == "-":
sum_ans = ran_num1 - ran_num2 # Does the sum if it is a subtraction
plr_ans = int(input()) # Gets the user's answer
if plr_ans == sum_ans:
print("Correct!") # Prints correct
score = score + 1 # Adds 1 to score
else:
print("Incorrect!")
qno = qno + 1 # Adds 1 to qno
def plr_list_make(lines, listoreder):
index = 0
plr_names =[]
plr_scores =[]
for line in lines:
if listorder == 1:
column =0
rev = False
else:
column = 1
rev = True
return sorted(zip(plr_names, plr_scores),key = lambda x:(x[column]),reverse = rev)
def fileUP(plr_name, score, line ):
found = False
index = 0
for line in lines:
if line.startswith(plr_name):
line = line.strip("\n") + ","+str(score+"\n")
lines[index] = line
found = True
index = index + 1
if not found:
lines.append(plr_name+"|" +str(score)+"\n")
return lines
def save (plr_name, plr_class, score):
filename = "QuizScore_"+plr_class+".txt"
try:
fileI = open(filename)
except IOError:
fileI = open(filename, "w+")
fileI = open(filename)
lines = fileI.readlines()
fileI.close
lines = FileUP(plr_name, score, lines)
fileO = open(filename, "w")
fileO.writelines(lines)
fileO.close
def disp_list(): ## intialise_list
student_list=[]
filename = "QuizScore_"+plr_class+".txt"
try:
## open file read into list "lines"
input_file = open(filename)
lines = input_file.readlines() ## read file into list "lines"
input_file.close
student_list = create_student_list(lines, listorder) ### update "lines" with student list as requested by user
## output sorted list
for counter in range(len(student_list)):
print ("Name and Score: ", student_list[counter][0], student_list[counter][1])
except IOError:
print ("no class file!!!")
def menu():
print ("1 Test")
print ("2 Alphabetical")
print ("3 Highscore")
print ("4 Avg Score")
def Run():
selection = 0
while selection != 5:
menu()
option = int(input("Please select option: "))
if option == 1:
name, plr_class = details()
save(name, plr_class, Q())
else:
plr_class = input("input class ")
disp_list(plr_class, option-1)
Run()
Errors:
Traceback (most recent call last):
File "C:\Users\user\Documents\CharlieStockham\cgsca\ca2.py", line 117, in
Run()
File "C:\Users\user\Documents\CharlieStockham\cgsca\ca2.py", line 113, in Run
save(name, plr_class, Q())
File "C:\Users\user\Documents\CharlieStockham\cgsca\ca2.py", line 74, in save
lines = FileUP(plr_name, score, lines)
NameError: global name 'FileUP' is not defined
Line 110:
name, plr_class = details()
But the details function does not return anything - so Python tries to assign the default return value None to the tuple name, plr_class. It can't do this, because None is not an iterable (you can't assign two things to it). To fix it, add the following line to your details function:
return (plr_name, plr_class)
(I haven't tested this.)
I like your game but it's buggy as a mofo :P
score and qno aren't properly defined. Define them in the functions that need them, define them globally or pass them to the relevant functions as arguments.
details() doesn't return anything but you still attempt to use its output to define two other variables. Add return (plr_name, plr_class) to details()
Every time you cast user input to int without checking its value, your program will crash if an int can't be cast. This applies here:
option = int(input("Please select option: "))
here
plr_ans = int(input())#Gets the user's answer
and elsewhere.
Since your program is input-heavy you could make a a function to which you pass the expected datatype and an optional string to display to the user. This way you wouldn't have to write try/except 10 times and your program wouldn't crash on unexpected input.
In def fileUP(plr_name, score, line ): you have for line in lines: but lines isn't defined. Thus, the save() function that calls FileUP() also fails. Also, FileUP and fileUP are not the same thing. You call the function with a capital "f" but the defintion of the function calls it fileUP with a lower case "f".
While we're at it, the file handling in def save (plr_name, plr_class, score):looks weird. The standard way of opening files for simple reading and writing in Python is via with open().
disp_list() should take one or two arguments but it doesn't at the moment so this error is raised:
TypeError: disp_list() takes 0 positional arguments but 2 were given
These 2 positional arguments were given here:
disp_list(plr_class, option-1)
Ok so I am completely lost for this problem, please help me. I have already created a function that takes in a text file and sorts all the names into the text file, puts them in a dictionary. So my new dictionary looks like this:
namesDict = {'J': ['Jacob', 'Joshua'], 'T': ['Tyler'], 'A': ['Austin'], 'B': ['Brandon'], 'D': ['Daniel'], 'M': ['Michael', 'Matthew'], 'C': ['Christopher'], 'N': ['Nicholas']}
now I have to take in this dictionary I created and add new names. The new function has to do this
The function will ask the user to input their name. Assume the user will enter names with a capital first letter, and all lowercase letters after that.
If their name is already in the dictionary, print “[name] is already in the dictionary”, and then return the same dictionary.
If their name is not already in the dictionary, then you will add their name to the dictionary under the appropriate key, print “[name] added to dictionary”, and then return the updated dictionary.
If their name is not already in the dictionary AND the first letter of their name is not already a key in the dictionary, then you will add the first letter of their name as a key, with a list containing their name as the value. You will then print “[name] added to dictionary”, and return the updated dictionary.
so I have this so far which of course is not complete:
def updateDictionary(namesDict):
newname= input('What is your name?')
if newname = key:
print(newname'is already in the dictionary')
elif newname != key:
print (newname 'added to dictionary')
elif newname = key[0]:
print (newname 'added to dictionary')
also my first code to create the dictionary from the text file is this:
def newDictionary():
names={}
file = open('file.txt','r')
lines = file.read().split('\n')
if len(lines) == 1 and len(lines[0]) == 0:
print('empty file')
else:
for line in lines:
if line in names:
names[(line[0])].append(line)
else:
names[(line[0])] = [line,]
return names
but i am having an error in this code which says names[(line[0])] = [line,]
IndexError: string index out of range.
PLEASE PLEASE help me out. I don't know how to take in the new input name and put it in the dictionary.
Thank you
If you are getting IndexError for this line:
[(line[0])] = [line,]
it means that there is no first (line[0]) character in the line - in other words, the line is blank. So you need to ignore blank lines
updating the dictionary can be done as follows:
def updateDictionary(namesDict):
newname = input('What is your name?')
key = newname[0]
if key not in namesDict:
namesDict[key] = []
item = namesDict[key]
if newname in item:
print(newname, 'is already in the dictionary')
else:
item.append(newname)
print(newname, 'added to dictionary')
return namesDict
Problem:
Your newDictionary() cannot produce the dictionary because probably there is an empty line in your file.
Solution:
collections.defaultdict will make things easier:
from collections import defaultdict
def newDictionary():
names = defaultdict(list)
with open('file.txt','r') as f:
for line in f:
line = line.strip()
if line:
names[line[0]].append(line)
return names
I have a starting file which has values on each line separated by a comma, like so:
hello,welcome
hi, howareyou
hola,comoestas
I want to take those words and put them into a dictionary so they are key/value pairs. Then i am trying to ask for a key and return the corresponding value. I believe i am close so any help would be appreciated. Also i am a beginner so simple code is best.
def CreateDictionary():
WordDictionary = open('file.csv', 'r')
for line in WordDictionary:
mylist = line.split(',')
return(mylist)
def main():
cd = CreateDictionary()
text=input('input text:')
for x in cd.values():
if x == text:
word=cd[x]
print(word)
main()
def makeDict(infilepath):
answer = {}
with open(infilepath) as infile:
for line in infile:
key,val = line.strip().split(',')
answer[key] = val
return answer
def main(infilepath):
cd = makeDict(infilepath)
key = input('input text: ')
if key in cd:
print(cd[key])
else:
print("'%s' is not a known word" %key)
Here's a way you could edit your solution to create a dictionary.
def CreateDictionary():
ret_dict = {}
with open('file.csv', 'r') as WordDictionary:
for line in WordDictionary:
parts = line.split(',')
ret_dict[parts[0]] = parts[1]
return ret_dict
def main():
cd = CreateDictionary()
text = raw_input('input text:')
word = cd[text]
print word
main()
A main issue with your approach is that you have return inside of a for loop. The function will return after the first loop iteration and will not continue beyond the first line of the file.