-4

I am trying to code a program that will ask the user for their name and age and return how long until they turn 100 years old. I keep getting errors and I can't understand what I am doing wrong.

Here is the more basic code I have changed it to try and get it to work, as was getting too much resistance getting my f-strings to print with {age}, {name} and so on.

import sys, math

# Inputs

name = str(input("What is your name: "))

age = str(input("How old are you: "))

# Calculations

diff = (100 - age)

year = str((2020 - age)+100)

# Output


print ("Hay " + name + " you are currently " + age + " years old, in " + diff + " years you will be 100, in the year " + year)

at the diff = (100 - age) stage of my program it comes back with the following:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~/Documents/Python/years until you are 100.py in 
      7 # Calculations
      8 
----> 9 diff = (100 - age)
     10 
     11 year = str((2020 - age)+100)

TypeError: unsupported operand type(s) for -: 'int' and 'str'

What am I missing?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
TechSlugz
  • 1
  • 3
  • 1
    You can perform arithmetic on an int. You can't perform arithmetic on a string. Your `age` is a string. – khelwood Jul 30 '20 at 13:54
  • 1
    but age is referring to my user's input which was an int no? ohhhhh as I was typing I've half realised, all input is as a string right? so how can I make 'age' be calculated as an int? Do I have to convert the input to an int first? – TechSlugz Jul 30 '20 at 13:57
  • You did check the link that Jonrsharpe gave? – Jongware Jul 30 '20 at 14:10
  • no but am about to have a read of that now also. – TechSlugz Jul 30 '20 at 14:28
  • 1
    I solved it, was that I didn't convert the srting to int as he mentioned. I did a quick age = int(age) and it sorted it right out :D thank you Jonsharpe! – TechSlugz Jul 30 '20 at 14:33
  • this is actuallythe exact page I used https://www.geeksforgeeks.org/type-conversion-python/ – TechSlugz Jul 30 '20 at 14:54

1 Answers1

0

RIGHT! I got it myself in case any other noobs want to know like I did!

the following is the correct code

import sys, math

# Inputs

name = str(input("What is your name: "))

age = str(input("How old are you: "))

# Conversions

age = int(age)

# Calculations

diff = (100 - age)

year = str((2020 - age)+100)

# Output


print (f"Hay {name} you are currently {age} years old, in {diff} years you will be 100, in the year {year}")

the issue was as stated in my comments on this question between myself and another very kind user.

I forgot that all inputs are strings so when I went to use my (age) variable, it wouldn't do the math.

Simply adding a conversion from str to int prior to my calculations sorted it all out :D : age = int(age)

TechSlugz
  • 1
  • 3