1
\$\begingroup\$

My code:

# Filename: P05_Numbers.py
# Author: Joseph Chua
# Date: 10/24/2016
# Purpose: Evaluating an input and comparing them.
# Other: http://repeatercreeper.me

#========================================================#
# Variables/Input                                        #
#========================================================#
dataType1 = eval(input("Data #1: "), {})
dataType2 = eval(input("Data #2: "), {}) 
#========================================================#
if type(dataType1) == type(dataType2):
    print('''
       =============== Data Types ==================
       = Data Type #1: %s
       = Data Type #2: %s
       =============================================

       =============== Extra Details ===============
       = Data Type Same? => True
       = Operation       => Addition
       = Result          => %d
       =============================================
    ''' % (type(dataType1), type(dataType2), (dataType1 + dataType2)))
elif type(dataType1) != type(dataType2):
    print('''
       =============== Data Types ==================
       = Data Type #1: %s
       = Data Type #2: %s
       =============================================

       =============== Extra Details ===============
       = Data Type Same? => False
       = Operation       => Multiplication
       = Result          => %d
       =============================================
    ''' % (type(dataType1), type(dataType2), (dataType1 * dataType2)))
else:
    print("You're doing something wrong!")

My Teacher's code:

# File Name: KEY P5b Numbers
# Author: XXXXXXXX
# Date: 10/24/2016
# Purpose: To input two different numbers then have Python compare the numbers in a For Loop.

#------------------------------------------------------------------------------------------------

for i in range(0,3):

    num1 = float(input("Please input a Number, "))
    if num1 == int(num1):
        num1 = int(num1)
        print('This value is an integer!')
    elif num1 == float(num1):
        print('This value is a decimal!')
    else:
        print('YOUR INPUT WAS NO A NUMBER; Guess again')

#The above if, elif, else is to determine whether the input is a number or a letter

#If a number then what type? Decimal which is a float or an Integer which is a whole number


        num2 = float(input("Please input a Number, "))
        if num2 == int(num2):
            num2 = int(num2)
            print('This value is an integer!')
        elif num2 == float(num2):
            print('This value is a decimal! ')
        else:
            print('YOUR INOUT WAS NOT A NUMBER; Guess again')

#We are now ADDING together the numbers if they are the same data type

#Meaning Integers with Integers & Numbers with Numbers
        if num1 == int(num1) and int(num2): #Comparing values
            print('both values are integers')
            num3 = num1 + num2
            print(num3)
        elif num1 == float(num1) and num2 == int(num2):
            print('first value is a float and the second value is a integer')

            num3 = num1 * num2
            print(num3)
        elif num1 == int(num1) and num2 == float(num2):
            print('first value is a integer and the second value is a float')

            num3 = num1 * num2
            print(num3)
        elif num1 == float(num1) and float(num2): #Comparing Values

            print('both values are floats')
        else:
            print('Your input is not valid.')

So I'm just looking for improvements that can be done with my code.

EXTRA: One of them is to actually be able to detect whether it's a string or not a string without destroying my program. I have tried a try catch valueerror thingy and it still somehow throws something else.


Instructions are as follows:

Activity 1: Write the Python code to allow the input of two numbers and then compare the datatypes.

  • a) Within a FOR loop that iterates three (3) times, allow the user to input two numeric values, then compare the values to see if the datatypes are the same (integer or float) within an IF…ELIF…ELSE control structure, printing the datatypes and results.
    1. Allow the user to input the first numeric value.
      • Validate the input as a value.
    2. Allow the user to input the second numeric value.
      • Validate the input as a value.
    3. Using a control structure (IF...ELIF...ELSE), compare the two numeric values.
      • If the values are of the same datatype, print the datatype, add the values together and print the result.
      • If the values are of different datatypes, print the datatype of each value, multiple the values together and print the result.

That's the exact same instructions that is written on the docx file.

\$\endgroup\$
  • \$\begingroup\$ Could you clarify whether the code is supposed to be Python 2 or Python 3? \$\endgroup\$ – 200_success Oct 28 '16 at 23:21
  • \$\begingroup\$ @200_success It's for Python 3. \$\endgroup\$ – RepeaterCreeper Oct 28 '16 at 23:22
  • \$\begingroup\$ Your teacher needs to think of some more meaningful programming exercises. We're not supposed to review other people's code, but I have to point out that num1 = float(…) followed by elif num1 == float(num1) is silly, because it is converting a float to a float. \$\endgroup\$ – 200_success Oct 28 '16 at 23:31
  • \$\begingroup\$ @200_success Oh. I thought this was the place for code improvements sorry. This will be my last one. \$\endgroup\$ – RepeaterCreeper Oct 28 '16 at 23:33
  • \$\begingroup\$ Posting your own code for review is absolutely OK! Posting code that someone else wrote is not. Including the teacher's solution for comparison is OK, as long as you understand that answers are supposed to focus on your code, not the teacher's. \$\endgroup\$ – 200_success Oct 28 '16 at 23:35
4
\$\begingroup\$

This assignment, like your previous question, is a poorly conceived programming exercise. Given two values, either they have the same type, or they don't. I see that this could be a valid approach:

if type(value1) == type(value2):
    # Do something
else:
    # Do something else

However, I don't see any room for an if-elif-else chain.

if type(value1) == type(value2):
    # Do something
elif type(value1) != type(value2):
    # Do something else
else:
    # How is this code possibly reachable?

Your teacher's solution also uses an if-elif-else chain that doesn't make sense. Can you figure out why?


Your variables are confusingly named: dataType1 and dataType2 suggest that they are types (e.g. int or float) rather than numbers. Furthermore, PEP 8, the official Python style guide, recommends lower_case_with_underscores for variable names.


The biggest problem with your solution is that it uses eval(). Calling eval() on user input introduces an arbitrary code execution vulnerability. Observe this proof-of-concept exploit:

$ python3 cr156677.py
Data #1: __import__('os').system('cat /etc/hosts')
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1   localhost
255.255.255.255 broadcasthost
::1             localhost 
Data #2: _
\$\endgroup\$
  • \$\begingroup\$ Ah, I think I see why the else doesn't make sense. That's because as your comment states, it will never be able to reach that place. Unless I specify what type I'm looking for. E.g: type(value1) == str \$\endgroup\$ – RepeaterCreeper Oct 29 '16 at 0:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.