88dax
88dax

Reputation: 307

What is the need of 'if statement' in this python code?

Even if I remove the 'if statement' from the code,I get the same output.

   word='pizza'
   begin=None
   while begin!='':
         begin=(raw_input('\nBegin:'))
         if begin:
             begin=int(begin)
             end = int(raw_input('End:'))
             print "word[",begin,":",end,"]"
             print word[begin:end]
   raw_input("\n\nPress enter key")

Upvotes: 0

Views: 62

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121524

To see if the user entered something other than the empty string.

>>> if '':
...     print 'empty'
...
>>> if 'I entered something':
...     print 'not empty'
...
not empty
>>> raw_input('just hit enter: ')  # just hinting 'enter' results in the empty string
just hit enter:
''

Upvotes: 1

elyase
elyase

Reputation: 40963

The if is used to make sure that the input of begin=(raw_input('\nBegin:')) is not empty. In pep 08, in "Programming Recommendations" section you can see that:

"For sequences, (strings, lists, tuples), use the fact that empty sequences are false."

Upvotes: 1

ATOzTOA
ATOzTOA

Reputation: 35950

The if checks if the user just pressed Enter.

If you remove the if, execute the program and just press Enter, you will see the output like this:

Begin:


Press enter key

If you enter 1 and press Enter, the output will be this:

Begin:1Begin:


Press enter key

Upvotes: 1

Related Questions