MIke Burton
MIke Burton

Reputation: 1

Newbie problems with printing strings and variables in Python

I am completely new to coding and having just got hold of a Raspberry Pi i am starting out from scratch. Im trying a simple program to display a multiplication table chosen from an input off the user. the entire code is listed below - sorry if its scruffy

The output I'm looking for is for example

1 x 5 = 5
2 x 5 = 10
3 x 5 = 15

etc...

What I actually get is:

(((1, "x"), 5), ' + ') 5)
(((2, "x"), 5), ' + ') 10)
(((3, "x"), 5), ' + ') 15)

etc...

Can anyone help me with a reason as to why this is coming out this way? I appreciate the code may be a little scruffy and bloated. I am trying to use a couple of different methods to set the variables etc just for the sake of experimentation.

thank you in advance Mike

m = int(1)
z = input ("What table would you like to see?")
t = int(z)
while m <13:
    e = int(m*t)
    sumA = (m, " x ")
    sumB = (sumA, t)
    sumC = (sumB, " + ")
    print (sumC, e)
    m += 1

Upvotes: 0

Views: 135

Answers (2)

Zac Wrangler
Zac Wrangler

Reputation: 1445

  1. you don't need to specify the type in python. instead of m = int(1), you could just say m= 1, and e = m* t

  2. you are building tuples instead of formatting the output, if you want to format the pirntout, the simplest way here is to use format as discussed from python doc: http://docs.python.org/2/library/string.html. The code would be like,

    print("{0} x {1} = {2}".format(m, t, e))
    

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1122342

Don't use tuples as your intermediary variables; just print the whole thing:

while m <13:
    e = m * t
    print(m, 'x', t, '+', e)
    m += 1

and you may want to use a range()-based loop instead of while:

z = input ("What table would you like to see?")
t = int(z)
for m in range(1, 13):
    e = m * t
    print(m, 'x', t, '+', e)

Note that there is no need to call int() so many times; use it only on the return value of input(), which is a string otherwise.

Upvotes: 2

Related Questions