If You Create a Variable Inside a If Statement Is It Available Outside the If Statement

How to access the variables after if-condition when the variable is defined inside the if-condition in python

Your problem appears to be the fact that you are referencing a variable outside of its scope. Essentially what is happening is in your if statement you are creating a variable exclusively for use within the if scope. Effectively when you have said print vn.firstChild.nodeValue you can also imagine it as being any other variable such as print undefinedVar. What is occuring is your are referencing (calling) upon the variable before it has even been defined.

However, no worries here since this is very easy to fix. What we can do is simply create your vn and test variables outside of the if scope, hence inside your actual method by doing the following:

vn = None
test = None

for DO in range(count) :
atnnames = doc.getElementsByTagName("atnId")[DO]
atn = atnnames.childNodes[0].nodeValue
if atn == line[0]:
vn = doc.getElementsByTagName("vn")[DO]
vncontent = vn.childNodes[0].nodeValue
y = vncontent.encode('utf-8')
# print y
if '-' in y:
slt = (int(y.split('-')[0][-1]) + 1)
test = y.replace(y.split('-')[0][-1], str(slt))
# print test
else:
slt = (int(y.split('.')[-1]) + 1)
test = y.replace(y.split('.')[-1], str(slt))
# print test
else:
#print test
vn.firstChild.nodeValue = test
print vn.firstChild.nodeValue

This basically just creates an empty variable in the outermost scope. I've set the values to None since they get defined once your for loop runs. So what happens now is you have a variable which has been declared outside, and is None at the start, but as you run your for loop you are not creating a temporary variable just inside the if statement, but you are actually changing the value of

Is it possible to define a variable in a Swift if statement?

No you can not. The if statement defines a local scope, so whatever variable you define inside its scope, won't be accessible outside of it.

You have a few options

var cellWidth = requiredWidth
if notification.type == "vote"{
cellWidth = maxWidth - 80
println("cellWidth is \(cellWidth)")
println("maxWidth is \(maxWidth)")
}
println("cellWidth is \(cellWidth)")

or (better IMHO) without using variable, but only constants

func widthForCell(_ maxWidth: CGFloat, _ requiredWidth: CGFloat, _ notification: Notification) -> CGFloat {
switch notification.type {
case "vote": return maxWidth - 80
default: return requiredWidth
}
}
let cellWidth = widthForCell(maxWidth, requiredWidth, notification)
println("cellWidth is \(cellWidth)")

how can i acess a variable outside of an if statement in java

Use can use it as

 int buyOrder= 0;
if((e.getSource()==userOrder2)&& (orderType==1)){
String buyO= userOrder2.getText();
buyOrder= Integer.parseInt(buyO);
}
if(orderType==1 && (stockPrice <= buyOrder))

Java uses block level local variable scopes. A variable has to be declared in a scope which is common for all the places where you want to use it.

In your case the variable the scope of the variable buyOrder is limited to the block if((e.getSource()==userOrder2)&& (orderType==1)){...}, so it is not available outside the if block. Here we need to declare the variable out side the if((e.getSource()==userOrder2)&& (orderType==1)){...} so that it can be accessed outside of the block.

How to access a variable declared inside IF statement outside IF statement in Python

It seems that this problem can be alleviated by the global treatment to the variable. How about declaring the searchData as global first?

@app.route('/ML', methods=['GET', 'POST'])
def index():
global searchData
if request.method == "POST":
request_data = json.loads(request.data)
searchData = (request_data['content'])
return jsonify(searchData)
mycursor = mydb.cursor(dictionary=True)
query = "SELECT * FROM COMPANY WHERE COMPANY_NAME LIKE %s LIMIT 20;"
mycursor.execute(query,("%" + searchData + "%",))
myresult = mycursor.fetchall()

company = []
content = {}

for result in myresult:
content ={'COMPANY_NAME':result['COMPANY_NAME'],}
company.append(content)
content = {}
return jsonify(company)

What's the scope of a variable initialized in an if statement?

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.

(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)



Related Topics



Leave a reply



Submit