Converting data types - Answers
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. This program asks the user to enter some data. It then tries to convert the data into an integer. If it fails, it displays one message and if it succeeds, it displays the message in the else part of the construction. It displays 'Goodbye' whether or not an integer is entered.
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. This program continually asks the user to enter an integer until one is entered. If an integer is entered, 'You have entered an integer.' is displayed. Otherwise, 'This is not an integer!' is displayed and the user is asked to enter an integer again.
Q5 - Q6
# Cannot convert this data into a number
myData = False
while myData == False:
myString = input("Please enter a number >>> ")
try:
n = float(myString)
myData = True
except:
print ("This is not a number!")
else:
print('You have entered a number.')
finally:
print('Goodbye')