Is there something wrong with this line of code? [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I want to take from the user an input integer, and turning to a string in my code.
My line of code for that is:
num1 = input(int(str("Enter a number: ")))
But the console says: ValueError: invalid literal for int() with base 10: 'Enter a number: '
If this line isn't correct can you show me a way how can I turn an integer that is given by the user to a string in my code?

You have the functions in the wrong order: First you need to turn the input into a Python object, so input() has to be the innermost function (to be applied first). Also, input() will cast the input as a string by default, so you don't need str().
So the line should read:
num1 = input("Enter a number: ")

Related

Function to detect integers instead string in Python [duplicate]

This question already has answers here:
How do I check if a string represents a number (float or int)?
(39 answers)
How can I check if string input is a number?
(30 answers)
Closed 1 year ago.
I'm trying to make a function that count the numbers of characters in a string and detect when an integer is typed, the condition is use "if" function. I'd expect that if I type any integer like"4464468" instead a string, the program displayed: "Sorry, you typed an integer". But, instead, counts the total number and displayed "The word you type has 7 characters".
My code is next:
def string_lenght(mystring):
return len(mystring)`
#Main Program
mystring = (input("Type a word: "))
if type(mystring) == int or type(mystring) == float:
print("Sorry, you typed an integer")
else:
print("The word you typed has",string_lenght(mystring), "characters")
I'm Newbie at Python. I really appreciate your help and patience.
Best regards.
input() always returns a string so you can try to convert it into int/float, if the operation is successful then it's a number, else it is a string:
try:
float(mystring)
print("Sorry you typed an integer")
except ValueError:
# Rest of the code ...

How do I convert a string from an input into an integer? (Python 3.9) [duplicate]

This question already has answers here:
Short way to convert string to int [duplicate]
(3 answers)
Closed 1 year ago.
As you know, a user input in Python by default is a string. I tried converting them using the int() function after, however, it still stays as a string.
Code example:
number = input("Input a number: ")
int(number)
print(type(number))
This would give an output of: <class 'str'>
, even though I tried converting them to an integer.
You need to assign the value, because int() doesn't apply on place.
number = int(number)
Python int() function
You also need to assign the converted variable to your number:
number = input("Input a number: ")
number = int(number)
print(type(number))
Or directly like this:
number = int(input("Input a number: "))
print(type(number))

Problem with checking if input is integer (very beginner) [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I'm just starting to learn Python (it's my first language). I'm trying to make a simple program that checks if the number the user inputs is an integer.
My code is:
number = input('Insert number: ')
if isinstance(number, int):
print('INT')
else:
print('NOT')
I have no idea why, but every number gets it to print 'NOT'. If I just make a statement 'number = 1' in the code, it prints 'INT', but if I input '1' in the console when the program asks for input, it prints 'NOT' no matter what. Why is that?
(I'm using Python 3.8 with PyCharm)
When you input something, the type is always a str. If you try:
number = input('Insert number: ')
if isinstance(number, str):
print('INT')
else:
print('NOT')
you will always get:
INT
If all you want is to detect whether the input is an integer, you can use str.isdigit():
number = input('Insert number: ')
if number.isdigit():
print('INT')
else:
print('NOT')

How to change this data input type in python? [duplicate]

This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 6 years ago.
I have this line in my programme-
num = int(input("Enter a number: "))
Now as the input type is int, I cannot use any exponents. How can I change the data input type from int to something else so that I can input exponents like 2**4 (= 2^4)?
Don't use int() :)
>>> x = input("Enter a number:")
Enter a number:2**3
>>> print x
8
It can be explained by the documentation (https://docs.python.org/2/library/functions.html#input):
input([prompt])
Equivalent to eval(raw_input(prompt)).
This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.
...
Consider using the raw_input() function for general input from users.
In python3 things a bit changed, so the following alternative will work:
x = eval(input("Enter a value"))
print(x)
You could always accept a string and then split in on a delimiter of your choice, either ^ or **.
If I'm not mistaken, eval is insecure and should not be used (please correct me if I'm wrong).

Error in a basic python code [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
so I just started Python today. Tried a basic program, but I'm getting an error "can't convert int object to str implicity"
userName = input('Please enter your name: ' )
age = input('Please enter your age: ')
factor = 2
finalAge = age + factor **ERRORS OUT ON THIS LINE**
multAge = age * factor
divAge = age / factor
print('In', factor, 'years you will be', finalAge, 'years old', userName )
print('Your age multiplied by', factor, 'is', multAge )
print('Your age divided by', factor, 'is', divAge )
When I do enter int(age)+factor, instead of age, it works perfectly. But the author says that python auto detects the variable type when you key it in. So in this case when I enter age=20, then age should become integer automatically correct?
Looking forward to any help!!
From the doc
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
As you can see, the input() function in python 3+ returns a string by converting whatever input you are given, much like raw_input() in python 2.x.
So, age is clearly a string.
You can't add a string with an integer, hence the error.
can't convert int object to str implicity
int(age) converts age to an integer, so it works in your case.
What you can do:
Use:
age = int(input('Please enter your age: '))
To cast your input to an integer explicitly.
Your problem is that input returns a string (since in general, input from the command line is text). You can cast this to an int to remove the error, as you have done.
Python only automatically detects the type of your variables in your program if they don't already have a type - it does not automatically convert typed variables to different types.
Python does not know what operation you're trying to make, provided the '+' operator can be used both to concatenate strings and adding numbers.
So, it can't know if you're trying to do
finalAge = int(age) + factor #finalAge is an integer
or
finalAge = age + str(factor) #finalAge is a string
You need to explicitly convert your variables so it won't be ambiguous.
In your case, int(age) returns an integer, which is the proper way to get what you want.

Categories

Resources