python

LAB: Interstate highway numbers


I have a assignment to write a program that takes a highway number as input and outputs whether the highway is primary or auxiliary, goes east/west, north/south, and if it is auxiliary, what primary highway is it serving. Here is my code:

highway_number = int(input(''))

if highway_number >= 1 and highway_number <= 99:
    prim = 'is primary,'
    if (highway_number % 2) == 0:
        print('I-', highway_number, prim, 'going east/west.')
    else:
        print('I-', highway_number, prim, 'going north/south.')
elif highway_number >= 100 and highway_number <= 999:
    aux = 'is auxiliary,'
    if (highway_number % 2) == 0:
        print('I-', highway_number, aux, 'serving I- %d, going east/west.' % (highway_number%100))
    else:
        print('I-', highway_number, aux, 'serving I- %d, going north/south.' % (highway_number%100))
else:
    print(highway_number, 'is not a valid interstate highway number.')

But if I run it. It adds a space between the "I-" and the highway number. Screenshot


Solution

  • Your issue is in the part where you print: Using print(string, string) your writing out 2 seperate stings, which per default by python will be seperated by a blank space. Your going to have to append the strings which can easily be done by a + print(string + string). BE sure to parse numbers etc first using str(toparse).

    For the second part printing a space between I- and the number its because in your string you have a space I- %d. Yust change it to I-%d

    Hope this helps :D

    In complete

    highway_number = int(input(''))
    
    if highway_number >= 1 and highway_number <= 99:
        prim = 'is primary,'
        if (highway_number % 2) == 0:
            print('I-' + str(highway_number), prim, 'going east/west.')
        else:
            print('I-' + str(highway_number), prim, 'going north/south.')
    elif highway_number >= 100 and highway_number <= 999:
        aux = 'is auxiliary,'
        if (highway_number % 2) == 0:
            print('I-' + str(highway_number), aux, 'serving I-%d, going east/west.' % (highway_number%100))
        else:
            print('I-' + str(highway_number), aux, 'serving I-%d, going north/south.' % (highway_number%100))
    else:
        print(highway_number, 'is not a valid interstate highway number.')