Python - True part of if condition always executes - python

No matter what's the value of what, the true part of if condition is always executed.
what = ""
def sendPacket(where, what):
print("sendPacket()> i/p what :" + what)
if what:
zb.send('tx',dest_addr_long = where,dest_addr = UNKNOWN,data = what)
print('sendPacket()> Data: '+ what)
print('sendPacket()> Data sent to: '+ where )
else:
print('sendPacket()> data not sent')
I want the true part to be executed only when what is not equal to null or empty.
Any help would be appreciated.

Ask explicitly for the condition you want:
if what and not what.isspace():
The above states that what is not null, is not an empty string, and is not a string of just whitespaces. It's possible that your input has some line break, tab, or other non-printable character that's messing with the test.

Related

simple print statement is not working inside method with if statement in python

I started learning Python code recently and one simple print statement is giving me trouble since last 4 days.
Problem: the print statement is not working inside the validatePostcode(postcode) method for if-statement. The assigned value is 200 (status code) which is printing fine without the if-statement. Also, when I compare with the True (result value) for that API it works fine without if-statement, why it is not working after I apply the if and try to compare?
Error:
File "./py_script3.py", line 32
print ("Congrats")
^
IndentationError: expected an indented block
#!/usr/bin/env python3
import os,re,sys
import urllib.request as req
import json
def loadJsonResponse(url):
#return json.loads(req.urlopen(url).read().decode('utf-8'))['result']
#return json.loads(req.urlopen(url).read().decode('utf-8'))['status']
print ("I am in loadJsonResponse before returning string")
string = json.loads(req.urlopen(url).read().decode('utf-8'))
return string
print ("I am in loadJsonResponse after returning string")
def lookuppostcode(postcode):
url = 'https://api.postcodes.io/postcodes/{}'.format(postcode)
return loadJsonResponse(url)
def validatePostcode(postcode):
url = 'https://api.postcodes.io/postcodes/{}/validate'.format(postcode)
#return loadJsonResponse(url)
string = json.loads(req.urlopen(url).read().decode('utf-8'))
Value = str(string['status'])
print (Value)
if Value == 200 :
print ("Congrats")
def randomPostcode():
url = 'https://api.postcodes.io/random/postcodes'
return loadJsonResponse(url)
def queryPostcode(postcode):
url = 'https://api.postcodes.io/postcodes?q={}'.format(postcode)
return loadJsonResponse(url)
def getAutoCompletePostcode(postcode):
url = 'https://api.postcodes.io/postcodes/{}/autocomplete'.format(postcode)
return loadJsonResponse(url)
#Input = input("Enter the postcode : ")
#print(lookuppostcode('CB3 0FA'))
validatePostcode('CB3 0FA')
#print(queryPostcode('HU88BT'))
#print(randomPostcode(Input))
This piece of code (which is generating the error):
if Value == 200 :
print ("Congrats")
Should be
if Value == 200 :
print ("Congrats")
Because python expects an indented block after the conditional, just like the message error is saying to you
You should indent the print statement like so:
if Value == 200 :
print ("Congrats")
You can read more about this here!
From https://docs.python.org/2.0/ref/indentation.html:
Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.
By doing
if Value == 200:
print ("Congrats")
Python interprets the two lines as two different groups of statements. What you should do is:
if Value == 200:
print ("Congrats")
Need to add an indent after the if statement. You can do so by pressing return after typing the colon
After the if-statement, a section of code to run when the condition is True is included. The section of must be indented and every line in this section of code must be indented the same number of spaces. By convention, four space indentation is used in Python.
if Value == 200:
print ("Congrats")

Using function returns with None

Write a function file_in_english(filename, character_limit) that takes a filename (as a str) and a character_limit (as an int). The filename is the name of the file to convert from Cat Latin to English and the character limit is the maximum number of characters that can be converted. The limit is on the total number of characters in the output (including newline characters).
The function should return a string that contains all the converted lines in the same order as the file - remember the newline character at the end of each line (that is make sure you include a newline character at the end of each converted line so that it is included in the line's length).
If the limit is exceeded (ie, a converted sentence would take the output over the limit) then the sentence that takes the character count over the limit shouldn't be added to the output. A line with "<>" should be added at the end of the output instead. The processing of lines should then stop.
The lines in the file will each be a sentence in Weird Latin and your program should print out the English version of each sentence
The function should keep adding sentences until it runs out of input from the file or the total number of characters printed (including spaces) exceeds the limit.
The answer must include your definition of english_sentence and its helper(s) functions - that I should have called english_word or similar.
You MUST use while in your file_in_english function.
You can only use one return statement per function.
The test file used in the examples (test1.txt) has the following data:
impleseeoow estteeoow aseceeoow
impleseeoow estteeoow aseceeoow ineleeoow 2meeoow
impleseeoow estteeoow aseceeoow ineleeoow 3meeoow
impleseeoow estteeoow aseceeoow ineleeoow 4meeoow
I program works fine except that sometimes it returns None.
def english_sentence(sentence):
"""Reverse Translation"""
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
eng_sentence = []
for coded_word in sentence.split():
if coded_word.endswith("eeoow") and (coded_word[-6] in consonants):
english_word = coded_word[-6] + coded_word[:-6]
if (coded_word[-6] == 'm') and (coded_word[0] not in consonants):
english_word = '(' + english_word + ' or ' + coded_word[:-6] + ')'
eng_sentence.append(english_word)
return " ".join(eng_sentence)
def file_in_english(filename, character_limit):
"""English File"""
newone = open(filename)
nowline = newone.readline()
characters = 0
while characters < character_limit and nowline != "":
process = nowline[0:-1]
print(english_sentence(process))
characters += len(nowline)
nowline = newone.readline()
if characters > character_limit:
return("<<Output limit exceeded>>")
ans = file_in_english('test1.txt', 20)
print(ans)
Output is:
simple test case
simple test case line (m2 or 2)
simple test case line (m3 or 3)
simple test case line (m4 or 4)
None
But I must use only one return statement in each function. How can I do that for the second function and avoid the "None" in output?
You're doing the same thing as:
def f():
print('hello')
print(f())
So basically narrows down to:
print(print('hello world'))
Also btw:
>>> type(print('hello'))
hello
<class 'NoneType'>
>>>
To solve your code do:
def file_in_english(filename, character_limit):
s=""
"""English File"""
newone = open(filename)
nowline = newone.readline()
characters = 0
while characters < character_limit and nowline != "":
process = nowline[0:-1]
s+=english_sentence(process)+'\n'
characters += len(nowline)
nowline = newone.readline()
if characters > character_limit:
s+="<<Output limit exceeded>>"
return s
ans = file_in_english('test1.txt', 20)
print(ans)
You have to make sure, that any function that should return something, does this for ALL ways that your function can end.
Your function file_in_english only returns something for the case if characters > character_limit:
If charachter == or charachter < character_limit this is not the case, the function returns nothing explicitly.
Any function that does not return something from it on end, implicitly returns None when it returns to its caller.
def something(boolean):
"""Function that only returns something meaninfull if boolean is True."""
if boolean:
return "Wow"
print(something(True)) # returns Wow
print(something(False)) # implicitly returns/prints None
You can find this fact f.e. in the python tutorial:
Coming from other languages, you might object that fib is not a
function but a procedure since it doesn’t return a value. In fact,
even functions without a return statement do return a value, albeit a
rather boring one. This value is called None (it’s a built-in name).
Writing the value None is normally suppressed by the interpreter if it
would be the only value written. You can see it if you really want to
using print():
Source:https://docs.python.org/3.7/tutorial/controlflow.html#defining-functions - just short after the 2nd green example box

Python-Json Parser

I am trying to implement python Json parser with the following set of rules:
Rule 1:
A JSON data object always begins with curly braces and ends with curly braces.
{}
Rule 2:
All data is represented in the form of
"string":value
where the value can be any of the following:
number
string
boolean
another json
Rule 3:
The rules for forming the strings (on the left hand side in red) are similar to rules for variables in most programming languages.
* They can be alphanumeric, but should always begin with a letter.
* They are case sensitive
* They can not contain special characters except underscores.
I worked on it and completed all the conditions except "another json". Hee is my code
import re
import string
class parser(object):
fp=open('jsondata.txt','r')
str=fp.read()
def __init__(self):
print "Name of the file Opened is :",self.fp.name
print "Contents of the file :\n",self.str
def rule1(self,str):
if self.str[:1].startswith('{'):
if self.str[:-1].endswith('}'):
print "RULE 1\n",
print "first character is '{' last character is '} : passed rule1\n"
else:
print "Not a JSON data"
def splitdata(self):
self.str=self.str[1:]
self.str=self.str[:-2]
print self.str
#Storing the words of string in a list
self.list1=[]
self.list1=re.split(',',self.str)
self.list2=[]
self.list3=[]
for i in self.list1:
self.list2=list(re.split(':',i))
self.list3.extend(list(self.list2))
self.left_list=[]
self.right_list=[]
self.i=0
self.left_list=list([self.list3[i] for i in range(len(self.list3)) if i % 2 == 0])
self.right_list=list([self.list3[i] for i in range(len(self.list3)) if i % 2 == 1])
print "DATA SPLIT"
print "Left elements of the json data:",self.left_list
print "Right elements of the json data:",self.right_list,"\n"
def left_parse(self):
"""we gona check "This part of the string":"This part will be checked in next function"\
Conditions imposed on left part of string:\
1.starts and ends with ""\
2.Starts with Alphabet\
3.Contains No special characters except unserscore _"""
for i in range(len(self.left_list)):
self.str1=self.left_list[i]
if self.str1.startswith('"') and self.str1.endswith('"')\
and self.str1[1].isalpha():
self.str2=self.str1[1:]
self.str3=self.str2[:-1]
print "Left side content:",self.str3
print "Status : Valid"if re.match("^[a-zA-Z0-9_]*$", self.str3) else "Invalid"
else:
print "Left side content:",self.str1
print "Status: Invalid"
obj=parser()
obj.rule1(str)
obj.splitdata()
obj.left_parse()
Now the problem is When i tried to check my right_list, whenever i get Another json data then the output goes wild. Can anyone please help me. i framed left_list and right_list based on splitting(comma and colon).
While parsing json inside a json this logic seems not working...

Python: How to make a script to continue after a valid string variable is returned

I got a question about a flow of definition in python:
def testCommandA () :
waitForResult = testCommandB ()
if result != '' :
print 'yay'
Is there any way to make waitForResult to wait for testCommandB to return something (not just an empty string)? Sometimes testCommandB will produce nothing (empty string) and I do not want to pass empty string but as soon as I got a string in waitForResult then testCommandA will continue to run. Is it possible?
Thanks in advance
# Start with an empty string so we run this next section at least once
result = ''
# Repeat this section until we get a non-empty string
while result == '':
result = testCommandB()
print("result is: " + result)
Note that if testCommandB() doesn't block, this will cause 100% CPU utilization until it finishes. Another option is sleep between checks. This version checks every tenth of a second:
import time
result = ''
while result == '':
time.sleep(0.1)
result = testCommandB()
print("result is: " + result)
Just return from testCommandB only where it's not an empty string. ie, have testCommandB block until it has a meaningful value.

Python if statement not working as expected

I'm searching for a string in a website and checking to see if the location of this string is in the expected location. I know the string starts at the 182nd character, and if I print temp it will even tell me that it is 182, however, the if statement says 182 is not 182.
Some code
f = urllib.urlopen(link)
#store page contents in 's'
s = f.read()
f.close()
temp = s.find('lettersandnumbers')
if (htmlsize == "197"):
#if ((s.find('lettersandnumbers')) == "182"):
if (temp=="182"):
print "Glorious"
doStuff()
else:
print "HTML not correct. Aborting."
else:
print htmlsize
print "File size is incorrect. Aborting."
str.find returns integer, not string. String-integers comparison always returns False.
Im not a python guru, but ill take a shot
Try it like this
if (temp == 182)
Why? See SilentGhost answer. It involves types

Categories