Not returning return statement - python

I just posted a question about this code, and I am sorry to do it again, but my return statement is not working. Whenever I try to run the code, it asks for a global variable of position, which I am trying to return in the searching method. Any help is appreciated. Thanks.
def main():
names = ['Ava Fischer', 'Bob White', 'Chris Rich', 'Danielle Porter','Gordon Pike', 'Hannah Beauregard', 'Matt Hoyle', 'Ross Harrison', 'Sasha Ricci', 'Xavier Adams']
binarySearch(names, "Ava Fischer")
print("That name is at position "+str(position))
def binarySearch(array, searchedValue):
begin = 0
end = len(array) - 1
position = -1
found = False
while not found and begin<=end:
middle=(begin+end)//2
if array[middle] == searchedValue:
found=True
position = middle
elif array[middle] >searchedValue:
end = middle-1
else:
first = middle+1
return position

At the moment you are calling your function, but just throwing the result away. You don't actually give a value from your function call (you use return just fine):
You want something like:
position = binarySearch(names, "Ava Fischer")
The variable that you are expecting to exist globally is local to the scope of binarySearch. We can get it by assigning a variable to the returned value, like above.

This is a scope issue. In the function binarySearch you are declaring a local variable position, so it is only accessible within that function. Since that function will return a value, you can assign that result to a variable:
position = binarySearch(names, "Ava Fischer")
print("That name is at position " + str(position))

Related

How do I add a prefix/suffix to any given string in python?

"Your task is to write a function that adds a prefix or suffix to a person's name. The name of your function should match exactly as shown below, including cases (all lowercase")
def fix_names(name, position, added_phrase):
name = ''
added_phrase = ''
position = "prefix" or "suffix"
if (position == "prefix"):
prefix = added_phrase
print (added_phrase+name)
elif (position == "suffix"):
suffix = added_phrase
print(name+added_phrase)
return(fix_names)
fix_names("John", "prefix", "Dr.")
This is my code, but when I run it, I don't receive any output. Any tips/suggestions to make it work? Thank you
The name, added_phrase, etc. are coming into the function as variables. But, you are setting them to blanks, which is why you are not seeing any output for print. Also, the return should have the newname you want to send back to the main function, not fix names. Updated code here...
def fix_names(name, position, added_phrase):
# name = ''
# added_phrase = ''
# position = "prefix" or "suffix"
if (position == "prefix"):
prefix = added_phrase
print (added_phrase+' '+name)
newname=added_phrase+' '+name
elif (position == "suffix"):
suffix = added_phrase
print(name+' '+added_phrase)
newname=name+' '+added_phrase
return(newname)
variable = fix_names("John", "prefix", "Dr.")
## Do something else with the new name....
In your function definition, you are overwriting the value of the parameters
name = ''
added_phrase = ''
position = "prefix" or "suffix"
Here is the working code
def fix_names(name, position, added_phrase):
fix_name = added_phrase + name if position == "prefix" else name + added_phrase
return fix_name
op = fix_names("John", "prefix", "Dr.")
print(op)
Argument passed were overwritten with blank string in your function, and some variables are not used or redundant, also your return value should be your print function or does not need a return value if you're printing directly from function.
def fix_names(name, position, added_phrase):
if position == "prefix":
return f'{added_phrase} {name}'
elif position == "suffix":
return f'{name} {added_phrase}'
print(fix_names("John", "suffix", "Dr."))
Or:
def fix_names(name, position, added_phrase):
if position == "prefix":
print(f'{added_phrase} {name}')
elif position == "suffix":
print(f'{name} {added_phrase}')
fix_names("John", "suffix", "Dr.")
This might not answer the question exactly, since I don't understand it fully, but it could have something to do with you setting the "name" and "added_phrase" arguments to blank at the start of the function, defeating the purpose of having them. Also, make sure not to have a space between functions and brackets, as this is a syntax error.
EDIT: Also, as said in the comments, "position = 'prefix' or 'suffix'" isn't a valid line, and isn't needed. You are already defining position with the argument, so you wouldn't need this even if it worked.
Also, try to make your questions clearer on what you're trying to do so people can help you efficiently, and try to do research before asking a question on here.
Example of fixed code:
def fix_names(name, position, added_phrase):
if (position == "prefix"):
prefix = added_phrase
print(added_phrase+name)
elif (position == "suffix"):
suffix = added_phrase
print(name+added_phrase)
fix_names("John", "prefix", "Dr.")

Menu for a turn based game

Our teacher has assigned us an assignment for doing a turned based game.
This only included name.strip() but this does not prompt player to input unique name:
def start():
print("\nNew game started...Setting up Player 1's team...\n")
for total_characters in range (1,4):
name = input('Enter a unique name for unit #'+str(total_characters)+'==> ')
if not name.strip():
print('Cant be blank name,please provide a unique name')
return start()
else:
role_selection()
def role_selection():
for total_characters in range (1):
role = input('Select unit #'+str(total_characters)+' type: (W)arrior, (T)anker, or Wi(Z)ard ==> ')
total_characters+=1
if role.upper() == 'W':
pass
elif role.upper() == 'T':
pass
elif role.upper() == 'Z':
pass
else:
print("I don't understand what are you typing.")
return role_selection()
There are things that doesn't make sense :
You have the exact same function twice :
def set_up(team_size)
def set_up(name)
You are doing :
for total_units in range(team_size):
[...]
invalid = True
[...]
while invalid: # Infinite loop
set_up() # What's this function ?
As you can see from the comments in the code above, you never set invalid to False, leading to the infinite loop.
Note: My recommendation is that you should check out some tutorial on python before moving on coding a complex project, because your homework is not that easy.
Edit :
From the new code you've posted, you could do something like this :
def new_game():
names = []
for unit_id in range(1,4):
print(f'Enter a unique name for unit #{unit_id} ->')
empty = True
while empty:
name = input('>')
if name == "":
continue
empty = False
if name in names:
print('Unit name must be unique.')
else:
print('Name looks good!')
names.append(name)
python menu
At first glance, this stood out to me:
if not name.strip():
print('Unit name could not be blank.')
invalid = True
Remember in python the indentation matters. You are setting invalid to True regardless of the if condition. Further down you have a while loop that checks it.
The other if conditions have invalid=True inside the condition. Plus you don't have invalid=False anywhere as far as I see, so you'll get an error if you don't declare it somewhere so it's always on the path before the while.
this doesn't seem like a specific problem, more an ask for general guidance for going about this kind of problem?
One thing to note is that your above script only uses functions (which store behaviour) whilst really for something like the turn based game, you need to store behaviour (attacks etc) and information (how much health is left etc).
I won't write the script for you, but here's an example of how you might define an rpg like entity, capable of attacking, being attacked by another entity etc:
class Entity:
"""Abstract class for any combat creature"""
def __init__(self, name, health):
self.name = name
self.health = health
self.is_alive = True
def attack(self, other):
dmg = random.randint(7, 12)
other.be_attacked(dmg)
def be_attacked(self, dmg):
self.health = self.health - dmg
if self.health <= 0:
self.die()
def die(self):
self.is_alive = False
def check_life(self):
return self.is_alive
You can then initialise a bunch of these to make up the 'team' you where talking about:
one_person = Entity('Lee', 34)
another_person = Entity('Someone Else', 21)
etc. Hope that helps a bit. Good luck with your project and have fun!

Python - UnboundLocalError: local variable "ID" referenced before assignment

Id, conf = recognizer.predict(gray[y:y+h,x:x+w]
def hour(cn):
for z in range(9,17):
if now.hour == z:
worksheet(cn, str(z)+":00")
def identify(number):
sht = gc.open("Test")
wks3 = sht.worksheet("NAMES")
b = wks3.acell('B'+str(number)).value
a = wks3.acell('A'+str(number)).value
if(Id == a and conf<65):
print(Id, conf)
Id = str(b)
Time = time.ctime()
hour(number)
elif(conf>64):
print(conf)
Id = "Unknown"
for m in range(2,100):
identify(m)
The above code is being used for facial recognition, I copied what I felt was necessary, it is not the entire code.
I'm trying create a function which I want to call back in a for loop
What am I doing wrong? I've been looking t this for 6 hours now, and anything I try doesn't seem to work.
I get a message back saying "UnboundLocalError: local variable 'Id' referenced before assignment"
It's impossible because I'm assigning with:
a = wks3.acell('A'+str(number)).value
So it grabs the ID number from the google spread sheet and checks if it is equaled to that, can someone tell me where I'm going wrong here?
def identify(number):
sht = gc.open("Test")
wks3 = sht.worksheet("NAMES")
b = wks3.acell('B'+str(number)).value
a = wks3.acell('A'+str(number)).value
#because you did, Id = ?
if(Id == a and conf<65):
print(Id, conf)
Id = str(b)
Time = time.ctime()
hour(number)
elif(conf>64):
print(conf)
Id = "Unknown"
Because you did, variable Id isn't passed as any parameter or global/local variable or as an argument to existing class.
If Id was parameter:
def identify(number,Id):
If Id was global variable:
def identify(number):
global Id
If Id was local variable:
def identify(number):
id = None # or some other data type
And if Id was argument from some class:
some_class.Id
In short you referenced Id before it was initialised. This is rookie mistake and there is some stuff where you can actually init a variable in if elif else statement but you need to trow a none of above logic of the rule.
if True: Id = 2; elif False: Id = 3; else: Id =0 #this is pseudocode, don't paste it in.
Also have in mind that next variable is also Unbound conf
EDIT:
Often to avoid this problem we write code like this:
def somefunction(parm1,parm2... ):
# global variables : description for variable stack is optional
global var1,var2 # if needed
#local variables
var3,var4 = None;
var5 = 'something else'
#in body functions : functions inside functions or just general program functions
def a(... ): return ...
#body : actually what function/program does.
# returning , finishing statement.

Initialize function variable once & change variable value when function is called

Language: Python
I want the value of a variable to be initialized to zero at the start of the execution. This variable is used in a function & its value may also get changed within the function. But I do not want the value of this variable to reset to zero whenever a function call is made. Instead, its value should be equal to the updated value from its previous function call.
Example:
get_current() is constantly returning a different value when it is called.
ctemp is initially zero.
In the first function call get_current_difference() will return cdiff & then update the value of ctemp such that ctemp = current.
In the second function call, the value of ctemp should not be zero. Instead, it should be equal to the updated value from the first function call.
import serial
arduino = serial.Serial('/dev/ttyACM1',9600)
ctemp = 0
def get_current():
line = arduino.readline()
string = line.replace('\r\n','')
return string
def get_current_difference():
global ctemp
current = get_current()
cdiff = float(current) - ctemp
return cdiff
ctemp = current
while 1:
current = get_current_difference()
print(current)
You return before setting value of ctemp
return cdiff
ctemp = current
must become
ctemp = current
return cdiff
You are describing mutable state and a function to modify it, which is what classes are for.
class Temperature:
def __init__(self, arduino):
self.ctemp = 0
self.arduino = arduino
def current(self):
line = self.arduino.readline()
return line.replace('\r\n', '')
def difference(self):
current = self.current()
cdiff = float(current) - self.ctemp
self.ctemp = current
return cdiff
t = Tempurature(serial.Serial('/dev/ttyACM1', 9600)
while True:
print(t.difference())
Using a class scales if, for example, you have multiple temperature monitors to work with.

Python alter external variable from within function

When I run this it works, but it says
"name 'select_place' is assigned to before global declaration"
When I get rid of the second global, no comment appears, but as select_place is no longer global it is not readable (if selected) in my last line of code.
I'm really new to python, ideally I'd like a way of not using the global command but after searching i still can't find anything that helps.
My code:
def attempt(x):
if location =='a':
global select_place
select_place = 0
if location =='b'
global select_place
select_place = 1
place = ([a,b,c,d])
This is the start of some turtle graphics
def Draw_piece_a(Top_right):
goto(place[select_place])
You need to declare the variable first, additionally the function code can be made clearer:
select_place = False
def attempt(x):
global select_place
if location == 'a':
select_place = 0
elif location == 'b':
select_place = 1
Also, there is no return value for attempt(), is this what you want?

Categories