how to denote function arguments in python [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I need to print following info using unnecessary argument (track):
def make_album(singer, album, track = ''):
album = {'singer_name' : singer, 'slbum' : album}
if track:
album['track'] = track
return album
output = make_album('Linkin Park', 'October')
print(output)
output = make_album('Lara Fabian', 'Ju\'tem', 13)
print(output)
output = make_album('Space Girls', 'Viva')
print(output)
But the output is kind of
None
{'singer_name': 'Lara Fabian', 'slbum': "Ju'tem", 'track': 13}
None
How to denote args to avoid none output

you have a return in your function only if your track argument is not an empty string otherwise your function returns None to fix you can use:
def make_album(singer, album, track = ''):
album = {'singer_name' : singer, 'slbum' : album}
if track:
album['track'] = track
return album

Related

Convert text file into dictionary [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I want to turn a txt file with this format:
valido;válido
invalidos;inválidos
avaliacao;avaliação
nao e;não é
into this with Python:
{'valido': 'válido', 'nao e': 'não é', 'invalidos': 'inválidos', 'avaliacao': 'avaliação'}
My code so far:
final = []
with open("fich_teste.txt", 'r') as file:
for line in file:
key; value = linha.sprit().split(';')
final[key] = value
return final
This returns an error:
builtins.NameError: global name 'key' is not defined
You need to assign values using key, value not key; value and fix some indentation problems along with the final declaration and method name:
def myFunc():
final = {}
with open("fich_teste.txt", 'r') as file:
for line in file:
key, value = line.strip().split(';')
final[key] = value
return final

Invalid syntaxt sum(list) >= 2 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I get an invalid syntax error at:
if sum(severe_symptoms_list) >= 2
I have set the values for the severe and moderate symptoms slots to True and False depending on what answer was given by the user to a YES/NO question. What have i done wrong ?
class ActionHowManySymptoms(Action):
def name(self) -> Text:
return "action_how_many_symptoms"
def run (self, dispatcher, tracker, domain):
severe_symptom1 = tracker.get_slot('severe_symptom_one')
severe_symptom2 = tracker.get_slot('severe_symptom_two')
severe_symptom3 = tracker.get_slot('severe_symptom_three')
severe_symptom4 = tracker.get_slot('severe_symptom_four')
moderate_symptom1 = tracker.get_slot('moderate_symptom_one')
moderate_symptom2 = tracker.get_slot('moderate_symptom_two')
moderate_symptom3 = tracker.get_slot('moderate_symptom_three')
moderate_symptom4 = tracker.get_slot('moderate_symptom_four')
severe_symptoms_list = [severe_symptom1, severe_symptom2, severe_symptom3, severe_symptom4]
moderate_symptoms_list = [moderate_symptom1, moderate_symptom2, moderate_symptom3, moderate_symptom4]
True = 1
if sum(severe_symptoms_list) >= 2
dispatcher.utter_response(response="utter_some_severe_symptoms", tracker)
elif sum(severe_symptoms_list) == 1
dispatcher.utter_response(response="utter_one_severe_symptoms", tracker)
else:
dispatcher.utter_response(response="utter_no_severe_symptoms", tracker)
if sum(moderate_symptoms_list) >= 2
dispatcher.utter_message(response="utter_some_moderate_symptoms")
elif sum(moderate_symptoms_list) == 1
dispatcher.utter_message(response="utter_one_moderate_symptoms")
else:
dispatcher.utter_message(response="utter_no_moderate_symptoms")
return[]
Try to code in a more decent presentable manner. It will help you in the long run
if (sum(severe_symptoms_list) >= 2):

Python 3 returning dictionary from a function case [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have python function that should return diction:
def load_cred(FILE):
key_for_enc = getpass(prompt='Key for encrypted credentials file: ', stream=None)
cipher = AESCipher(key_for_enc)
crd_dict={}
with open(FILE, 'r') as fh:
for line in fh:
dec_line = cipher.decrypt(line)
# print("line: {}".format(dec_line))
dec_line.strip()
start_string, user, password = dec_line.split(10*'|')
crd_dict[start_string] = (user, password)
#print("1: {} 2: {} 3: {}".format(start_string,user,password))
print("crd diction: {}".format(crd_dict))
return crd_dict
but when I call it from other script like that:
Data_cred = load_cred(CRED_FILE)
print ("Data type: {}".format(type(Data_cred)))
print("Data: ".format(Data_cred))
The returned dictionary don't appear as a returned value... Could anybody help me with this? Notice that within the function load_cred , crd_dict have it's items.. but outside it doesn't. I still don't get it why..
Key for encrypted credentials file:
crd diction: {'first_line': ('User1', 'Pass1')}
Data type: <class 'dict'>
Data len:
Data:
The function load_cred() is returning the dictionary. You just forgot to add the replacement field in the last line when printing it. -
print("Data: {}".format(Data_cred))

python oop classes, syntax error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
The following is giving me a syntax error at (def__init__(self, price, max_speed, total_miles_ridden, initial_miles = 0):)
I'm also wondering if I can concatenate like this: self.total_miles_ridden + 10?
^:
class Bike(object):
def__init__(self, price, max_speed, total_miles_ridden, initial_miles = 0):
self.price = price
self.max_speed = max_speed
self.total_miles_ridden = total_miles_ridden
self.initial_miles = initial_miles
def displayinfo(self):
print("The price is ", self.price)
print("This bike's max speed is ", self.max_speed)
print("The total miles is ", self.total_miles_ridden)
def ride(self):
print("Riding ", self.total_miles_ridden + 10) #add 10miles to total
def reverse(self):
print("Reversing " self.total_miles_ridden - 5) #minus 5 miles from total
bike1 = new Bike(200, '25mph')
print bike1
I think you're missing a space between def and init.

Python type showing instance before return but none after [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have a function used to build a tree from a set of nodes
def buildTree(self, nodeList,):
if len(nodeList) > 1:
nodeList = sorted(nodeList, key=self.getKey)
newNode = self.makeNode(nodeList[0], nodeList[1])
nodeList.pop(0)
nodeList.pop(0)
nodeList.append(newNode)
nodeList = self.buildTree(nodeList)
else:
print type(nodeList[0])
return nodeList[0]
This outputs type 'instance'
from TreeFactory import TreeFactory
nodeList = builder.buildNodeList(
'the quick brown fox jumped over the lazy dog')
nodeHead = builder.buildTree(nodeList)
print type(nodeHead)
When I print the type of the return from the builder, I get "type 'NoneType'" printed out
So why is it a valid instance before the return, but not after?
As per https://stackoverflow.com/users/367273/npe the issue was that the if branch was returning nothing, so the recursion was causing nodeList to be filled with None values. By changing the buildTree function so that it reads as
def buildTree(self, nodeList,):
if len(nodeList) > 1:
nodeList = sorted(nodeList, key=self.getKey)
newNode = self.makeNode(nodeList[0], nodeList[1])
nodeList.pop(0)
nodeList.pop(0)
nodeList.append(newNode)
nodeList = self.buildTree(nodeList)
return nodeList
else:
return nodeList[0]
fixed the issue.

Categories