Using a variable outside of function in Python - python

A really simple question, and I'm sure I knew it but must have forgotten
When running this code:
x = 0
def run_5():
print "5 minutes later"
x += 5
print x, "minutes since start"
run_5()
print x
I get x isn't defined. How can I have x used in the function and effected outside of it?

Just return a value ?
x = 0
def run_5():
print "5 minutes later"
x += 5
return x
x=run_5()
print x

Put global x at the start of the function.
However, you should consider if you really need this - it would be better to return the value from the function.

Just to make sure, the x that is not defined is the one on line 4, not the one on the last line.
The x outside the function is still there and unaffected. It's the one inside that can't have anything added to it because, as far as Python is concerned, it does not exist when you try to apply the += operator to it.

I think you need to define a variable outside the function, if you want to assign it a return value from the function.
The name of the variable can be different than the name in function as it is just holding it

Related

Best way to change value of global value inside a function in Python?

I work a lot with a lot of global variables in Python which value constantly need to be changed when my code progresses. A very fine solution for me would be to take a global variable as an argument inside a function, however, as far as my knowledge reaches, it is only possible to change a global variable inside a function by actually naming that specific variable during the function definition. Because I work with a lot of different variablenames, this would force me to make a lot of functions per variablename.
What I want is something like this:
x = 5
def foo(_):
global _
_ = 10
return _
foo(x)
print(x)
where x now would be 10 instead of the actual output, which is 5.
What is the most efficient way to reach what I want?
Since you go to the trouble of naming x when you call foo(x), its not too much of a stretch to do x = foo(x):
x = 5
def foo(_):
_ = 10
return _
x = foo(x)
print(x)
I may not have completely understood your need to do this, but, you can also manage globals as follows:
x = globals()
x['cartoon'] = 'mickey'
print(x['cartoon'])

Python - why isnt my function outputting 'a' ten times? Beginner question

def testfunction():
for i in range(10):
return('a')
print(testfunction())
I want 'a' outputed 10 times in one line. If I use print instead of return, it gives me 10 'a's but each on a new line. Can you help?
return terminates the current function, while print is a call to another function(atleast in python 3)
Any code after a return statement will not be run.
Python's way of printing 10 a's would be:
print('a' * 10)
In your case it would look like the following:
def testfunction ():
return 'a' * 10
print(testfunction ())
The reason its only printing once is because the return statment finishes the function (the return function stops the loop).
In order to print 'a' 10 times you want to do the following:
def testfunction():
for i in range(10):
print('a')
testfunction()
If you want "a" printed 10 times in one single line then you can simply go for:
def TestCode():
print("a"*10)
There's no need to use the for loop. For loop will just "a" for 10 times but every time it'll be a new line.
You can also take in a function argument and get "a" printed as many times as desired.
Such as:
def TestCode(times):
t = "a"*times
print(t)
Test:
TestCode(5)
>>> aaaaa
TestCode(7)
>>> aaaaaaa
print and return get mixed up when starting Python.
A function can return anything but it doesn't mean that the value will be printed for you to see. A function can even return another function (it's called functional programming).
The function below is adapted from your question and it returns a string object. When you call the function, it returns the string object into the variable called x. That contains all of the info you wanted and you can print that to the console.
You could have also used yield or print in your for loop but that may be outside of the scope.
def test_function(item:str="a", n:int=10):
line = item*n # this will be a string object
return line
ten_a_letters = test_function()
print(ten_a_letters)
"aaaaaaaaaa"
two_b_letters = test_function("b",2)
print(two_b_letters)
"bb"
I want 'a' outputed 10 times in one line. If I use print instead of
return, it gives me 10 'a's but each on a new line.
If you want to use print, the you need to pass a 2nd parameter as follows:
def testfunction():
for i in range(10):
print('a', end='')
However, I think the pythonic way would be to do the following:
def testfunction():
print('a' * 10)
When you use return you end the execution of the function immediately and only one value is returned.
Other answers here provide an easier way to solve your problem (which is great), but I would like to suggest a different approach using yield (instead of return) and create a generator (which might be an overkill but a valid alternative nonetheless):
def testfunction():
for i in range(10):
yield('a')
print(''.join(x for x in testfunction()))
1. What does "yield" keyword do?
def test ():
print('a' * 10)
test()
Output will be 'aaaaaaaaaa'.

How do I change part of an input value in python?

So if I make an input that is function=input() and I want the user to put in a function like y=2x+3. How would I change the x so that it equals one (without the user having to type it in manually) so if I print it, it would be y=21+3
I tried using global x then setting x=1 but that didn't work. (I'm pretty new to python so sorry if I'm missing something obvious.)
You can replace x in input string:
function=input()
# function gets 'y=2x+3' here
function = function.replace('x', '1')
# function now 'y=21+3'
Maybe so
>>> x = 1
>>> formula = raw_input()
>>> formula.replace('x', str(x))

I cannot initialize class in python

I have a class Flight, and I'm trying initialize it, but I have a syntax error in
print x=Flight(flightFromInput='nebrasca')
This is a content of my example file
class Flight:
flightFrom = None
flightTo = None
departureDate = None
arrivalDate=None
airline=None
serviceClass=None
departureAirport = None
arrivalAirport=None
#----------------------------------------------------------------------
def __init__(self,flightFromInput):
self.flightFrom = flightFromInput
print x=Flight(flightFromInput='nebrasca')
What is wrong with this code?
You should write
x = Flight(flightFromInput='nebrasca')
print x
In python an assignment statement doesn't return the assigned value. So you cannot use it within another statement. As the other answers suggested, you can work around this by printing x in a separate line.
Note, that there are exceptions though:
a = b = 0 # works
a = (b = 0) # does not work
The first case is a special case allowed for convenience when you want to assign the same value to multiple variables. In the second case you clearly tell the compiler that b=0 is a separate statement, but as it doesn't return a value the outer assignment to a leads to the resulting SyntaxError.
Hope this explains it a bit more clearly, why you should do print x after assigning it.
Contrary to C, in Python assignments are statements only and not expressions. Therefore they do not have their own value. Try this:
x = Flight(flightFromInput='nebrasca')
print x

Can't assign function call while changng a variable

I was checking a project that i have to turn in (it's a battleship game) and for some reason when it runs "through" the section bellow it says "can't assign function call" when it's a copy paste of a piece of just above (with a couple changes) and it gives no error. Do you see the error?
'''
elif y == "v":
if a + 3 > 4:
return "put the boat higher, here it leaves the board"
else:
board(a)(b) = "V"
a = a + 1
board(a)(b) = "V"
a = a + 1
board(a)(b) = "V"
return board
'''
First of all, I highly recommend you to use python 3, read this.
And I don't know what is board, so I will answer for two cases.
board is not a function, nested python list
In this case, just change () to [] to access array.
board is a function
In this case, you're definitely wrong. board() is a function call and will return function result. So, you cannot assign "V" into your function call. This is pretty natural.
Now, check out what is your case and happy coding.
Maybe instead of accessing a matrix with the [] operator you are making calls with (). So try replacing board(a)(b) with board[a][b] but without more information is really hard to tell.

Categories