IndentationError: expected an indented block within nested for loop [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am not sure where my indentation error is with my code. I am getting this error:
File "ex1.py", line 43
if v == 'arista_eos':
^
IndentationError: expected an indented block
Here is the code that is giving me the error:
for line in devices:
for k, v in line.items():
if v == 'juniper_junos':
try:
net_conn = ConnectHandler(**line)
config = net_conn.send_command("show config | display set")
filename = net_conn.host + '_' + time
with open(filename, mode='w') as f:
cwd = os.getcwd()
cfl = cwd + '/' + filename
f.write(config)
shutil.move(cfl, direct)
except NoValidConnectionsError:
if v == 'arista_eos':
try:
net_conn = ConnectHandler(**line)
config = net_conn.send_command("show run")
filename = net_conn.host + '_' + time
with open(filename, mode='w') as f:
cwd = os.getcwd()
cfl = cwd + '/' + filename
f.write(config)
shutil.move(cfl, direct)
except (NetMikoTimeoutException, NoValidConnectionsError, NameError):

except NoValidConnectionsError:
if v == 'arista_eos':
After except NoValidConnectionsError: there must follow an indented block which specifies what should happen in case of a NoValidConnectionsError:
except NoValidConnectionsError:
# indented block here
if v == 'arista_eos':
You omitted that for some reason, which isn't valid.

Related

how to print the exception from exce? My code is in string. It works fine on the correct code snippet. not on error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
This post was edited and submitted for review 4 days ago and failed to reopen the post:
Not suitable for this site
Improve this question
import os
path = "C:\\Users\\Abdul Rafay\\Downloads\\Compressed\\day3_t1\\day3_t1"
file_name = os.listdir(path)
word1 = "email"
word2 = "return"
word3 = "def"
x = ""
y = "5"
for i in file_name:
path1 = os.path.join(path, I)
with open(path1, 'r') as fp:
lines = fp.readlines()
for line in lines:
if line.find(word1) != -1:
print("File: ",path1)
print("Email: ",line.strip("email= "))
elif line.find(word2) != -1 or line.find(word3) != -1:
x += line
if 'def' in x and 'return' in x:
print("Solution(5): ")
exec(x + """
try:
print(solution("""+str(y)+"""))
except Exception as err:
print(err)
""")
print("=========================")
x = ""
#The End---------------------------------------The End
Type 1 (with Error)
Type 2 (No Error)
I am reading the "solution" method from these files. and pass the parameter using exec and execute the function.
But the problem is when there is no error in the code it works fine but if there is a error it doesn't show the exception.
This is the output. when there is error it prints the particular function multiple times.

"NameError: name is not defined" for user input [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am new to python and made a short script to try them out, while doing so I came across and error I've never had for the particular situation before, when I try to define uN as a str inputted by the user I get:
Traceback (most recent call last):
File "/home/pi/Desktop/Scripts/classTest/classTest1.py", line 14, in <module>
uN = input(str("Username"))
File "<string>", line 1, in <module>
NameError: name 'ben' is not defined
The code is as follows:
class user:
def __init__(self, usrName, pWord):
self.usrName = usrName
self.pWord = pWord
def createUsrPw(self):
f = open("usrName.txt", "a")
f.write(self.usrName)
f.write(" ")
f.write(self.pWord)
f.write("\n")
f.close()
uN = input(str("Username"))
pW = input(str("Password"))
usr1 = user(uN, pW)
usr1.createUsrPw()
I have used the x = input(str()) syntax a lot before and never had this error, and the error traces back to line 1, so is uN = input(str("Username")) still being considered a part of the class?
when I simplify the code to this it works perfectly:
class user:
def __init__(self, usrName, pWord):
self.usrName = usrName
self.pWord = pWord
def createUsrPw(self):
f = open("usrName.txt", "a")
f.write(usrName)
f.write(" ")
f.write(pWord)
f.write("\n")
f.close()
usr1 = user("Ben", "testPw")
usr1.createUsrPw()
with the file usrName.txt being appended to include "Ben testPw" as intended.
You should use raw_input instead of input as you are using Python 2.X. input works in Python 3.
This code would work:
class user:
def __init__(self, usrName, pWord):
self.usrName = usrName
self.pWord = pWord
def createUsrPw(self):
f = open("usrName.txt", "a")
f.write(self.usrName)
f.write(" ")
f.write(self.pWord)
f.write("\n")
f.close()
uN = raw_input("Username")
pW = raw_input("Password")
usr1 = user(uN, pW)
usr1.createUsrPw()
Use raw_input. This looks like a Python 2 error, I don't think you're using Python 3
You also don't need to call str on a string literal. str("asdf") == "asdf"

python sintaxError: invalid sintax , else: [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I get this invalid syntax error:
File "./data_3.0.1.py", line 148
else:
^
SyntaxError: invalid syntax
When I try to run this function:
def funzione_aggiornamento_prezzi(titolo):
pprint ("titolo " + titolo)
#parametri per scaricare lo storico dei prezzi
params = {'item': titolo,
'frequency': 'TBT',
'dataDa':x_giorni_fa()}
try:
r = requests.get(myurl, params=params)
except:
pprint("Si e' verificato un errore")
else:
pprint(r.status_code)
pprint(r.url)
new_list = crea_lista(r)
#codice per scrivere su di un csv da una lista
nomen = "%s.TBT.csv" % (titolo)
csvfile = open(nomen, 'a')
reportwriter = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
#codice per scrivere su di un csv
# controllo del numero di rows nel file
with open(nomen,"r") as f:
reader = csv.reader(f,delimiter = ",")
data = list(reader)
row_count = len(data)
if row_count == 0:
for i in new_list:
da_appendere = new_list[i+1]
reportwriter.writerow(da_appendere)
csvfile.close()
#here I get the error
else:
with open(nomen, 'rb') as f:
last_timestamp = f.readlines()[-1].split(",")[0]
#codice per aggiungere al csv solo i nuovi dati
found_it = 0
for i in new_list:
if i == last_timestamp:
found_it = 1
if found_it == 1:
da_appendere = new_list[i+1]
reportwriter.writerow(da_appendere)
csvfile.close()
for i in lista_indici:
funzione_aggiornamento_prezzi(i)
I don't understand what is the problem... Maybe is something very easy but.. I don't really see it!!
Basically what I want to do is say to python if the csv file you're opening is empty simply attach the new list otherwise attach only the elements from the new list that are not already in the csv file you just opened
Thanks
The line csvfile.close() is outdented to be level with the if above it so terminates that if - so you have an else: when you are not in an if. You also need to fix the indentation of the line after the with

Syntax Error In Python Function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have checked everything that I could to try and fix this code. It may just be something stupid that I didn't see but I literally learned this language today. I keep getting invalid syntax. Can someone look over my code?
import glob, os, datetime, sys, time, shutil
def rename(dir1, dir2):
filenum = 1
date = time.strftime("%d%m%Y")
fileiter = glob.iglob(os.path.join(dir1, r'*.mp4')
for filen in fileiter:
print(filen);
filename = dir2 + filen + date + filenum + r'.mp4'
filedir1 = dir1 + filen
shutil.copy2(filedir1, dir2);
filedir2 = dir2 + filen
os.rename(filedir2, filename);
print("Copying Done!");
return;
starting_dir = input("Enter Input Directory: ")
if len(starting_dir) == 0:
print("Actually Enter Enter Something")
sys.exit()
output_dir = input("Enter Output Directory: ")
if len(output_dir) == 0:
print("Actually Enter Enter Something")
sys.exit()
rename(starting_dir, output_dir)
In python, if you don't specify a return it automatically returns None. In your code, the indentation of your return statement is off. It is enough to just remove it. Here is the correct code:
import glob, os, datetime, sys, time, shutil
def rename(dir1, dir2):
filenum = 1
date = time.strftime("%d%m%Y")
fileiter = glob.iglob(os.path.join(dir1, r'*.mp4'))
for filen in fileiter:
print(filen);
filename = dir2 + filen + date + filenum + r'.mp4'
filedir1 = dir1 + filen
shutil.copy2(filedir1, dir2);
filedir2 = dir2 + filen
os.rename(filedir2, filename);
print("Copying Done!");
starting_dir = input("Enter Input Directory: ")
if len(starting_dir) == 0:
print("Actually Enter Enter Something")
sys.exit()
output_dir = input("Enter Output Directory: ")
if len(output_dir) == 0:
print("Actually Enter Enter Something")
sys.exit()
rename(starting_dir, output_dir)

while true loop in python can't be stopped [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a problem with this loop in python:
i = 1
while True:
with open('/tmp/file.txt', 'r+') as f:
for line in f:
work = 'word1' + line + 'word2' + line + 'counter=' + str(i) + 'test'
result = Function()
if "statement" in result:
out = open('/tmp/result.txt', 'a+')
out.write(result)
out.close()
i = i + 10
else:
return i
I want first read file.txt line by line and then for each line count i till statement exists in result but this loop is infinitive... So I removed break and used return i instead. but no result
How can I tell the while True loop to be stopped when all lines from file.txt is read and for each line counter is completed?
UPDATE
what I want to process:
word1line1word2line1counter=1test
word1line1word2line1counter=2test
word1line1word2line1counter=3test
.
.
.
#`till my if condition is true` then
word1line2word2line2counter=1test
word1line2word2line2counter=2test
word1line2word2line2counter=3test
.
.
.
and so on
Thanks
I think you need to switch your loops around:
i = 1
with open('/tmp/file.txt', 'r+') as f:
for line in f:
result = ...
while "statement" in result:
with open('/tmp/result.txt', 'a+') as out:
out.write(result)
i += 10
result = ...
Although it is not at all clear what this algorithm is supposed to be doing
I found the answer:
out = open('/tmp/result.txt', 'a+')
with open('/tmp/file.txt', 'r+') as f:
for line in f:
i = 1
line=line.strip('\r\n ')
while True:
work = 'word1' + line + 'word2' + line + 'counter=' + str(i) + 'test'
print work
result = Function()
if "statement" in result:
out.write(result)
i += 10
else:
break
out.close()

Categories