1

This is my first time using python and I'm having trouble getting it to print the way I want. I would like the output to be side by side. It might be because I'm tired, but I cant seem to figure this out.

My Code:

def cToF():
    c = 0
    while c <= 100:
        print(c * 9 / 5 + 32)
        c += 1
def fToC():
    f = 32
    while f <= 212:
        print((f - 32) / 1.8)
        f += 1






print (cToF(),fToC())

OUTPUT:

all of the numbers from cToF()
all of the numbers from fToC()

How I would like the OUTPUT:

all of the numbers from cToF()    all of the numbers from fToC()
Dave Cribbs
  • 809
  • 1
  • 6
  • 16
  • 1
    To make your output more useful, I suggest that each of your functions should print _two_ numbers, the temperature it's converting from as well as the temperature it's converting to. But even if you don't do that you need to take special care if you want the output to be side by side because `cToF()` prints 100 lines, but `fToC()` prints 180 lines. – PM 2Ring Oct 18 '14 at 05:15

2 Answers2

2

Currently, the cToF function runs and prints all it's values, then the fToC function runs and prints all it's values. You need to change how you're generating the values so that you can print them side by side.

# generate f values
def cToF(low=0, high=100):
    for c in range(low, high + 1):
        yield c * 9 / 5 + 32

# generate c values
def fToC(low=32, high=212):
    for f in range(low, high + 1):
        yield (f - 32) * 5 / 9

# iterate over pairs of f and c values
# will stop once cToF is exhausted since it generates fewer values than fToC
for f, c in zip(cToF(), fToC()):
    print('{}\t\t{}'.format(f, c))
# or keep iterating until the longer fToC generator is exhausted
from itertools import zip_longest

for f, c in zip_longest(cToF(), fToC()):
    print('{}\t\t{}'.format(f, c))  # will print None, c once cToF is exhausted

If you're using Python 2, substitute xrange for range and izip_longest for zip_longest.

davidism
  • 121,510
  • 29
  • 395
  • 339
0

If you want to print like;

cToF first Element fToC first element
cToF second Element fToC second element
...

You can join 2 list to print it.

Example code that you can use;

import pprint
def cToF():
    c = 0
    ret_list = []
    while c <= 100:
        ret_list.append(c * 9 / 5 + 32)
        c += 1
    return ret_list

def fToC():
    f = 32
    ret_list = []
    while f <= 212:
        ret_list.append((f - 32) / 1.8)
        f += 1
    return ret_list

def join_list(first_list, second_list):
    length_of_first_list = len(first_list)
    for i, val in enumerate(second_list):
        second_list[i] = (" - "if (length_of_first_list-1) < i else first_list[i], val)
    return second_list

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(join_list(cToF(), fToC()))
umut
  • 1,016
  • 1
  • 12
  • 25