Python if statement not working as expected - python

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

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")

Please correct my code Python

I am trying to read from a file and return solutions based on the problem that the user inputs. I have saved the text file in the same location, that is not an issue. At the moment, the program just crashes when I run it and type a problem eg "screen".
Code
file = open("solutions.txt", 'r')
advice = []
read = file.readlines()
file.close()
print (read)
for i in file:
indword = i.strip()
advice.append (indword)
lst = ("screen","unresponsive","frozen","audio")
favcol = input("What is your problem? ")
probs = []
for col in lst:
if col in lst:
probs.append(col)
for line in probs:
for solution in advice:
if line in solution:
print(solution)
The text file called "solutions.txt" holds the following info:
screen: Take the phone to a repair shop where they can replace the damaged screen.
unresponsive: Try to restart the phone by holding the power button for at least 4 seconds.
frozen: Try to restart the phone by holding the power button for at least 4 seconds.
audio: If the audio or sound doesnt work, go to the nearest repair shop to fix it.
Your question reminds me a lot of my learning, so I will try give an answer to expand on your learning with lots of print statements to consider how it works carefully. It's not the most efficient or stable approach but hopefully of some use to you to move forwards.
print "LOADING RAW DATA"
solution_dictionary = {}
with open('solutions.txt', 'r') as infile:
for line in infile:
dict_key, solution = line.split(':')
print "Dictionary 'key' is: ", dict_key
print "Corresponding solution is: ", solution
solution_dictionary[dict_key] = solution.strip('\n')
print '\n'
print 'Final dictionary is:', '\n'
print solution_dictionary
print '\n'
print 'FINISHED LOADING RAW DATA'
solved = False
while not solved: # Will keep looping as long as solved == False
issue = raw_input('What is your problem? ')
solution = solution_dictionary.get(issue)
""" If we can find the 'issue' in the dictionary then 'solution' will have
some kind of value (considered 'True'), otherwise 'None' is returned which
is considered 'False'."""
if solution:
print solution
solved = True
else:
print ("Sorry, no answer found. Valid issues are 'frozen', "
"'screen' 'audio' or 'unresponsive'")
want_to_exit = raw_input('Want to exit? Y or N? ')
if want_to_exit == 'Y':
solved = True
else:
pass
Other points:
- don't use 'file' as a variable name anywhere. It's a python built-in and can cause some weird behaviour that you'll struggle to debug https://docs.python.org/2/library/functions.html
- If you get an error, don't say "crashes", you should provide some form of traceback e.g.:
a = "hello" + 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-6f5e94f8cf44> in <module>()
----> 1 a = "hello" + 2
TypeError: cannot concatenate 'str' and 'int' objects
your question title will get you down-votes unless you are specific about the problem. "help me do something" is unlikely to get a positive response because the error is ambiguous, there's no sign of Googling the errors (and why the results didn't work) and it's unlikely to be of any help to anyone else in the future.
Best of luck :)
When I change the line "for i in file:" to "for i in read:" everything works well.
To output only the line starting with "screen" just forget the probs variable and change the last for statement to
for line in advice:
if line.startswith( favcol ) :
print line
break
For the startswith() function refer to https://docs.python.org/2/library/stdtypes.html#str.startswith
And: the advices of roganjosh are helpfull. Particularly the one "please don't use python keywords (e.g. file) as variable names". I spent hours of debugging with some bugs like "file = ..." or "dict = ...".

replacing text in a file, Python

so this piece of code is meant to take a line from a file and replace the certain line from the string with a new word/number, but it doesn't seem to work :(
else:
with open('newfile', 'r+')as myfile:
x=input("what would you like to change: \nname \ncolour \nnumber \nenter option:")
if x == "name":
print("your current name is:")
test_lines = myfile.readlines()
print(test_lines[0])
y=input("change name to:")
content = (y)
myfile.write(str.replace((test_lines[0]), str(content)))
I get the error message TypeError: replace() takes at least 2 arguments (1 given), i don't know why (content) is not accepted as an argument. This also happens for the code below
if x == "number":
print ("your current fav. number is:")
test_lines = myfile.readlines()
print(test_lines[2])
number=(int(input("times fav number by a number to get your new number \ne.g 5*2 = 10 \nnew number:")))
result = (int(test_lines[2])*(number))
print (result)
myfile.write(str.replace((test_lines[2]), str(result)))
f=open('newfile', 'r')
print("now we will print the file:")
for line in f:
print (line)
f.close
replace is a function of a 'str' object.
Sounds like you want to do something like (this is a guess not knowing your inputs)
test_lines[0].replace(test_lines[0],str(content))
I'm not sure what you're attempting to accomplish with the logic in there. looks like you want to remove that line completely and replace it?
also i'm unsure what you are trying to do with
content = (y)
the output of input is a str (which is what you want)
EDIT:
In your specific case (replacing a whole line) i would suggest just reassigning that item in the list. e.g.
test_lines[0] = content
To overwrite the file you will have to truncate it to avoid any race conditions. So once you have made your changes in memory, you should seek to the beginning, and rewrite everything.
# Your logic for replacing the line or desired changes
myfile.seek(0)
for l in test_lines:
myfile.write("%s\n" % l)
myfile.truncate()
Try this:
test_lines = myfile.readlines()
print(test_lines[0])
y = input("change name to:")
content = str(y)
myfile.write(test_lines[0].replace(test_lines[0], content))
You have no object known purely as str. The method replace() must be called on a string object. You can call it on test_lines[0] which refers to a string object.
However, you may need to change your actual program flow. However, this should circumvent the error.
You need to call it as test_lines[0].replace(test_lines[0],str(content))
Calling help(str.replace) at the interpreter.
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
Couldn't find the docs.

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.

Restricting the User Input to Alphabets

I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
print x
elif x != r:
print "Come on,'", x,"' can't be your name"
print raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.
Please help me to debug my code. And, is it possible to do it without using the reg exp?
If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha():
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha() in your if-statement instead of x==r.
I don't understand what you're trying to do with
x = r
if x == r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
while not r.match(x):
print "Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
while not x.isalpha():
One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
if not namefield.isalpha():
print "Please use only alpha charactors"
elif not 4<=len(namefield)<=10:
print "Name must be more than 4 characters and less than 10"
else:
print "hello" + namefield
isalpha will check to see if the whole string is only alpha characters. If it is, it will return True.

Categories