I'm doing a real silly mistake in Python but unable to find what it is
I'm doing something like this in python
filename="file1"
if name == 'file1'
print 1
I'm getting an invalid syntax error
You are missing a colon
filename="file1"
if name == 'file1':
print 1
You need to put a colon at the end of the if statment
filename="file1"
if name == 'file1':
print 1
what is name?? did you define it elsewhere?? I assume its "filename" instead, so
filename="file1"
if filename == 'file1':
print 1
if "name" is defined, then the problem is indeed the ":" at the end of "if" line.
Related
I am trying to append characters in a string but I am getting problem with the loop. I don't know the command to append characters in the string:
import string
import random
def main():
generateRandomNumbers()
def generateRandomNumbers():
nameLength = 10
for i in range(nameLength)
x = random.choice(string.ascii_lowercase )
uname.append(x)
print (x)
size = 0
nameLength=0
if __name__ == "__main__":
main()
I am getting following error message:
File "Fl.py", line 8
for i in range(nameLength)
^ SyntaxError: invalid syntax
You are getting the syntax error because you are missing a colon at the end of your for loop. It should look like this:
for i in range(nameLength):
As Kenan has already said, I would recommend using the + operator to append to a string. This article has some decent examples that should put you on the right path.
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")
Context: I am trying to convert a maf file (multiple alignment file) to individual fasta file. I keep running into the same error that I'm not sure how to fix and this may be because I'm relatively new to python. My code is below:
open_file = open('C:/Users/Danielle/Desktop/Maf_file.maf','r')
for record in open_file:
print(record[2:7])
if (record[2] == 'Z'):
new_file = open(record[2:7]+".fasta",'w')
header = ">"+record[2:7]+"\n"
sequence = record[46:len(record)]
new_file.write(header)
new_file.write(sequence)
new_file.close()
else:
print("Not correct isolate.")
open_file.close()
The error I get is:
IndexError
Traceback (most recent call last)
2 for record in open_file:
3 print(record[2:7])
----> 4 if (record[2] == 'Z'):
5 new_file = open(record[2:7]+".fasta",'w')
6 header = ">"+record[2:7]+"\n"
IndexError: string index out of range
If I remove the if, else statement it works as I expect but I would like to filter for specific species that start with the character Z.
If anyone could help explain why I can't select for only strings that start with the character Z this way, that would be great! Thanks in advance.
Its giving an error when the length of record is less than 2.
To fix this you can change your if statement to:
if (len(record) > 2 and record[2] == 'Z'):
Ideally you should also handle such cases before separately.
Here's an alternative answer.
The problem you're having is because the record you're reading might not have at least 3 chars. For that reason you have to check the length of the string before checking index 2. As you might have noticed, the line 3 doesn't crash.
Slice operator in short will slice from index 2 to 7 returning anything it finds.
So if you have let look at this:
"abcd"[1:] == "bcd"
"abcd"[1:3] == "bc"
"abcd"[1:10] == "bcd"
"abcd"[4:] == ""
As you can see, it will return anything from index 1 to index 2 excluded. When it doesn't find anything the slice operation stop and return.
So one different way to get the same result as checking for the length would be to do this:
if (record[2:3] == 'Z'):
This way, you're slicing the char at index 2, if the index exists it will return a char otherwise an empty string. That said, I can't say if the slice operation will be faster than checking the length of the string and getting the index then. In some ways, the slice operation does that internally most probably.
A better answer
This way, we can fix the problem you had and also make it a bit more efficient. You're slicing multiple time the record for [2:7] you should store that in a variable. If the index 2 isn't present in the resulting filename, we can assume the filename is empty. If the filename is empty it will be falsy, if not we can check index 0 because it's certainly will be there and index 0 of filename is index 2 of record.
Second problem is to use the format string instead of + operator. It will convert anything you pass to the format string to a string as the format passed is %s. If you'd pass a False or None value, the program will crash as arithmetic operation are only allowed for str + str.
open_file = open('C:/Users/Danielle/Desktop/Maf_file.maf','r')
for record in open_file:
filename = record[2:7]
print(filename)
if (filename and filename[0] == 'Z'):
with open("%s.fasta" % filename,'w') as newfile:
header = ">%s\n" % filename
sequence = record[46:len(record)]
new_file.write(header)
new_file.write(sequence)
else:
print("Not correct isolate.")
open_file.close()
A bit of reformat and we'd end up with this:
def write_fasta(record):
filename = record[2:7]
print(filename)
if (filename and filename[0] == 'Z'):
with open("%s.fasta" % filename,'w') as new_file:
header = ">%s\n" % filename
sequence = record[46:len(record)]
new_file.write(header)
new_file.write(sequence)
else:
print("Not correct isolate.")
maf_filename = 'C:/Users/Danielle/Desktop/Maf_file.maf'
with open(maf_filename, 'r') as maf:
for record in maf:
write_fasta(record)
Use the context manager whenever possible as they'll handle the file closing themselves. So no need to explicitly call the close() method.
so I have some code such as:
print(csv[0])
Genes = csv[0]
OutPut.write(Genes)
OutPut.write(',')
OutPut.write(csv[1])
OutPut.write(',')
try:
OutPut.write(csv[2])
except IndexError:
print("No Lethality")
OutPut.write('\n')
Basically csv has 3 objects and they should print out as this:
atp,10101010,lethal
But for some reason, if csv[0] so the first value, begining with an 'l' it is printed as:
l
sfsf,1010101010,Lethal
I have tried using a for loop etc but I always get the same issue and all the other lines which start without an 'l' work perfectly.
Thanks
It's not clear from your description why you are seeing multiple lines, here's alternative logic that may help you diagnose the problem.
Try:
OutPut.write(','.join(csv))
OutPut.write('\n' if len(csv) == 3 else "No Lethality\n")
Or:
from __future__ import print_function
print(','.join(csv), file=Output)
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