I had a problem in Python. I was trying to make an addition calculator but a problem popped up. My code is attached.
prompt = input("Do you want to use this calculator? Y for yes and N for no ")
if prompt == 'n' :
print ("Maybe next time. ")
if prompt == 'y':
numberone = input("What is your first number? ")
numbertwo = input("What is your second number? ")
print ("Your equation is ",numberone, "+ ",numbertwo, )
answer = (numberone * numbertwo)
print ("Your answer is ",answer, )
When I print the answer it comes out as two numbers combined. For example if I'm using 9+10, it'll come out as 910. I don't know what to do to fix it.
input gets the input from the user and returns it as a string.
You need to convert the input to a number. I presume you want the numbers to be int, but you could just replace int with float if you need to.
prompt = input("Do you want to use this calculator? Y for yes and N for no ")
if prompt == 'n' :
print ("Maybe next time. ")
elif prompt == 'y':
numberone = int(input("What is your first number? "))
numbertwo = int(input("What is your second number? "))
print ("Your equation is ",numberone, "+ ",numbertwo, )
answer = (numberone + numbertwo)
print ("Your answer is ",answer, )
Related
first project beginner here! I just finished my first project, a somewhat working calculator i know it is not that great but as i said beginner. I would like to limit the options for number = input meaning if you write anything else than add,substract,divide or multiply you receive an error like " please try again" and afterwards the programm is restarted
Help very much appreciated Thank you.
list = ("add", "substract", "divide" , "multiply" )
number = input("do you want to add substract divide or multiply? ")
if number in list:
print("ok")
else:
print("try again")
number_one = float(input("enter your first number "))
number_two = float(input("enter your second number "))
if number == "add":
solution_one = number_one + number_two
print(solution_one)
if number == "substract":
solution_two = number_one - number_two
print(solution_two)
if number == "divide":
solution_three = number_one / number_two
print(solution_three)
if number == "multiply":
solution_four = number_one * number_two
print(solution_four)
i could only find solutions regarding while loops but i did not know how to use them in this case as these weren't strings but integers.
The fact that you're prompting for a string doesn't change the way the while loop works. Run your code in a loop and break when it's time for the loop to end.
while True:
number = input("do you want to add substract divide or multiply? ")
if number in ("add", "substract", "divide" , "multiply" ):
print("ok")
break
print("try again")
Note that it's considered bad practice to give a variable a name like list (or any other built-in name) since it can lead to very confusing bugs when you try to reference the built-in name later!
You could consider using the operator module.
Build a dictionary that maps the user's selected operation with the relevant function.
import operator
OMAP = {
'add': operator.add,
'subtract': operator.sub,
'divide': operator.truediv,
'multiply': operator.mul
}
while (op := input('Do you want to add, subtract, multiply, divide or end? ')) != 'end':
try:
if (func := OMAP.get(op)):
x = float(input('Enter your first number: '))
y = float(input('Enter your second number: '))
print(func(x, y))
else:
raise ValueError(f'"{op}" is not a valid choice')
except ValueError as e:
print(e)
I want to get a string from a user, and then to manipulate it.
testVar = input("Ask user for something.")
Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. "Hello" vs. Hello
If the user types in Hello, I get the following error:
NameError: name 'Hello' is not defined
Use raw_input() instead of input():
testVar = raw_input("Ask user for something.")
input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.
The function input will also evaluate the data it just read as python code, which is not really what you want.
The generic approach would be to treat the user input (from sys.stdin) like any other file. Try
import sys
sys.stdin.readline()
If you want to keep it short, you can use raw_input which is the same as input but omits the evaluation.
We can use the raw_input() function in Python 2 and the input() function in Python 3.
By default the input function takes an input in string format. For other data type you have to cast the user input.
In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting
x = raw_input("Enter a number: ") #String input
x = int(raw_input("Enter a number: ")) #integer input
x = float(raw_input("Enter a float number: ")) #float input
x = eval(raw_input("Enter a float number: ")) #eval input
In Python 3 we use the input() function which returns a user input value.
x = input("Enter a number: ") #String input
If you enter a string, int, float, eval it will take as string input
x = int(input("Enter a number: ")) #integer input
If you enter a string for int cast ValueError: invalid literal for int() with base 10:
x = float(input("Enter a float number: ")) #float input
If you enter a string for float cast ValueError: could not convert string to float
x = eval(input("Enter a float number: ")) #eval input
If you enter a string for eval cast NameError: name ' ' is not defined
Those error also applicable for Python 2.
If you want to use input instead of raw_input in python 2.x,then this trick will come handy
if hasattr(__builtins__, 'raw_input'):
input=raw_input
After which,
testVar = input("Ask user for something.")
will work just fine.
testVar = raw_input("Ask user for something.")
My Working code with fixes:
import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)
correct= False
while(correct == False):
guess1= input("Which number is the highest? "+ str(list) + ": ")
if maxNum == guess1:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
print("Correct!")
correct = True
else:
print("Incorrect, try again")
correct= False
while(correct == False):
guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
if sqrtOne >= 2.0 and str(guess3) == "y":
print("Correct!")
correct = True
elif sqrtOne < 2.0 and str(guess3) == "n":
print("Correct!")
correct = True
else:
print("Incorrect, try again")
print("Thanks for playing!")
This is my work around to fail safe in case if i will need to move to python 3 in future.
def _input(msg):
return raw_input(msg)
The issue seems to be resolved in Python version 3.4.2.
testVar = input("Ask user for something.")
Will work fine.
I feel like the question is not well worded for a question, but this is what I really want:
I am writing this code where a 'user' can enter as many integers from 1 to 10 as he/she wants. Every time after the user has entered an integer, use a yes/no type question to ask whether he/she wants to enter another one. Calculate and display the average of the integers in the list.
Isn't 'while' supposed to running part of a program over and over and over again until it stops when it is told not to?
num_list = []
len()
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while integer_pushed < 0 or integer_pushed > 10:
print('You must type in an integer between 0 and 10')
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
while again == "y":
integer_pushed = float(input("Enter as many integers from 1 to 10"))
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print ("Number list:", num_list)
It stops after the 2nd time even if the user types in 'y'. It then gives me the 'Number List: ".
Once again, you guys have been great assisting my classmates and I. Im in an introduction to Python course and we are learning about loops and lists.
One while loop is sufficient to achieve what you want.
num_list = []
again = 'y'
while again=='y':
no = int(input("Enter a number between 1 and 10: "))
if not 1 <= no <= 10:
continue
num_list.append(no)
again = input("Enter another? [y/n]: ")
print("Average: ", sum(num_list) / len(num_list))
The while loop runs as long as again == 'y'. The program asks for another number if the user inputs an integer not between 1 and 10.
Try this:
num_list = []
again = "y"
while again == "y":
try:
integer_pushed = float(input("Enter as many integers from 1 to 10"))
if integer_pushed > 0 or integer_pushed <= 10:
num_list.append(integer_pushed)
again = input("Enter another integer? [y/n]")
print("Number list:", num_list)
else:
print('You must type in an integer between 0 and 10')
except ValueError:
print('You must type in an integer not a str')
I'm not sure why you had two different while loops, let alone three. However, this should do what you want. It will prompt the user for a number, and try and convert it to a float. If it can't be converted, it will prompt the user again. If it is converted it will check to see if it's between 0 and 10 and if it is, it will add it to the list, otherwise, it will tell the user that that's an invalid number.
I'm working on a Python script where a user has to guess a random number, selected by the script. This is my code:
import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)
while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break
It works... Sort of... I was trying it and came across this:
User enters 2, it says it's incorrect, but then displays the same number!
I have the feeling that, every time I call the variable 'number', it changes the random number again. How can I force the script to hold the random number picked at the beginning, and not keep changing it within the script?
As far as I understand it, you want to pick a new random integer in every loop step.
I guess you are using python 3 and so input returns a string. Since you cannot perform comparisson between a string and an int, you need to convert the input string to an int first.
import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
try:
antwoord = int(antwoord)
except:
print ("You need to type in a number")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)
while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here is my code:
name = input("What is your name? ")
print name + " do you want to play a game?"
answer = input("To play the game, type either yes or no. ")
if answer == yes:
print "Great," + name + "lets get started!"
elif answer == no:
print "Okay, good bye!"
import random
number = random.randint(1,50)
guess = input ("Pick a number between 1 and 50. This number cannot be a decimal. ")
if guess > number:
print "Your guess is too high!"
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
else import random
number = random.randint(1,50)
if guess == number:
print "You guessed it!"
print "Great job."
print "Do you want to play again?"
while answer == yes:
import random
number = random.randint(1,50)
guess = input ("Pick a number between 1 and 50. This number cannot be a decimal. ")
if guess > number:
print "Your guess is too high!"
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
if guess == number:
print "You guessed it!"
print "Great job."
print "Do you want to play again?
elif answer == no:
print "Okay. Good game " + name + "!"
print "Play again soon!"
Ok, my first question is why does python not recognize input for the name variable as a string.
The second question is the last elif statement keeps giving me a syntax error. I am not sure why.
The last question is can I loop this code any easier way?
In Python 2x versions, input() takes variable as integer, you could use raw_input() to take it as string.
So basically change your input() to raw_input() for taking the data as string.
In Python 3x versions there is no raw_input, there is only input() and it takes the data as string.
Second question;
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
else import random
number = random.randint(1,50)
This is not a correct syntax, your else needs an if block above itself. You can't use else without an if block.If you think for a second, that makes sense.
Your last question is not fit with SO rules.