Cannot get this code to work, simple Python else if statement - python

When I run the code below I keep getting a syntax error and it is highlighted where shown.
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5
sf_area = (int(sf_area))
rio_area = (int(rio_area))
def x= sf_population/sf_area
def y= rio_population/rio_area
if x<y:
print"True"
if x>y:
print"False"

Working example:
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5
sf_area = int(sf_area)
rio_area = int(rio_area)
x = sf_population/sf_area
y = rio_population/rio_area
if x < y:
print"True"
if x > y:
print"False"

def is used in python to define functions, not variables. To set the value of x to sf_population/sf_area simply drop the def in lines 5 and 6.

sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5
sf_area = (int(sf_area))
rio_area = (int(rio_area))
x = sf_population/sf_area
y = rio_population/rio_area
if x<y:
print "True"
if x>y:
print "False"
Unless you want to define a function, there is no need for def
Beside of this, consider using elif for the second condition
if x<y:
print "True"
elif x>y:
print "False"

Related

How to pass some initial value in the first iteration of the loop and then pass the derived values in the subsequent iterations in python?

initial_state = 40
def funct_1(x):
return y
def funct_2(y):
return z
def main():
funct_1(x)
funct_2(y)
for i in range(10):
main()
In the first iteration, I want input to funct1 i.e. x = initial_state and from the second iteration onwards, I want output of funct_2 i.e. z becomes input to funct_1. Please let me know how can I implement this in python.
Straightforward way is following:
def funct_1(x):
y = x + 1
return y
def funct_2(y):
z = y + 1
return z
def main(x):
y = funct_1(x)
z = funct_2(y)
return z
state = 40
for i in range(10):
state = main(state)
This should work: In the first iteration you have your default value of x and in all iterations after that x is the output of funct_2().
x = init_state
def main():
y = funct_1(x)
x = funct_2(y)
for i in range(10):
main()
Normally, this should work:
initial_state = 40
def funct_1(x):
return y
def funct_2(y):
return z
def main():
for i in range(10):
if i == 1:
funct_1(x)
else:
funct_2(y)
if __name__ == '__main__':
main()

Store function ouput if output isnt false (in a single call)

Is there a way to store the output of the function but only if it isnt false, and not having to call the function 2 times as in the example?
def example(x):
if x>=5:
return "great"
else:
return False
def main():
x = 5
if example(x):
asnwer = example(x)
else:
print("x<5")
main()
If your Python interpreter version 3.8 or greater, you can use Assignment Expresions
import random
def example():
return random.randint(0, 10)
if (result := example()) >= 5:
print(result)
else:
print("x < 5")
def main():
x = 5
result = example(x)
asnwer = result if result else print("x<5")
You could also just modify the function:
def example(x):
return "Great" if x>=5 else print("x<5")
def main():
x = 5
asnwer = example(x)
main()
This would give asnwer == None when x<5 and asnwer == Great when x>=5.

How do You change a variable to a string in python?

So I am trying to change a randomized variable to a string with a function, any ideas why this isn't working?
def letter(x):
if x == 1:
x = "A"
elif x == 2:
x = "C"
elif x == 3:
x = "G"
elif x == 4:
x = "T"
else:
print "Error"
randint18= random.randrange(1,5)
letter(randint18)
print randint18 `
You have to return the value from the function, and assign it to a variable.
def letter(x):
...
return x
randint18 = random.randrange(1, 5)
result = letter(randint18)
print result
mine isn't a proper answer, which have been provided already, but a suggestion for improving your code. I'd do it in a comment, but the code formatting ain't good enough.
Why not use a dictionary for the mapping, instead of a sequence of if's? You could still place it in a function if you like:
letter = {1:'A', 2:'C', 3:'G', 4:'T'}
randint18 = random.randrange(1,5)
mapping = letter.get(randint18, 'Error')
print mapping
mind you, a list would be even more efficient, if the mapping started form zero:
letter = ['A', 'C', 'G', 'T']
randint18 = random.randrange(0,4)
try: # in case your random index were allowed to go past 3
mapping = letter[randint18]
except IndexError:
mapping = 'Error'
print mapping
You cannot alter the variable in place you must return it and capture the returned value.
import random
def letter(x):
if x == 1:
x = "A"
elif x == 2:
x = "C"
elif x == 3:
x = "G"
elif x == 4:
x = "T"
else:
print "Error"
return x # return it here
randint18= random.randrange(1,5)
randint18 = letter(randint18) # capture the returned value here
print randint18
There is a simpler way to achieve what you want, using a dictionary to map the values.
import random
def letter(x):
mapd = {1:'A', 2:'C', 3:'G', 4:'T'}
return mapd.get(x, None)
randint18= random.randrange(1,5)
randint18 = letter(randint18)
print randint18
You forgot to include a return in your function
def letter(x):
if x == 1:
x = "A"
elif x == 2:
x = "C"
elif x == 3:
x = "G"
elif x == 4:
x = "T"
else:
print "Error"
return x
randint18 = random.randrange(1,5)
returned_result = letter(randint18)
print returned_result
Add a return value of the function
return x
value_you_want = letter(randint18) ##add the return statement. Output will be saved to value_you_want
Please note that the variables defined inside a function are local to the function and cannot be accessed outside the scope of the function. You were expecting the value of x outside the function which is not possible. Just to check run your function and try to access the value in variable x. It will give error.
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
print x
NameError: name 'x' is not defined

python method breaks code

i have written some code that i want to convert into something i can import instead of it being used as the main.
floorMap = [[000,000,000,000,000,999,999,999,999,999],
[000,000,999,000,999,000,000,000,999,999],
[000,000,999,000,999,000,000,000,999,999],
[000,000,000,000,999,000,000,000,999,999],
[999,000,000,000,999,000,999,999,999,999],
[999,000,000,000,000,000,999,000,000,999],
[999,000,000,000,999,999,999,000,000,999],
[999,000,999,000,000,000,999,000,000,999],
[999,000,999,999,999,000,000,000,000,999],
[999,999,999,999,999,999,999,999,000,000]]
currentNum=0
wall=999
uncalculated=000
robotX=0
robotY=0
goalX=9
goalY=9
floorMap[goalY][goalX]=1
def changeSurroundings(X, Y):
#left
if(floorMap[X-1][Y]==uncalculated and X > 0):
floorMap[X-1][Y]=currentNum
#right
if(X < len(floorMap[0])-1 and floorMap[X+1][Y]==uncalculated):
floorMap[X+1][Y]=currentNum
#up
if(floorMap[X][Y-1]==uncalculated and Y > 0):
floorMap[X][Y-1]=currentNum
#down
if(Y < len(floorMap)-1 and floorMap[X][Y+1]==uncalculated):
floorMap[X][Y+1]=currentNum
def printMap():
i=0
floorMap[goalY][goalX]='G'
floorMap[robotY][robotX]='R'
while(i<len(floorMap)):
print floorMap[i]
print ""
i+=1
print ""
print ""
#------------------MOST IMPORTANT CHUNK OF CODE--------------
while(floorMap[robotY][robotX]==uncalculated):
x=0
while(x<len(floorMap[0])):
y=0
while(y<len(floorMap)):
if(floorMap[x][y] > uncalculated and floorMap[x][y] < wall):
currentNum=floorMap[x][y]+1
changeSurroundings(x,y)
y+=1
x+=1
printMap()
my problem is that whenever i try to put the most important chunk of code at the bottom into a method like so;
def calcMap():
while(floorMap[robotY][robotX]==uncalculated):
x=0
while(x<len(floorMap[0])):
y=0
while(y<len(floorMap)):
if(floorMap[x][y] > uncalculated and floorMap[x][y] < wall):
currentNum=floorMap[x][y]+1
changeSurroundings(x,y)
y+=1
x+=1
printMap()
it breaks my code. why? I dont seem to get any errors, it just gets stuck on one of the nested loops. i dont see any reason it should be doing this, but you guys probably will ;)
Thanks, Logan
Your problem comes from your global variables, in particular currentNum. This is basically what you're doing :
current = 0
def f():
current = 1
g()
def g():
print(current)
f() # Output: 0
What you need to do is:
current = 0
def f():
global current
current = 1
g()
def g():
print(current)
f() # Output: 1
Or better :
def f():
current = 1
g(current)
def g(current):
print(current)
f() # Output: 1
Also, you should consider using a more pythonic synthax for your calcMap function, something like :
def calc_map():
while floor_map[robot_x][robot_y] == uncalculated :
for x,array in enumerate(floor_map):
for y,element in enumerate(array):
if uncalculated < element < wall:
current_num = element + 1
change_surroundings(x, y, current_num)

Loop function in python

Could any one tell me whats wrong in the following code? (In Python 2.7)
def echo(msg):
print msg
def loop(x,y):
a = 0
while (a < x + 1):
a = a + 1
y
loop(5,echo("ok"))
I should be getting "ok" five times, but instead I just get "ok" once, no matter what
amount I set x to be.
echo("ok") is being evaluated before passing it to the function maybe, this is what you really want
def loop(x,y, *args):
a = 0
while (a < x + 1):
a = a + 1
y(*args)
def echo(msg):
print msg
loop(5,echo, "ok")
It's because you're evaluating echo("ok") when you call loop.
What you probably want to do is call echo("ok") on each iteration.
def echo(msg):
print msg
def call_echo_ok():
echo("ok")
def loop(x,y):
a = 0
while (a < x + 1):
a = a + 1
y()
loop(5, call_echo_ok)
Note that this can be done more concisely with lambda functions.
def echo(msg):
print msg
def loop(x,y):
a = 0
while (a < x + 1):
a = a + 1
y()
loop(5, lambda: echo('ok'))
You can try this:
def loop(times,message):
for i in range(times):
print message
loop(5,"Ok")

Categories