How to get the integers entered but it says it is in string format?

Question:

num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
num3 = input("Enter third number: ")
num4 = input("Enter fourth number: ")
num5 = input("Enter fifth number: ")
print("n")
print("%d,%d,%d,%d,%d" %("num1,num2,num3,num4,num5"))

Results:

Enter first number: 90
Enter second number: 98
Enter third number: 94
Enter fourth number: 98
Enter fifth number: 99
Traceback (most recent call last):
  File "<string>", line 7, in <module>
TypeError: %d format: a number is required, not str
Asked By: Ulysses Dizon

||

Answers:

The numbers that you entered into the console were considered as strings. You need to cast them into ‘int’.

print("%d,%d,%d,%d,%d" % (int(num1), int(num2), int(num3), int(num4), int(num5)))

Answered By: shashika11

If you want to use them as integers later on, you’ll need to convert the input to int type like this:

Also, natice that the quotes around the variable in the string formatting have been removed. The quotes were causing the python interpreter to think it was just being passed a single string.

num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
num4 = int(input("Enter fourth number: "))
num5 = int(input("Enter fifth number: "))
print("n")
print("%d,%d,%d,%d,%d" %(num1,num2,num3,num4,num5))

If you don’t need to use the input as integers later on you can just leave them as strings and change the string formatting to use them as strings:

num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
num3 = input("Enter third number: ")
num4 = input("Enter fourth number: ")
num5 = input("Enter fifth number: ")
print("n")
print("%s,%s,%s,%s,%s" %(num1,num2,num3,num4,num5))
Answered By: bmcculley

if you do not know how to format a string by that way you can use

format (method) with your string.

num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
num3 = input("Enter third number: ")
num4 = input("Enter fourth number: ")
num5 = input("Enter fifth number: ")
print("n")
print("{},{},{},{},{}".format(num1,num2,num3,num4,num5))

it is better than that way. i think

Answered By: Mohammed almalki
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.