0

I am trying to make it that the user will get an error message back if they enter alphabetical letters or non-integer numbers, and when an integer is entered the program will proceed to show this integer number being squared and cubed. My teacher doesn't want any 'breaks' in code or any ValueErrors.

print("Squaring and cubing integer program has started") #Introduction of program for user
UserNumber=input("Enter an integer to be raised to the power of 2 and 3: ") #Asks user to input an integer, that will then be raised to the power of 2 and 3
while '.' in UserNumber or UserNumber.isalpha(): #Error-trap to test if input contained letters of the alphabet or contains decimal point
  print("You have not entered an integer. Try again and enter an integer!") #Alert for user to inform that their entry was invalid (not an integer)
  UserNumber=input("Enter an integer to be raised to the power of 2 and 3: ")  #Asks user again to enter an integer, if they did not previously.
print(int(UserNumber), " is the integer you entered.") #Displays to user their inital integer
print(int(UserNumber), " squared is ", int(UserNumber)**2) #Displays to user their input integer squared
print(int(UserNumber), " cubed is ", int(UserNumber) **3 ) #Displays to user their input integer cubed
print("Calculations are now finished.") #Output to show program has ended
twasbrillig
  • 17,084
  • 9
  • 43
  • 67
  • 1
    Your teacher doesn't want you to do the pythonic thing (`try/except` ["EAFP" programming](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#eafp-vs-lbyl)) and forces you to use C-style "LBYL" coding techniques? What kind of school is this? – Tim Pietzcker Oct 18 '14 at 05:44
  • 1
    nah its because we havnt learned it yet –  Oct 18 '14 at 05:46
  • This question has tags for both Python 2.7 and Python 3.x. Which version are you using? – twasbrillig Oct 18 '14 at 05:47
  • sorry the newest one? whichever one that is i dont really know. –  Oct 18 '14 at 05:49

4 Answers4

3

2.0 is not an integer; it is a float. float in Python is similar to the standard IEEE 754 Floating Point (if platform supports IEEE 754 Floating Point then Python probably uses it) that have limited precision. Integers in Python have infinite precision (until you run out of memory):

>>> i = 123456789012345678901234567890
>>> i ==  123456789012345678901234567890
True
>>> f = i * 1.0 # make it a float
>>> f.is_integer() # check whether it is a whole number
True
>>> f ==  123456789012345678901234567890
False

Never mix float and int unless you know that it won't change the result in your case e.g., 2 == 2.0 but as the example shows it can be false for larger numbers.

Your teacher probably expects that you find .is_integer() method:

>>> 2.0 .is_integer()
True
>>> 2.1 .is_integer()
False

See also, How to check if a float value is a whole number.

To convert '2.0' to a float, you could call float() function:

#!/usr/bin/env python3
while True:
    try:
         f = float(input('Enter a number: '))
    except ValueError:
         print('Try again')
    else:
         break # got a number

It is the correct way to get a number from stdin in Python. If your teacher forbids using ValueError and break then you could use a regular expression:
if re.match("^[+-]? *(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$", input_string): that accepts 20e-1 == 2.0 == 2. See Extract float/double value.

To test whether the input is not empty and contains only decimal digits i.e., to check whether it is a nonnegative integer, you could use input_string.isdecimal() method if calling int(input_string) and catching ValueError is forbidden. See How do I check if a string is a number in Python?.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

The OP's question is based on a class assignment. This answer assumes that the solution must fit the rules as decided by the teacher.

Just get rid of trailing zeros and then get rid of the final decimal point:

UserNumber = UserNumber.rstrip('0').rstrip('.')

Place this line after the input statement but before you perform tests:

print("Squaring and cubing integer program has started") #Introduction of program for user
UserNumber=input("Enter an integer to be raised to the power of 2 and 3: ") #Asks user to input an integer, that will then be raised to the power of 2 and 3
UserNumber = UserNumber.rstrip('0').rstrip('.')
while '.' in UserNumber or UserNumber.isalpha(): #Error-trap to test if input contained letters of the alphabet or contains decimal point
    print("You have not entered an integer. Try again and enter an integer!") #Alert for user to inform that their entry was invalid (not an integer)
    UserNumber=input("Enter an integer to be raised to the power of 2 and 3: ")  #Asks user again to enter an integer, if they did not previously.
    UserNumber = UserNumber.rstrip('0').rstrip('.')
print(int(UserNumber), " is the integer you entered.") #Displays to user their inital integer
print(int(UserNumber), " squared is ", int(UserNumber)**2) #Displays to user their input integer squared
print(int(UserNumber), " cubed is ", int(UserNumber) **3 ) #Displays to user their input integer cubed
print("Calculations are now finished.") #Output to show program has ended
John1024
  • 109,961
  • 14
  • 137
  • 171
  • Can you incorporate that into my code? im fairly new to python so dont know much...sorry about that –  Oct 18 '14 at 05:39
  • actually for some reason after i enter for example a letter, then after i write in 2.0, it says that it is not an integer. How can i fix this? –  Oct 18 '14 at 05:52
  • And i was wondering if there was anything like a .isfloat code? –  Oct 18 '14 at 06:03
  • (A) Do you want to remove all letters? Or just letters that precede the number? (B) What kind of objects do you want `isfloat` to test? Test numbers to see if they are float or integer? – John1024 Oct 18 '14 at 06:12
  • A) i dont want to remove any numbers B) i want to check if the users input is anything but an integer, so letters, and decmials (not decimals like 2.0, 1.0 as they equal to 2,1 respectively). If it is an integer the output will print the integer enters squared and cubed. but if the user enters a letter or decimal number then a error will come up to enter an integer, it is then up to them to enter an integer or not. If they do it will procedd to output. If they dont enter an integer, the error will come back again. Hope this is clear enough –  Oct 18 '14 at 06:30
  • I am not understanding you. Let's get specific. Is there some way that this code is not meeting your requirements? Is there some user input to the code in my answer that produces output that you don't want? What, precisely, is that input? – John1024 Oct 18 '14 at 06:55
  • ok if i input 2.0 it works first try, however if i input 'a' for example, then on my second try enter 2.0, it doesnt work. –  Oct 18 '14 at 06:58
  • @Sampson I cannot reproduce that. If I enter `a` the first time and `2.0` on the retry, it accepts the 2.0 and prints the squares and cubes. – John1024 Oct 18 '14 at 07:37
  • @Sampson I had an idea: note that the new line that I added to your code gets added in __two__ places. If the first was included but not the second, the result would be the behavior that you see. See my code for where that line goes (or copy-and-paste the code from my answer). – John1024 Oct 18 '14 at 08:05
0

A) i dont want to remove any numbers B) i want to check if the users input is anything but an integer, so letters, and decmials (not decimals like 2.0, 1.0 as they equal to 2,1 respectively)

According to your description, you can use re module to implement your work:

import re


def is_integer(num):
    s = str(num)
    return re.match('^(-?\d+)(\.[0]*)?$', s) is not None


print is_integer(1123123)  # True
print is_integer(1123123.)  # True
print is_integer(1123123.00000)  # True
print is_integer(1123123.00100)  # False
endless
  • 114
  • 1
  • 2
  • 5
-1
x = 2.0
try:
    x = int(x)
except ValueError:
    pass
return x

It's the only acceptable way in Python, if your teacher doesn't understand exceptions he shouldn't teach programming in Python (honestly, he shouldn't teach programming at all)

Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93