Francisco Echaniz
Francisco Echaniz

Reputation: 11

My number won't add up for my algorithm and I don't know why

print ("Perimeter for Total House Floor Remodeling Calculator")   
print(" ")   
width1 = input ("Please enter the width of the floor: ")   
length1 = input ("Please enter the length of the floor: ")   
print (" ")   
length = length1 * 2   
width = width1 * 2   
perimeter = (length + width)   
print ("The perimeter of the floor is: ",perimeter)    

Once I input my number and lets say I put in 5 for the width and 5 for the length, my perimeter would come out as 5555 instead of 20. I'm new to coding so any help is greatly appreciated.

Upvotes: 1

Views: 55

Answers (4)

umutto
umutto

Reputation: 7700

input() function gives you strings, you need to convert them to integer before doing any calculation. Try:

width1 = int(input("Please enter the width of the floor: "))   
length1 = int(input("Please enter the length of the floor: ")) 

Python can do multiplication operation between strings, which repeats them. IE: '5'*3 gives you '555' because it is a string. While 5*3 gives 15 because it is an integer.

Upvotes: 3

Kyle
Kyle

Reputation: 1066

You are capturing the data from input() which is a string. You need to cast it to a number. When you have a string aka "12" and you run "12"*2 it will output "1212".

raw_output = input("Enter a number: ")
print("Type of raw_output: {0}".format(type(raw_output))
actual_integer = int(raw_output)
print("Type of actual_integer: {0}".format(type(actual_integer))

From the help function

Help on built-in function input in module builtins:

input(...)
    input([prompt]) -> string

Read a string from standard input.  The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled.  The prompt string, if given,
is printed without a trailing newline before reading.

Upvotes: 1

Axle12693
Axle12693

Reputation: 56

I'm not sure which version of python you're using, but on 2.7.13 that I have on my computer, your code works just fine. Check which version you're got, and let us know.

Upvotes: 0

Chaitanya Baranwal
Chaitanya Baranwal

Reputation: 42

Since data types don't need to be explicitly mentioned in Python, you'll have to type cast (forcibly convert to some other data type) your inputs for them to be considered as integers.

width1 = int(input("Please enter the width of the floor: "))
length1 = int(input("Please enter the length of the floor: ")) 

This should work!

Upvotes: 0

Related Questions