How to make global empty integer? - python

How to declare global empty integer? I have simple code but i don't know how to declare a variable before def. In java I can do just that: public int a;
but how to do it in python? Without this, the third if not working
My code:
def abcd:
if s<0.72:
if e>30:
a=0
return a
else:
a=0
return a
else:
if a == 1:
a = 1
return a
else:
a=1
return a
while True:
abcd

Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above.
You can declare as follow, if you want a non-value variable:
a = None
Or you can declare as follow, if you want a zero value int variable:
a = int()

At the top:
a = int()
int() returns 0 to start.
Also, you need to use proper function syntax:
def abcd():
If e or s are arguments passed to abcd, you need to add those to the function signature:
def abcd(e, s):

Python is a dynamic language with duck typing. So if you gonna declare an empty variable use None as it's initial value. That means no value.

Yes dont make it equal to zero, depending on what you are doing your program will not work if equal to zero.
REMEMBER ZERO IS NOT THE SAME AS NONE

Related

How to reuse a variable

I have the variable total in a function. Say that I'd like to use that variable in an if statement in another function. I can use the return keyword and return that variable from my first function but how would I use that variable in an if statement that would be outside that function or even in a different function?
You could re-declare the variable with the value from the function. I don't have a lot of information, but I think this is what you mean.
def some_function():
total=10
return total
total=some_function()
print(total)
return the value from your first function, and then a call to that function will evaluate to that value. You can assign the value to a variable, or pass it directly to another function. In either case, the value doesn't need to be assigned to the same variable name in different scopes.
def func_a():
total = 42
return total
def func_b(the_answer):
if the_answer == 42:
print("That's the answer to the ultimate question!")
func_b(func_a())

python change global string in function

First off i am very new to coding and python. I am trying to call a global string inside of a function. Then I want to change it into an integer. Next, I want to apply some Math to the integer. Finally I want to convert that integer back to a string and send it back to the global to use in other functions.
I have accomplished most of what I needed to do, but I am having trouble sending the string back to the global. I have tried using return() but it just quits the program. Instead I want it to go to another function, while retaining the new value
Relevant code
current_gold = '10'
def town():
global current_gold
print(current_gold)
def pockets():
global current_gold
new_gold = int(current_gold) + 5
new_gold = str(new_gold)
print(new_gold.zfill(3))
input("\tPress Enter to return to town")
town()
This is not the full code. I maybe doing stuff drastically wrong though.
current_gold = '10'
def changeToInt():
global current_gold
current_gold = int(current_gold)
print(type(current_gold)) # It's a string right now
changeToInt() # Call our function
print(type(current_gold)) # It's an integer now
Or you could do it by passing a parameter to your function like so:
current_gold = '10'
def changeToInt2(aVariable):
return int(aVariable)
print(type(current_gold)) # It's a string right now
current_gold = changeToInt2(current_gold) # make current_gold the output of our function when called with current_gold as aVariable
print(type(current_gold)) # It's an int now

How to use counter variable inside the body of recursive function

Below the code for counting the no of '1' character in String.
count2=0 #global variable
def Ones(s):
no=0;
global count2 #wanted to eliminate global variable
if(count2>=len(s)):
return no
if(s[count2]=='1'):#count2 is the index of current character in String
no = no+1
count2=count2+1
return no + Ones(s)
else:
count2=count2+1
return Ones(s)
in the above code using count2 as a global variable , is there any possible way to declare and use count2 variable as a local inside the function , have tried like but no luck
def Ones(s):
count2=0 # but everytime it get reset to zero
Note: number of parameter of function should be remain only one and no any other helper function have to use.
The avoidance of explicit state variables is an important part of the recursion concept.
The method you are calling only needs the remainder of the string to find 1s in it. So instead of passing a string, and the position in the string, you can pass only the remainder of the string.
Python's powerful indexing syntax makes this very easy. Just look at it this way: Each instance of the method can take away the part it processed (in this case: one character), passing on the part it didn't process (the rest of the string).
Just like #ypnos said, if you really want to use recursion, here is the code:
def Ones(s):
if not s:
return 0
if s[0]=='1':
return 1 + Ones(s[1:])
else:
return Ones(s[1:])
Hope it helps.

Why using the returned value of a method as the value of an optional parameter is not allowed in a Python function definition?

Following is my code:
def find_first_occurance(s, c, start=0, end=len(s) ):
while start<end:
if s[start] ==c: # whether they are the same or not
return start
else:
start+=1
return -1
print(find_first_occurance("the days make us happy make us wise","s"))
I got an error, name "s" is not defined.
I kind of understand what is going on. While on the other hand, it would be so nice if this feature was allowed in Python, right?
What do you think? Or did I miss something here?
s is not defined when you define the function, thus the error.
You can try initialize within the function
def find_first_occurance(s, c, start=0, end=None ):
if end is None:
end = len(s)

Python "if" statement - if xpath is true

im trying to code in python (very new to it) and need to check if an xpath is there then variable = the xpath but if not variable = string.
An example is below
if tree.xpath('//*#id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/span/text()') = true
$value = tree.xpath('//*#id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/span/text()')
else
$value = ''
You should really start by doing the whole official tutorial before anything else, as it will anwser your question.
First point : Python objects all have a 'truth' value in a boolean context, which is defined by the object's type and actual value. For builtin types, all empty containers (lists, dicts, sets etc), the empty string, all numerical zeros and the None object are false, everything else is true. For non builtin types you'll have to check the package's documentation.
The builtin type bool will also tell you the boolean value of a given object, so all of the below tests are equivalent:
if myobj:
xxx
if bool(myobj):
xxx
if bool(myobj) == True:
xxx
BUT keep in mind that it doesn't imply that bool(myobj) is the same as myobj - the first one is the boolean value of your object, so the following is NOT equivalent (unless myobj is one of True, 1 or 1.0):
if myobj == True:
xxx
Now wrt/ your actual code snippet: it's not valid Python (bad indentation, invalid identifier $value, invalid use of the assignment operator =, missing : after the if and else statements, wrong capitalization for True...)
Assuming you meant:
# let's make this at least readable:
path = '//*#id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/span/text()'
if tree.xpath(path) == True:
value = tree.xpath(path)
else:
value = ''
The obvious error is the explicit test against True (tree.xpath() doesn't return a boolean). You either have to explicitely cast the return of tree.xpath() to a boolean (which is quite verbose, totally useless and definitly unpythonic) or just let Python do the right thing by removing the == True part of your test.
As a side note: calling tree.xpath twice in a row with the same argument is a waste of processor cycle (both calls will return the same value), so use a variable instead - it will also make your code much more readable and maintainable. The Pythonic version of your code would look something like:
path = '//*#id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/span/text()'
found = tree.xpath(path)
value = found if found else ''
or even more simply:
path = '//*#id="page"]/div[1]/div/main/div/article/div/div[1]/section[2]/p[1]/span/text()'
value = tree.xpath(path) or ''
since the or operator will not yield a boolean value but either the first of it's operand that has a true value or the last operand if none has a true value.
#No need to test == if value is bool. and you not check, you assign value with one =
if anything:
#Then do this
else:
#Do this

Categories

Resources