Print else only once? [duplicate] - python

This question already has answers here:
Print out message only once from the for loop
(4 answers)
Closed 5 years ago.
how do I get my else print to only print once instead of for every row that the string doesn't exist? I tried moving it around by tabbing back a couple of layers but it doesn't work. I understand the logic, I but don't know how to limit it. I'm adding a little bit at a time to my parsing scripts for practice, learning as I go, but this one got me. Thanks!
import csv
# Testing finding something specifical in a CSV, with and else
testpath = 'C:\Users\Devin\Downloads\users.csv'
developer = "devin"
with open (testpath, 'r') as testf:
testr = csv.reader(testf)
for row in testr:
for field in row:
if developer in row:
print row
else:
print developer + " does not exist!"

In Python, you can have an else clause attached to your for loop. For example
>>> for i in range(10):
... if i == 5: break # this causes the else statement to be skipped
... else:
... print 'not found'
...
Note 5 was found so the else statement is not executed
>>> for i in range(10):
... if i == 15: break
... else:
... print 'not found'
...
not found
See the documentation on for statements
A break statement executed in the first suite terminates the loop
without executing the else clause’s suite. A continue statement
executed in the first suite skips the rest of the suite and continues
with the next item, or with the else clause if there is no next item.

See Gibson's answer first. You can do this:
for row in testr:
found = False
for field in row:
if developer in row:
print row
found = True
break
if found: break
else:
print developer + " does not exist!"
You can also omit the found flag (as suggested by Jean-François Fabre in the comment) but this makes a bit hard to understand imo (I had to compile in my head):
for row in testr:
for field in row:
if developer in row:
print row
# We found the developer. break from the inner loop.
break
else:
# This means, the inner loop ran fully, developer was not found.
# But, we have other rows; we need to find more.
continue
# This means, the else part of the inner loop did not execute.
# And that indicates, developer was found. break from the outer loop.
break
else:
# The outer loop ran fully and was not broken
# This means, developer was not found.
print developer, "does not exist!"

Related

Exceptions and Output

I have problem when calling my function, I am receiving bad output as I will explain later in the text.
These are the resources I am working with:
Main_Building=[10,12,14,17,21,25,30,36,43,52,62,74,89,107,128,154,185,222,266,319,383,460,552,662,795,954,1145,1374,1648,1978]
Barracks=[16,19,23,28,33,40,48,57,69,83,99,119,143,171,205,247,296,355,426,511,613,736,883,1060,1272]
Stables=[20,24,29,35,41,50,60,72,86,103,124,149,178,214,257,308,370,444,532,639]
Workshop=[24,29,35,41,50,60,72,86,103,124,149,178,214,257,308]
Blacksmith=[19,23,27,33,39,47,57,68,82,98,118,141,169,203,244,293,351,422,506,607]
Market=[10,12,14,17,21,25,30,36,43,52,62,74,89,107,128,154,185,222,266,319,383,460,552,662,795]
Axe=[6,7,9,10,12,15,18,21,26,31,37,45,53,64,77,92,111,133,160,192,230,276,331,397,477,572,687,824,989,1187]
Clay_Pit=[6,7,9,10,12,15,18,21,26,31,37,45,53,64,77,92,111,133,160,192,230,276,331,397,477,572,687,824,989,1187]
Mine=[6,7,9,10,12,15,18,21,26,31,37,45,53,64,77,92,111,133,160,192,230,276,331,397,477,572,687,824,989,1187]
Settler_House=[5,6,7,9,10,12,15,18,21,26,31,37,45,53,64,77,92,111,133,160,192,230,276,331,397,477,572,687,824,989]
Warehouse=[6,7,9,10,12,15,18,21,26,31,37,45,53,64,77,92,111,133,160,192,230,276,331,397,477,572,687,824,989,1187]
Wall=[8,10,12,14,17,20,24,29,34,41,50,59,71,86,103,123,148,177,213,256]
Here is my code:
def buildings(points):
for i in range(0,30):
try:
if Main_Building[i]>=points:
del Main_Building[i:]
if Barracks[i]>=points:
del Barracks[i:]
if Stables[i]>=points:
del Stables[i:]
if Workshop[i]>=points:
del Workshop[i:]
if Blacksmith[i]>=points:
del Blacksmith[i:]
if Market[i]>=points:
del Market[i:]
if Axe[i]>=points:
del Axe[i:]
if Clay_Pit[i]>=points:
del Clay_Pit[i:]
if Mine[i]>=points:
del Mine[i:]
if Settler_House[i]>=points:
del Settler_House[i:]
if Warehouse[i]>=points:
del Warehouse[i:]
if Wall[i]>=points:
del Wall[i:]
except IndexError:
continue
The problem is when the it comes to Condition of Blacksmith, it looks to me as the condition is only passed, and the same for others continuing to Wall condition. The condition is determining where to stop and delete rest of the list for further use. The lists are different lengths so I used simple exception for when it is out of range it just skips and continue to next condition.
Suggested output when def buildings(100):
Blacksmith=[19,23,27,33,39,47,57,68,82,98]
Actual output is whole list without any change. The same applies to continuing condition.
What I tried:
I tried to restart Python but that unfortunately was not it.
If I misspelled the variable name.
Redoing spacing on every condition.
Maybe solution but not effective, adding to each condition try exception ?(Not a good Idea in my opinion).
Why it skips the conditions ?
Thank you for your help and time.
Continue will return to the beginning of current loop and grab next index. This means that if an error occurred halfway, the last half is skipped. It was also quite lengthy. Here is my solution.
data = [Main_Building, Barracks, Stables, Workshop, Blacksmith, Market, Axe, Clay_Pit, Mine, Settler_House, Warehouse, Wall]
def buildings(points):
for building in data: # loop through each building seperately, shortens code and removes arbitrary loop number
for point in building: # loop through each buildings index, same as your code
if point >= points:
del building[building.index(point):]
buildings(20)
print data
If any error occured between try-except, Python will pass or continue all of the codes between try-except.
try:
a = int(input("integer: "))
print("print this")
print("print that")
except:
pass
Output:
>>>
integer: ab
>>>
See that print this and print that not printed. You should catch the errors one by one.
try:
a = int(input("integer: "))
except:
pass
print("print this")
print("print that")
>>>
integer: ab
print this
print that
>>>

Please help me better understand this one "except"conditional line

I'm about a couple weeks into learning Python.
With the guidance of user:' Lost' here on Stackoverflow I was able to figure out how to build a simple decoder program. He suggested a code and I changed a few things but what was important for me was that I understood what was happening. I understand 97% of this code except for the except: i += 1 line in the decode(). As of now the code works, but I want to understand that line.
So basically this code unscrambles an encrypted word based on a specific criteria. You can enter this sample encrypted word to try it out. "0C1gA2uiT3hj3S" the answer should be "CATS"
I tried replacing the except: i += 1 with a Value Error because I have never seen a Try/Except conditional that just had an operational and no Error clause. But replacing it with Value Error created a never ending loop.
My question is what is the purpose of writing the except: i += 1 as it is.
'Lost' if you're there could you answer this question. Sorry, about the old thread
def unscramble(elist):
answer = []
i = 0
while i <= len(elist):
try:
if int(elist[i]) > -1:
i = i + int(elist[i]) + 1
answer.append(elist[i])
except:
i += 1
return "".join(answer)
def boom():
eword = input("paste in your encrypted message here >> ")
elist = list(eword)
answer = unscramble(elist)
print (answer)
clear()
boom()
The purpose is to advance i by one, skipping the current character in case the cast to int fails, i.e. if elist[i] is not a digit.
There are a couple of errors, than can occur inside the try-Block:
i is out of index, because the while loop runs one index to far.
elist[i] is not a number, which leads to an ValueError
i = i + int(elist[i]) + 1 gets to big, and the next index access leads also to an IndexError
In either way, the except-clause will ignore the next character. And the loop goes on.
An correct implementation wouldn't need any exceptions:
def unscramble(elist):
answer = []
i = 0
while i < len(elist):
i += int(elist[i]) + 1
answer.append(elist[i])
i += 1
return "".join(answer)

Python supports `else` in loop. Is there a similar feature in Ruby?

In Python, the else block will be executed unless the loop is broke:
for person in people:
if is_a_coder(person): break
# ... more code ...
else: # nobreak
print('There is no coder.')
How can I do it in Ruby?
Just use and:
people.each do |person|
break if is_a_coder(person)
# more code
end and puts 'There is no coder.'

Can't get my loop & match to append to correct list

I´m experiencing problems with my code.
I can´t get it to append to the list not_found as well as it loops twice for some reason.
Can anyone point me in the right direction? The match works for my_track, but it doesn't when it doesn't match.
# coding: utf-8
#!/usr/bin/env python
import spotimeta
import sys
import time
my_tracks = raw_input("Please enter a sentence: ").title().split()
playlist = []
real_playlist = []
not_found = []
def check_track(track_name, my_track, track_href):
if track_name == my_track:
playlist.append(track_href)
return 1
# make sure the user does not input a single word as input
if (len(my_tracks) > 1):
path = my_tracks[1]
else:
sys.exit("Invalid input, please enter a sentence.")
# let's search
for my_track in my_tracks:
match = 0
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if not match == 1:
try:
match = check_track(result["name"],my_track,result["href"])
except Exception, e:
error = "not available"
else:
if data['total_results'] > 0:
not_found.append(my_track)
You should try debugging it. One of the simplest ways of debugging is add the lines:
import pdb
pdb.set_trace()
Then when you run the script it will stop at the set_trace line in the debugger.
Check out http://docs.python.org/library/pdb.html for more information.
From my understanding you're trying to do something like:
for my_track in my_tracks:
print "Searching for '%s'\n" % (my_track),
data = spotimeta.search_track(my_track)
for result in data['result']:
if result['name'] == my_track:
playlist.append(result['href'])
elif data['total_results'] > 0:
not_found.append(my_track)
Will this more or less work for you?
Please help me to understand.
Right off the bat, I'm noticing two things.
First, you're checking data['total_results'] a bit late; if the total results value is greater than zero (wait, what?), then you want to add it to the list immediately and move on without parsing the data. I would, after the call from spotimeta.search_track(), check to see if this is the data you don't want (then subsequently add it into the list).
Second, I'm confused about the intention of your for loop. If you're going through it to only find one item, then you can use the in statement (my_track in result).

Executing Multiple Lines in Python

When Python is first installed, the default setting executes users' code input line-by-line. But sometimes I need to write programs that executes multiple lines at once. Is there a setting in Python where I can change the code execution to one block at once? Thanks
>>> if (n/2) * 2 == n:;
print 'Even';
else: print 'Odd'
SyntaxError: invalid syntax
When I tried to run the above code, I got an invalid syntax error on ELSE
Your indentation is wrong. Try this:
>>> if (n/2) * 2 == n:
... print 'Even'
... else: print 'Odd'
Also you might want to write it on four lines:
>>> if (n/2) * 2 == n:
... print 'Even'
... else:
... print 'Odd'
Or even just one line:
>>> print 'Even' if (n/2) * 2 == n else 'Odd'
One step towards the solution is to remove the semicolon after the if:
if True:; print 'true'; print 'not ok'; # syntax error!
if True: print 'true'; print 'ok'; # ok
You cannot have an else in the same line because it would be ambiguous:
if True: print 't'; if True: print 'tt; else: ... # <- which if is that else for??
It is also clearly stated in the docs that you need a DEDENT before the else statement can start.
Since python 2.5 you can do one line ifs
print ('Even' if n % 2 == 0 else 'Odd')
Still to answer your question you can either:
1. enter the code properly without syntax errors and your blocks will be executed as blocks regardless if they span multiple lines or not, even in interactive shell. See tutorials in dive into python
2. write code in the script and execute that script using either command line or some IDE (idle, eclipse, etc..)
One of the idea behind python is to prefer multiple lines and to aim for uniform formatting of source, so what you try to do is not pythonic, you should not aim to cram multiple statements into single line unless you have a good reason.
print n % 2 == 0 and 'Even' or 'Odd'
:-)

Categories

Resources