473,799 Members | 3,310 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why do I require an "elif" statement here?

Jim
Could somebody tell me why I need the "elif char == '\n'" in the
following code?
This is required in order the pick up lines with just spaces in them.
Why doesn't
the "else:" statement pick this up?

OLD_INDENT = 5 # spaces
NEW_INDENT = 4 # spaces

print 'Reindent.py:'
print '\nFrom file %s' % infile
print 'Change %i space indentation to %i space indentation.' % (
OLD_INDENT, NEW_INDENT)
print 'And place revised file into %s' % outfile

whitespace = ' '
n = 0
nline = 0

for line in input.readlines ():
nline += 1
# Only look at lines that start with a space.
if line[0] == whitespace:
i = 0
for char in line:
i += 1
if char == whitespace:
pass
elif char == '\n': # Why do I need this for a
blank line with only spaces?
output.write(li ne)
break
else: # Why doesn't the blank line
get picked up here?
x = line.count(whit espace*OLD_INDE NT,0,i)
# Reindent lines that have exactly a multiple of
OLD_INDENT.
if x 0 and (i-1)%OLD_INDENT == 0:
output.write(wh itespace*NEW_IN DENT*x+line.lst rip())
n += 1
break
else:
output.write(li ne)
break
else:
output.write(li ne)

input.close()
output.close()
print 'Total number of %i lines reindented out of %i lines.' % (n,
nline)

Aug 4 '06
13 1935
No offense. I didn't mean there was anything wrong with your way, just
that it wasn't "neat". By that, I meant, you were still using lots of
for loops and if blocks.

Justin Azoff wrote:
danielx wrote:
I'm surprised no one has mentioned neat-er, more pythonic ways of doing
this. I'm also surprised no one mentioned regular expressions. Regular
expressions are really powerful for searching and manipulating text.
I suppose I put those things too close together. I meant I was
surprised for each of the two Separate (non)occurances .
[snip]

I'm surprised you don't count my post as a neat and pythonic way of
doing this. I'm also surprised that you mention regular expressions
after neat and pythonic. While regular expressions often serve a
purpose, they are rarely neat.
Anyway, here's my solution, which does Not use regular expressions:

def reindent(line):
## we use slicing, because we don't know how long line is
head = line[:OLD_INDENT]
tail = line[OLD_INDENT:]
## if line starts with Exactly so many spaces...
if head == whitespace*OLD_ INDENT and not tail.startswith (' '):
return whitespace*NEW_ INDENT + tail
else: return line # our default
[snip]

This function is broken. Not only does it still rely on global
variables to work, it does not actually reindent lines correctly. Your
It's just an illustration.
function only changes lines that start with exactly OLD_INDENT spaces,
ignoring any lines that start with a multiple of OLD_INDENT.
Maybe I misread, but that's what I thought he wanted. Did you not see
my code comments expressing that very intent? Anyway, it wouldn't be
that hard to modify what I gave to do multiple replacement: just add a
recursive call.
>
--
- Justin
Aug 6 '06 #11
danielx wrote:
No offense. I didn't mean there was anything wrong with your way, just
that it wasn't "neat". By that, I meant, you were still using lots of
for loops and if blocks.

Justin Azoff wrote:
danielx wrote:
I'm surprised no one has mentioned neat-er, more pythonic ways of doing
this. I'm also surprised no one mentioned regular expressions. Regular
expressions are really powerful for searching and manipulating text.

I suppose I put those things too close together. I meant I was
surprised for each of the two Separate (non)occurances .
And what would regexes give you? A Pythonic way of calculating the
number of leading spaces??? N.B. in your (mis)reading of the OP's
intent, you don't need/use the number of leading spaces.

Anyway, here's my solution, which does Not use regular expressions:
>
def reindent(line):
## we use slicing, because we don't know how long line is
head = line[:OLD_INDENT]
tail = line[OLD_INDENT:]
## if line starts with Exactly so many spaces...
if head == whitespace*OLD_ INDENT and not tail.startswith (' '):
return whitespace*NEW_ INDENT + tail
else: return line # our default
[snip]

This function is broken. Not only does it still rely on global
variables to work, it does not actually reindent lines correctly. Your

It's just an illustration.
An illustration of ... what?
>
function only changes lines that start with exactly OLD_INDENT spaces,
ignoring any lines that start with a multiple of OLD_INDENT.

Maybe I misread, but that's what I thought he wanted.
(a) Such a requirement is rather implausible.
(b) No "maybe":

x = line.count(whit espace*OLD_INDE NT,0,i)
# Reindent lines that have exactly a multiple of
OLD_INDENT.
if x 0 and (i-1)%OLD_INDENT == 0:
output.write(wh itespace*NEW_IN DENT*x+line.lst rip())

Did you not see
my code comments expressing that very intent?
Those comments merely documented the brokenness.
Anyway, it wouldn't be
that hard to modify what I gave to do multiple replacement: just add a
recursive call.
.... which would make it uglier.

Aug 6 '06 #12
"sp*****@gmail. com" <sp*****@gmail. comwrites:
>-------------------------------
whitespace = " "
old_indent = 3
new_indent = 5

x = " starts with 3 spaces"

x = x.replace(white space*old_inden t, whitespace*new_ indent)
-------------------------------

In this example though, it will replace the 3 spaces no matter where
they are at, not just in the beginning... still, it's probably more
practical for most use cases.
You'd corner it with:

if x.startswith(' '*3): x=x.replace(' '*3,' '*5,1)
--
John Savage (my news address is not valid for email)
Aug 7 '06 #13

John Savage wrote:
"sp*****@gmail. com" <sp*****@gmail. comwrites:
-------------------------------
whitespace = " "
old_indent = 3
new_indent = 5

x = " starts with 3 spaces"

x = x.replace(white space*old_inden t, whitespace*new_ indent)
-------------------------------

In this example though, it will replace the 3 spaces no matter where
they are at, not just in the beginning... still, it's probably more
practical for most use cases.

You'd corner it with:

if x.startswith(' '*3): x=x.replace(' '*3,' '*5,1)
As others have stated, this will only get lines that start with only 1
set of "old_indent " and not multiples of "old_indent ".
--
John Savage (my news address is not valid for email)
Aug 15 '06 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1740
by: Raymond Arthur St. Marie II of III | last post by:
Del's "except"ional PEP Rejection Ladieees and Gentilmen and Pyth-O-neers of all ages. Step right up. Don't be shy. Come one come all. Be the first on your block TO GROK *THE* one *THE* only Exception you won't find
26
14161
by: Joe Stevenson | last post by:
Hi all, I skimmed through the docs for Python, and I did not find anything like a case or switch statement. I assume there is one and that I just missed it. Can someone please point me to the appropriate document, or post an example? I don't relish the idea especially long if-else statements. Joe
27
3081
by: Ron Adam | last post by:
There seems to be a fair amount of discussion concerning flow control enhancements lately. with, do and dowhile, case, etc... So here's my flow control suggestion. ;-) It occurred to me (a few weeks ago while trying to find the best way to form a if-elif-else block, that on a very general level, an 'also' statement might be useful. So I was wondering what others would think of it.
40
3050
by: Steve Juranich | last post by:
I know that this topic has the potential for blowing up in my face, but I can't help asking. I've been using Python since 1.5.1, so I'm not what you'd call a "n00b". I dutifully evangelize on the goodness of Python whenever I talk with fellow developers, but I always hit a snag when it comes to discussing the finer points of the execution model (specifically, exceptions). Without fail, when I start talking with some of the "old-timers"...
13
7246
by: darthbob88 | last post by:
Problem: I wish to run an infinite loop and initialize a variable on each iteration. Sort of like, "Enter Data", test it, "No good!", "Next Try?", test it, etc. What I've tried is simply while 1: var1 = raw_input, test var1, then run through the loop again. What results is var1 gets and keeps the first value it receives. If this is in the FAQ, my apologies, I did not find it. Thank you in advance.
1
2042
by: arnold | last post by:
Hi, I've been knocking my head against the wall trying to create an XSL transform to perform "normalizations" of a set of XML files that have a common structure. % XML file before transform
7
12724
by: Girish Sahani | last post by:
Hi, Please check out the following loop,here indexList1 and indexList2 are a list of numbers. for index1 in indexList1: for index2 in indexList2: if ti1 == ti2 and not index1 != indexList1.pop(): index1+=1 index2+=1 continue
8
20282
by: aine_canby | last post by:
>>v = raw_input("Enter: ") Enter: kjjkj Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'kjjkj' In my program I need to be able to enter char strings or int strings on the command line. Then I use an if-elif structure to establish which is which. For example -
11
1540
by: Stef Mientki | last post by:
hello, Is there some handy/ nice manner to view the properties of some variable ? As a newbie, I often want to see want all the properties of a var, and also some corner values (large arrays) etc. Probably it's not so difficult, but I don't see how to distinguish for example between a string and an array. An array has a shape, a string not etc.
0
9541
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10485
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10252
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10231
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10027
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9073
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7565
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4141
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.