Using Variables Outside of an 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

How to access a variable outside the if statement

Initialize $uname outside the if block:

$uname = '';
if ($row['ulogo'] == '1'){
$ulogo = '../images/varsity logos/witsLogo.jpg';
$uname = 'Wits';
echo $uname;
} else if ($row['ulogo'] == '2'){
$ulogo = '../images/varsity logos/UJ.png';
$uname = 'University of Johannessburg';
echo $uname;
}
echo $uname;

send variable to another if statement

This is an issue with scope.

Your variable, mytimer, is being declared locally within your if statement, meaning it can't be accessed by anything outside of that if statement as it doesn't exist there.

You could declare it outside the if blocks to start with and then reference it inside them when needed like so:

function myFunction(){

//Declare mytimer here
let mytimer = 0;

if(//condition){
mytimer = setInterval(function() {
alert("hello");
}, 1000);
} else if(//another condition){
//do something
} else{
clearTimeout(mytimer); <--- this will now be accessible here
}

if(){
clearTimeout(mytimer); <--- as will this one
}
}

Edit: I see from your edit you've said you can't declare your variable outside your if blocks.

As far as I'm aware, it's not possible to access local variables outside of scope in JavaScript; therefore, your only option is most likely to rewrite the program in a way that means you can unfortunately.

useState not reading variable outside of if statement

variables declared within if statements stay within the scope of the if statement. So when the pointer leaves the if block the variable is disposed of.

all you need to do is the following

const [data, setData] = useState({
name: "",
email: "",
machinetype: [],
});

const handleInputChange = (event) => {
if (event.target.name === "machinetype") {
const chck = event.target.checked;
let list = null;
if (chck) {
list = data[event.target.name].concat([event.target.value]);
} else {
const index = data[event.target.name].indexOf(event.target.value);
const remove = data[event.target.name].splice(index, 1);
list = data[event.target.name];
}
setData({
...data,
[event.target.name]: list,
});
}
};

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)


Related Topics



Leave a reply



Submit