Everything appears to be defined as a string? Python [duplicate]
Everything appears to be defined as a string? Python [duplicate]
This question already has an answer here:
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?
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
float('3.14')
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) ....– phihag
Jun 30 at 18:30
input
Let us close this question as a non-reproducible problem. Good luck programming Blessed! :)
– Anton vBR
Jun 30 at 18:31
"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 ?
– Robᵩ
Jun 30 at 18:32
2 Answers
2
In Python input always returns a string.
If you want to consider it as an int you have to convert it.
input
string
int
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))
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?
– Blessed
Jun 30 at 19:31
You can yourself define a functon
input which behave as you like in a module you will import.– Blincer
Jun 30 at 19:33
input
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.
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.– Anton vBR
Jun 30 at 18:29