This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I don't think I am using the write syntax to write my code, I am new and would like some help. This code is due tonight so anything would be helpful.
I have tried looking on youtube and other websites, but I couldn't find anything.
print("Hello, I can divide by two! Try me out.")
myNumber = input("What is your number?")
print("myNumber/2")
myAnswer = int(input(myNumber/2))
print("myAnswer")
I expect that the fourth line of code has incorrect syntax for the intended function.
input is always a string. It has to be converted to int for any int operations. Change this.
myNumber = input("What is your number?")
to
myNumber = int(input("What is your number?"))
You are taking input and storing it in myNumber which is string type. you can type-cast the myNumber to integer or float data type before dividing it by two.
print("Hello, I can divide by two! Try me out.")
myNumber = input("What is your number?")
print("myNumber/2")
myAnswer = int(myNumber)/2
print("myAnswer is ",myAnswer)
I believe this will do your work.
Related
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
What's the canonical way to check for type in Python?
(15 answers)
How can I read inputs as numbers?
(10 answers)
Closed last year.
I am a beginner when it comes to coding. I am trying to run a program on python that takes in kilometers(user input) and returns it in miles(output). I know how to do the task but I wanted to challenge myself by using if statements to check if the user has entered a number:
Kilometers = input("Please insert number of Kilometers: ")
if type(Kilometers) == int or float:
print("This is equivalent to", float(Kilometers)/1.609344, "Mile(s)")
else:
print("This is not a number")
I understand that whatever the user inputs will be saved as a string. However, whenever I run the code, the program always tries to convert the input into miles.
I have specified in the if statement that the type has to equal a float or an int, so shouldn't the output always be "This is not a number" until I change the first line to:
Kilometers = float(input("Please insert number of Kilometers: "))
or
Kilometers = int(input("Please insert number of Kilometers: "))
When programming if statements in Python, each condition must be fully rewritten. For example, you would write if type(Kilometers) == int or type(Kilometers) == float rather than if type(Kilometers) == int or float. Another important thing in your code is that if someone inputs 5.5, you would expect a float value, but Python interprets that to be a string. In order to circumvent this, you can use a try/except clause like this:
Kilometers = input("Please insert number of Kilometers: ")
try:
Kilometers = float(Kilometers)
print("This is equivalent to", Kilometers/1.609344, "Mile(s)")
except ValueError:
print("This is not a number")
What this is doing is trying to set Kilometers as a float type, and if the user inputs a string that cannot be interpreted as a float, it will cause a ValueError, and then the code inside except will run. You can find more on try/except clauses here: Python Try Except - W3Schools
One more thing I noticed is that you should name your variables according to the standard naming conventions, so Kilometers should be kilometers. You can find more on the naming conventions here: PEP 8
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: ")
This question already has answers here:
How does my input not equal the answer?
(2 answers)
Closed 5 years ago.
Hi all I hope you can explain what I am doing wrong. I am completely new to python and experimenting with basic code but it don't seem to work as i thought it might.
the program should be a simple one of guessing the right number contained in the variable, but even when guess correct it says "Nope, that's not right".
magic_number = 10
input("I am thinking of a number between 1 and 10, can you guess it? ")
if input == magic_number:
print("WOW! You must be psychic, that is spot on")
else:
print("Nope, that's not it")
first of all you should creat a variable that will store the answer, so for example.
answer = input("I am thinking of a number between 1 and 10, can you guess it? ")
thus you will also have to change if input == magic_number: to if answer == magic_number:
Nonetheless, the main problem is that when you enter something using the input method your input is automatically converted to a string.
So you have two choices:
Convert your magic number to a string (magic_number = 10to magic_number = "10") and run the code with the modifications that I have proposed
Convert your input too and Int modifying if answer == magic_number: to if int(answer) == magic_number:
Both of the methods work great, though be careful with the second one because if you input something that is not convertible to an int (for example "Hello", the code will return an error)
input isn't a variable, it's a function! You should type x=input("Enter a number"), and if x == magic_number. input returns a value, but you aren't storing the user's input anywhere.
try this :
magic_number = 10
guess = int(input("I am thinking of a number between 1 and 10, can you guess it? "))
if guess == magic_number:
print("WOW! You must be psychic, that is spot on")
else:
print("Nope, that's not it")
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).
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
This has been flagged as a duplicate, i was unaware of the issue at the time but I shall take this post down in the next 48 hours, apologies.
I'm currently working on a python (v3.5.0:374f501f4567) program that generates a ranom equation using multiplication, addition or subtraction using. The code works perfectly up until the final hurdle. When trying to return if the answer is correct or incorrect I am thoroughly stumped. When I use the following code:
import random
from operator import add,sub,mul
x=random.randint(0,10)
y=random.randint(0,10)
eqn=(add, sub, mul)
eqnchoice=random.choice(eqn)
eqnstring={add:'+',sub:'-',mul:'*'}
useranswer=0
def eqngenerator():
random.seed
answer=eqnchoice(x,y)
answer=round(answer,2)
print("what's the answer to",x,eqnstring[eqnchoice],y,"=?\n")
useranswer=input("Enter the answer here:")
if useranswer==answer:
print('Correct!')
else:
print('Incorrect!')
print(eqngenerator())
I am faced with the following problem as seen in the screenshots below.
I'm befuddled as to why this is, if anyone can help please do.
Thank you for your time.
input() will be giving you a string in your useranswer variable. It will need to converted to a number before use, eg a float or an int
useranswer = int(input("Enter the answer here:"))
or
useranswer = float(input("Enter the answer here:"))
Use int if you know the answer to your calculation will always be an integer
input returns a string, so you need:
useranswer=float(input("Enter the answer here:"))
it will raise an error if user enter any other value then a number, so you can make:
def eqngenerator():
random.seed
answer=eqnchoice(x,y)
answer=round(answer,2)
print("what's the answer to",x,eqnstring[eqnchoice],y,"=?\n")
useranswer=input("Enter the answer here:")
try:
if useranswer==answer:
print('Correct!')
else:
print('Incorrect!')
except ValueError:
print('Incorrect!')