Back

Converting data types

Q1. Get this code working in Python:

# Cannot convert this data into a number

myData = input('Please enter your data >>> ')

try:
    myNumber = int(myData)
except:
    print ('You cannot convert',myData,'into to a number.')
else:
    print('You have converted',myData,'into a number')
finally:

    print('Goodbye')

Q2. Run this program with a range of different data types. Describe what this program does.
Q3. Get this code working in Python:

# Cannot convert this data into a number

myData = False
while myData == False:
    myString = input("Please enter an integer >>> ")
    try:
        n = int(myString)
        myData = True
    except:
        print ("This is not an integer!")
    else:
        print('You have entered an integer.')

Q4. Describe carefully how this program works.
Q5. Modify this program so that it accepts any number, whether an integer or a float. The program should display 'Goodbye' after every incorrect data type entry or when a correct data type has finally been entered.
Q6. Test your program in Q5 with a range of data types and data to prove it works as intended.

Back