dyao
dyao

Reputation: 1011

2 codes work, the third doesn't

Beginner here. :)

So I want to achieve is this:

User enters a number. It spits out the ^3 of the number. If user enters a letter instead, it prints out a error message.

Code #1 works great:

def thirdpower():
try:
    number = int(raw_input("Enter a number : "))
    n=number**3
    print "%d to the 3rd power is %d" % (number,n)
except ValueError:
    print "You must enter an integer, please try again."
    thirdpower()

thirdpower()

But I want to try doing the same thing with a while statement since I want to practice with it. I know its a bit more verbose this way, but I think it's good practice nonetheless.

number=raw_input("Please Enter an integer")
while number.isalpha():
    print "You have entered letter. Please try again"
    number=raw_input("Please Enter an integer")

n=int(number)**3
print "%d to the 3rd power is %d" %(int(number), n)

My question is this. If I remove the number=raw_input("Please Enter an integer") under the while statement and replace it with a break, the code doesn't work.

Here is what I mean:

number=raw_input("Please Enter an integer")
while number.isalpha():
    print "You have entered letter. Please try again"
    break #This break here ruins everything :(

n=int(number)**3
print "%d to the 3rd power is %d" %(int(number), n)

Can anyone explain why?

Upvotes: 0

Views: 73

Answers (2)

Carter Sande
Carter Sande

Reputation: 1859

A break statement jumps out of a loop.

In this case, if the user types in a letter, the loop runs the print statement, then immediately reaches the break and terminates instead of looping over and over. (break is more useful when you put it inside an if statement that the program doesn't always reach.)

But using break doesn't stop the rest of your program from running, so Python still tries to run line 6. Since the number variable contains a letter, the program crashes when it tries to convert it to a number.

You were probably trying to end the program if the user typed in a letter. In that case, you could use the built-in sys module to do something like this:

import sys

number=raw_input("Please Enter an integer")
if number.isalpha():
    print "You have entered letter. Please try again"
    sys.exit()
#...

Upvotes: 2

khagler
khagler

Reputation: 4056

The break exits out of the while loop, at which point number is still whatever letter was entered so you get an error trying to make it an int.

Upvotes: 4

Related Questions