0

I am completely new to programming. However, I just wanna write a simple bit of code on Python, that allows me to input any data and the type of the data is relayed or 'printed' back at me.

The current script I have is:

x = input()
print(x)
print(type(x))

However, regardless of i input a string, integer or float it will always print string? Any suggestions?

4
  • 1
    The input function always returns a string. That is the purpose of it. If you want a float you have to do the conversion yourself. Try for instance: float('3.14') which returns a float-value. Commented Jun 30, 2018 at 18:29
  • 3
    Why do you expect the input function to return anything but a string (in Python 3)? From its documentation: The function (..) reads a line from input, converts it to a string (stripping a trailing newline) .... Commented Jun 30, 2018 at 18:30
  • Let us close this question as a non-reproducible problem. Good luck programming Blessed! :) Commented Jun 30, 2018 at 18:31
  • 2
    "Any suggestions?" Yes, find a good Python tutorial. Read and understand it, running all of the example programs it offers. Learning Python by guessing isn't very effective nor efficient. May I suggest the official Python Tutorial ? Commented Jun 30, 2018 at 18:32

2 Answers 2

2

In Python input always returns a string. If you want to consider it as an int you have to convert it.

num = int(input('Choose a number: '))
print(num, type(num))

If you aren't sure of the type you can do:

num = input('Choose a number: ')
try:
    num = int(num)
except:
    pass
print(num, type(num))
Sign up to request clarification or add additional context in comments.

2 Comments

So there's no way Python will allow the function in which I want to create, unless I fixate it on one type, and the info will have to fall into the specified type, meaning I'd have to run the same information through various shells/scripts?
You can yourself define a functon input which behave as you like in a module you will import.
1

1111 or 1.10 are valid strings

If the user presses the "1" key four times and then Enter, there's no magic way to tell if they wanted to enter the number 1111 or the string "1111". The input function gives your program the arbitrary textual data entered by user as a string, and it's up to you to interpret it however you wish.

If you want different treatment for data in particular format (e.g. if they enter "1111" do something with it as a number 1111, and if they enter "111x" show a message "please enter a valid number") then your program needs to implement that logic.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.