0

I'm EXTREMELY new to coding in general so i'm sorry if this is a dumb question but... I'm having a problem, and that is when I try to add text to an Input multiplication (I don't know if it has a name) it freaks out.

I've seen a few "solutions" about it, and it works for specific cases, but it messes up in this one.

This is my code:

j = input("What is your age? : ")
j = str(j)
DogY = (j * 7)
print("Your age in dog years is " + DogY)

I'm trying to make a dumb "Your age in dog years is * blank *." thing but this happens, I can't get what i'm looking for. If I input something easy like 10 (easy for me because I don't have to do math), this happens

What I want is:

Your age in dog years is 70

Instead I get

Your age in dog years is 10101010101010

I'm sure it has the easiest solution but I can't figure it out or find the solution anywhere. Please help

Some1
  • 3
  • 1
  • 2
    `j = str(j)` should probably be `j = int(j)`. – hiro protagonist Jan 11 '20 at 12:48
  • 1
    Multiplying a `string` in python repeats the string even if the string contains a number. – Ramy M. Mousa Jan 11 '20 at 12:50
  • Note that python _always_ takes input in the form of a string. You want an `int`, and so convert it to integer by `j = int(input("What ..."))`. Your print will become: `print('Your age...', dog_years)` since `int + str` is not allowed in python. – Jaideep Shekhar Jan 11 '20 at 12:55
  • Does this answer your question? [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) – John Coleman Jan 11 '20 at 13:08
  • It isn't a dumb question. Almost all beginning Python programmers get tripped up by how `input()` works at least once. – John Coleman Jan 11 '20 at 13:13

1 Answers1

1

The biggest upside of python is its simplicity and flexibility in implementation.

In the below code,

Type 1: Traditional way

j = input("What is your age? : ")
j = int(j)
Dog_Years = str(j * 7)
print("Your age in dog years is " + Dog_Years)

Type 2: Better way

  • We are setting up age with the constraint that it will always be int.
  • Then we are multiplying without storing.
j = int(input("What is your age? : "))
print("Your age in dog years is " + str((j * 7)))

Type 3: Pythonic Way

  • We are performing the operation without any usage of variables.
print("Your age in dog years is : ", str( int(input("What is your age? : ") )*7 ) )
High-Octane
  • 1,104
  • 5
  • 19