I know, it's a noob question..
I have these variables:
pgwdth = 30;
mrgn = 0;
fmt = True
And this function:
def Param(x,pgwdth,mrgn,fmt):
parametros = x.split(" ")
if parametros[0][1] == "p":
numerozinho = int(parametros[1])
print "Changing pgwdth"
pgwdth += numerozinho
print pgwdth
elif parametros[0][1] == "m":
numerozinho = int(parametros[1])
print "Changing mrgn"
mrgn += numerozinho
print mrgn
elif parametros[0][1] == "f":
numerozinho = parametros[1]
print "On/Off"
if numerozinho == "on\n":
fmt = True
elif numerozinho == "off\n":
fmt = False
else:
"Error"
print fmt
else:
print "Error"
I just want it to return the variables that it used as arguments after changing it.
return x,pgwdth,mrgn,fmt
Simple as that.
And where you call it:
val1,val2,val3,val = Param(x,pgwdth,mrgn,fmt)
A function returns exactly one result. The trick is to make that result a tuple containing the multiple values.
return (x, pgwdth, mrgn, fmt)
In Python syntax the braces around the tuple are optional so you'll more often see
return x, pgwdth, mrgn, fmt
Which looks like returning multiple values, but now it's clear there is really just one return value
Related
I am trying to create a program that will take two sets of random integers, and print a statement based on the results of those two sets of integers. However, when I call the method, I either receive "None" or an error stating "maximum recursion depth exceeded". I can't seem to figure out how to structure my return statements within these methods so that this works properly.
def genre(a,b):
genreType = random.randint(a,b)
if genreType == '1':
genreType = "Fantasy"
return genre()
elif genreType == '2':
genreType = "Sci-Fi"
return genre()
def medium():
mediumType = random.randint(1,2)
if mediumType == '1':
genre = genre(1,2)
print("Play a " + genre + "game")
return medium()
elif mediumType == '2':
genre = genre(1,2)
print("Watch a " + genre + "anime")
return medium()
First, if a function has a branch without a return, it will return None, e.g.:
def something():
if False:
return "Thing"
# There is no return in "else"
print(something()) # None
Second, comparing numbers to strings never succeeds:
print(1 == 1) # True
print(1 == '1') # False
So the example you've provided can only always return None
Third, you are not returning anything meaningful from your functions:
def genre(a,b):
genreType = random.randint(a,b)
if genreType == '1':
genreType = "Fantasy"
return genre() # call this function again, but with no parameters, why?!
If the condition had a chance of being true, you would be getting
TypeError: genre() missing 2 required positional arguments: 'a' and 'b'
I can only guess that you meant to do this:
if genreType == 1:
genreType = "Fantasy"
return genreType
Or, shorter and arguably more readable:
def genre(a,b):
genreType = random.randint(a,b)
if genreType == 1:
return "Fantasy"
elif genreType == 2:
return "Sci-Fi"
# And you can add your own error to know what exactly went wrong
else:
raise Exception("Genre bounds must be between 1 and 2")
I have been curious about how to simplify my work. But for now, my
problem is how to pass variables through functions and to get this If
statement to work. The variable a and b need to pass into the if
statement to check if the string is in the array 'colors' or
'other_colors'
import random;
hot_spot=0;
colors = ['R','G','B','O','P']
other_colors =['RED','GREEN','BLUE','ORANGE','PURPLE']
guesser_array=[]
def code_maker():
code_maker_array=[]
for i in range(4):
ran = random.randint(0,4)
print (ran)
code_maker_array.append(colors[ran])
print(code_maker_array)
return code_maker_array
x = code_maker()
def code_breaker():
trys = 0;
cbi = input('please put in r,g,b,o,p or red,green,blue,orange,purple_ ')
cbi = cbi.upper()
if ( isinstance(cbi,str) == True):
print ('it is a string')
print (cbi)
for i in range(4):
if (len(cbi)>=3):
a = other_colors[i].find(cbi)
else:
b = colors[i].find(cbi)
if (a >= 0 or b >= 0):
print ('yummmeiabui aebfiahfu dsdsde')
y = code_breaker()
"""
def code_checker(x):
print (x)
code_checker(x)
"""
Try this:
import random
hot_spot=0
colors = ['R','G','B','O','P']
other_colors =['RED','GREEN','BLUE','ORANGE','PURPLE']
guesser_array=[]
def code_maker():
code_maker_array=[]
for i in range(4):
ran = random.randint(0,4)
print (ran)
code_maker_array.append(colors[ran])
print(code_maker_array)
return code_maker_array
x = code_maker()
def code_breaker():
trys = 0;
cbi = input('please put in r,g,b,o,p or red,green,blue,orange,purple_ ')
cbi = cbi.upper()
if ( isinstance(cbi,str) == True):
print ('it is a string')
print (cbi)
for i in range(4):
a=b=0 #This line added
if (len(cbi)>=3):
a = other_colors[i].find(cbi)
else:
b = colors[i].find(cbi)
if (a >= 0 or b >= 0):
print ('yummmeiabui aebfiahfu dsdsde')
y = code_breaker()
"""
def code_checker(x):
print (x)
code_checker(x)
"""
The variables a and b you have defined run out of scope as soon as their respective if blocks end. To prevent this, you can simply define them by initializing them to 0 (or any other value) outside of the if statement.
While Lucefer's answer simplified code a lot, I added this because defining variables in an outer scope like this is and modifying their values later on (in the if blocks in your case) is a very common practice, you might find it helpful somewhere else as well.
remove this whole code segment
for i in range(4):
if (len(cbi)>=3):
a = other_colors[i].find(cbi)
else:
b = colors[i].find(cbi)
if (a >= 0 or b >= 0):
print ('yummmeiabui aebfiahfu dsdsde')
just simply add
if( (cbi in other_colors) or (cbi in colors) ):
print ('yummmeiabui aebfiahfu dsdsde')
Below is the hacker rank code and x is not being mapped to instance args.Can someone please provide me with a reason?https://www.hackerrank.com/challenges/python-lists/problem
if __name__ == '__main__':
N = int(input())
l=[]
for _ in range(N):
line = input().split()
cmd = line[0]
args= line[1:] # <=> here we have 0, 1 or 2 parameters, right?
"""if cmd!= "print":
cmd += "(" + ",".join(args)+")"""
#x = ",".join(map(str,args))
if len(args) == 2:
x, y = map(int, args)
if cmd == "insert":
l.insert(x, y)
elif len(args) == 1:
x = map(int,args)
if cmd == "remove":
l.remove(x)
elif cmd == "append":
l.append(x)
elif cmd == "sort":
l.sorted()
elif cmd == "pop":
l.pop()
elif cmd =="reverse":
l.reverse()
elif cmd == 'print':
print(l)
Your issue is with this line:
x = map(int,args)
This does not work like the line you have in a different branch of your code:
x, y = map(int, args)
The reason is that the first one binds the name x to the map call. It doesn't unpack the map object to get the single value it will yield. For that you'd need:
x, = map(int, args) # note the comma!
But if you know that you have only a single value in args, there's really no need to call map on it at all. Just use x = int(args[0]) instead.
You have couple of issues in your code.
By x = map(int,args) (line 16), x becomes a map object. To obtain integer from this map, first convert it into a list and then use indexing. x = list(map(int,args))[0] will solve your issue. Or you could simply use x = int(args[0]).
list has no sorted function, change l.sorted() to l.sort().
I know this seems like it should be very simple, but at this point I'm at my wit's end trying to figure this out. I've coded up a calculator in python, but for some reason the ending if-else statement is only firing the else segment.
import sys
import re
#setting values
x = 0
n = '+'
y = 0
#valid input flag
valid = True
#continue operations flag
run = True
again = "k"
#addition function
def add(x, y):
return x + y
#subtraction function
def subtract(x, y):
return x - y
#multiplication function
def multiply(x, y):
return x * y
#division function
def divide(x, y):
return x / y
#continuation loop
while run == True:
#Prompt for and accept input
equation = raw_input("Please insert a function in the form of 'operand' 'operator' 'operand' (x + y): ")
equation.strip()
#Divide input into 3 parts by spaces
pieces = re.split('\s+', equation)
#set part 1 = x as float
x = pieces[0]
try:
x = float(x)
except:
print "x must be a number"
valid = False
#set part 2 = operator
if valid == True:
try:
n = pieces[1]
except:
print "Please use valid formating (x [] y)."
valid = False
#set part 3 = y as float
if valid == True:
y = pieces[2]
try:
y = float(y)
except:
print "y must be a number"
valid = False
#If input is valid, do requested calculations
while valid == True:
if n == '+' :
print equation + " =", add(x,y)
elif n == '-' :
print equation, " =", subtract(x,y)
elif n == '*' :
print equation, "*", y, " =", multiply(x,y)
elif n == '/' :
if y == 0:
print "You cannot divide by zero."
else:
print equation, " =", divide(x,y)
else:
print "Please use an appropriate operator ( + - * / )."
#play again
again = raw_input("Play again? ")
print again
if again == ("yes", "y", "YES", "Yes","yes"):
run = True
print "yes'd"
else:
print "no'd"
run = False
When I run this code, I get two different problems:
If I enter a valid input (ie: 2 + 2), then my output is
"2 + 2 = 4.0"
"2 + 2 = 4.0"
"2 + 2 = 4.0"
repeating forever.
If I enter an invalid input, I get the "Play again? " Prompt, but
no matter what I enter, the else statement fires.
(for instance, in the case that I enter "yes" into "Play again? ", it will print:
"yes" (<-- this is from "print again" line )
"no'd" (<-- this is from "else: print "no'd" )
I dont know how to solve either of these problems at this point, so any help would be greatly appreciated.
Edit: Thank you everyone, I wish I could check mark all of you for helping me understand different things about what I did wrong.
In while valid == True:, you never change the value of valid, so it's always True and the loop is infinite. I don't see why it's even a loop - change it to if like the blocks above it and it will behave as expected.
Also, in if again == ("yes", "y", "YES", "Yes","yes"):, change == to in and it will behave as expected.
Perhaps you should replace this code:
while valid == True:
if n == '+' :
print equation + " =", add(x,y)
elif n == '-' :
print equation, " =", subtract(x,y)
elif n == '*' :
print equation, "*", y, " =", multiply(x,y)
elif n == '/' :
if y == 0:
print "You cannot divide by zero."
else:
print equation, " =", divide(x,y)
else:
print "Please use an appropriate operator ( + - * / )."
With this...
if valid:
Or...
while valid == True:
# Insert your previous code here.
break
You could also just simply set valid to false at the bottom of your loop too. That would work.
I think valid is constantly true in this case. You have also written while valid is true, which means it will keep iterating over the loop until valid is equalled to false. It appears that within this block of code in the while loop, valid isn't switched to false.
while valid == True: should probably be if valid == True
and for your second problem:
if again == ("yes", "y", "YES", "Yes","yes"): should probably be:
again = again.lower();
if again == "yes" or again == "y":
Your answer is looping because of
while valid == True:
Replace the loop with the if statement
You get "no'd" because of
if again == ("yes", "y", "YES", "Yes", "yes"):
Here you are equating string with a tuple, instead of checking whether the string is contained within a tuple. Try this instead:
if again in ("yes", "y", "YES", "Yes""):
I keep having this error on my bot program:
start.py:890 local variable 'cmd_part_1' referenced before assignment
Code:
try:
my_alias = message.body.split(" ", 3)
if len(my_alias) > 2:
cmd_part_1 = my_alias[0]
cmd_part_2 = my_alias[1]
elif len(my_alias) < 2:
cmd_part_1 = ""
cmd_part_2 = ""
except Exception as e:
cmd_part_1 = ""
cmd_part_2 = ""
if self.getAccess(user.name.lower()) >= lvl_config.rank_req_callme and cmd_part_1 == "call" and cmd_part_2 == "me":
whole_body = message.body
whole_body = whole_body.replace("call me ", "");
whole_body = whole_body.replace(",", ",");
chat_message("<font color='#%s' face='%s' size='%s'>%s <b>%s</b></font>" % (font_color, font_face, font_size, random.choice(["Recorded! ^_^ I will now call you", "Registah'd, you are now", "Yo, dis mah big homie, I call dem", "Ye-a-a-ah, I guess I can call you that...", "If I have to.. I suppose I'll call you..", "I decided I will call you"]), whole_body), True)
alias_flag = 0
finished_proc = 1
file = open("storage/flatfile/various/aliases.csv", "r")
for line in file.readlines():
alias_data = line.strip()
alias_username, alias_nickname = alias_data.split(",", 1)
Error Line:
if self.getAccess(user.name.lower()) >= lvl_config.rank_req_callme and cmd_part_1 == "call" and cmd_part_2 == "me":
What am I doing wrong?
You have if and elif statements in the first try block that set cmd_part_1.
What happens if none of the conditions in these if statements is True?
In that case, cmd_part_1 will never be assigned a value. This is what is going on in your code. Fix this and it will work. Maybe add an else clause there and assign a default value to both cmd_part_1 and cmd_part_2. Or make one of them have an =.
For example:
if len(my_alias) >= 2:
instead of:
if len(my_alias) > 2:
After that, as eryksun suggested in the comment below, you can replace the elif with an else.