Confusing result from raw_input() in Python - python

I'm having problems with the "operator" variable. So far I have only tried +. It doesn't seem to register and I can't figure out why. i'm using the online python interpreter on repl.it because I'm having problems with my computer.
EDIT: I should probably add that I just started learning Python (I had some Java experience but it was years ago). I'm trying to create a simple text calculator.
restart=raw_input("to restart calculations enter \'true\'")
#if restart == "true":
#stuff
numone=raw_input("Enter the first number: ")
operator = raw_input("Enter the operator(+,-,*,/):")
operator = str(operator)
numtwo=raw_input("Enter another number: ")
print("operator: " + operator)
if operator== '+':
answer=numone+numtwo
print(answer)
print("test")
if operator == "-":
answer=numone-numtwo
print(answer)
else:
print("something went wrong")
#if operator == "*":

Your problem is that you're concatenating two strings, you should cast to int before:
answer = int(numone) + int(numtwo)
Why? Because raw_input reads the input as string.

Give elif to the second statement
since user give '+'
first if statment excutes but in next statement it fails and go to the else so for + you get two result both addition and something wrong
and also you need to convert the operands to integer
one more thing while converting to integer you need check right conditions for integer else it will give error
numone=raw_input("Enter the first number: ")
operator = raw_input("Enter the operator(+,-,*,/):")
operator = str(operator)
numtwo=raw_input("Enter another number: ")
print("operator: " + operator)
if operator== '+':
try:
answer=int(numone)+int(numtwo)
print(answer)
print("test")
except ValueError:
print "one of the operand is not integer"
elif operator == "-":
try:
answer=int(numone)-int(numtwo)
print(answer)
print("test")
except ValueError:
print "one of the operand is not integer"
else:
print("something went wrong")

Related

Palindrome Program Cannot Recognize Other [duplicate]

This question already has answers here:
Python Palindrome
(3 answers)
Closed 1 year ago.
I am currently struggling with a homework problem and I need some help, as I feel like I'm a bit confused. I work on creating a program that looks for palindromes within integers only. The program I've made I know will accurately identify palindromes within integers, but I cannot get the program to identify when the input is not an integer (float, bool, str, etc.). I specifically want the program to note when an integer is not the input and print "The input is not an integer" before breaking. Here is my code below:
def Palindrome(n):
return n == n[::-1]
n = input("Please enter an integer: ")
ans = Palindrome(n)
if ans == True:
print("The number " + n + " is a palindrome")
elif ans == False:
print("The number " + n + " is NOT a palindrome")
I know this is kind of basic, but everyone needs to start somewhere! If anyone could explain what I could do to create the program and understand how it works, it would be very appreciated :)
Your palindrome() function has some indentation issues.
def palindrome(n):
return n == n[::-1]
This function can basically check whether a string str is a palindrome, and not just limited to integers.
n = input("Please enter anything: ")
is_palindrome = palindrome(n)
if is_palindrome:
print(n + " is a palindrome.")
else:
print(n + " is not a palindrome.")
Output
Test case A for racecar.
Please enter anything: racecar
racecar is a palindrome.
Test case B for 123.
Please enter anything: 123
123 is not a palindrome.
When you get an input it's always a string value, so a possible solution is to modify Palindrome. First, try to cast the input to int and then print and exit if it throws a ValueException in this way.
def Palindrome(n):
try:
int(n)
except ValueError as e:
raise ValueError('The value must be an integer')
return n == n[::-1]
if __name__ == "__main__":
try:
n = input("Please enter an integer: ")
ans = Palindrome(n)
if ans == True:
print("The number " + n + " is a palindrome")
elif ans == False:
print("The number " + n + " is NOT a palindrome")
except ValueError as e:
print(str(e))

how to make a conditional loop and a divison by zero is invalid

How to make a conditional loop and ("Divison by zero is invalid")
could not find an answer that works I searched for the past day or so
[: https://i.stack.imgur.com/CfcFo.png][1]
The answer is to use while loop:
print("Welcome to the amazing calculator!\n\n")
loop = True
while(loop):
print("--------------------------------------------")
one = float(input("Enter the first number:"))
two = float(input("And now the second one:"))
print("Choose what you want to do with those two numbers: \n")
print("Add -> '+'\n Substract -> '-'\n Multiply -> '*'\n # And so on...\n")
sign = input("So which action do you need? ")
# Now, here you check all conditions etc. I'm not writing this for you ;)
# In order to use the MATCH keyword you need at least python 3.10
match sign:
case "/":
if two == 0:
print("You cannot divide by ZERO!")
else:
print(f"Result of division: {one / two}")
case "+":
print("And so on...")
# If you don't have python 3.10 installed, just use if/else like you did in your code
if sign == "/":
if two == 0:
print("You cannot divide by ZERO!")
else:
print(f"Result of division: {one / two}")
# And when user wants to exit the program
else:
print("Exiting program....")
loop = False
I hope my answer was sufficient and now you know, how to program the best calculator ever known to humanity :D

Python While loop won't exit when asked to

I don't understand why when the user enters "0" the loop won't exit.
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
import sys
sys.exit()
if integerIn == "0":
done = True
else:
integers.append(integerIn)
return integers
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
import sys
sys.exit()
Everything above here is fine, but as soon as you got to the comparison, you forgot that you've casted the input to an int.
if integerIn == "0":
Should be
if integerIn == 0:
The reason is because integerIn is an integer and you are treating it like a string in if integerIn=="0". Replace it with integerIN==0 will do the job.
You're converting to an integer and then checking for equality with the string "0".
EDIT: screw the advice about using input or raw_input. Just saw you python 3.x tag, but decided to leave it for future readers.
You have few problems there...
First, in this line:
integers.append(integerIn)
where is integers to begin with? unless it's a global name you must define it in your function.
Second, in this line:
if integerIn == "0":
you're comparing integer to string here, and here's a thing: in python (using python 2.7 here) a string will be bigger than any number if you're doing a comparison, so integerIn == "0" will evaluate to False, always.
Fix it with this:
if integerIn == 0:
Finally, I should tell you this... your code the way it looks like will throws NameError instead of executing what you've done in your except statement.
Try it with the following test cases and try to explain the behavior yourself :)
Please enter an integer < 0 to finish >: test
Please enter an integer < 0 to finish >: "test"
To avoid such problem next time, use raw_input instead of input. So this line:
integerIn = input("Please enter an integer < 0 to finish >: ")
should be like this:
integerIn = raw_input("Please enter an integer < 0 to finish >: ")
NOTICE: I'm not sure but I think raw_input doesn't exist in python 3.x, instead input there will do exactly the same. please correct if I'm wrong.
However, If you're using python 3 then I think you should have no problem.
Here's input vs raw_input() in python 2.x:
input will evaluate the user input then return it.
raw_input will return the user input as string.
so:
# python 2.x
foo = input("input something") # input 3 + 5
print foo # prints 8
bar = raw_input("input something") # input 3 + 5
print bar # prints "3 + 5"
Try this
if integerIn == 0:
should work now.

Python Invalid Syntax on simple Maths Program

I am trying to create a random maths question quiz but the colon comes up as invalid syntax. Is it due to the operator I can not use the colon? If I take it out it is also seen as invalid syntax.
This is the code to create the 'correct_answer' variable so if the users in putted answer is correct or incorrect it lets them know. If the whole code is needed (which I'm sure it won't be as this is probably something really stupid i'm missing) I can post it.
if operator==+:
correct_answer=random_number1+number2
elif operator==-:
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2
FULL CODE:
import random
name=raw_input("Hi what's your name?")
print "Alrighty lets go, "+name+"!"
for i in range(10):
operator_list=('+','-','x')
operator=random.choice(operator_list)
random_number1=random.randint(1,12)
random_number2=random.randint(1,10)
question=1
print random_number1, operator, random_number2
if operator==+:
correct_answer=random_number1+number2
elif operator==-:
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2
answer = eval(str(int(raw_input("What is the answer?"))))
if answer==correct_answer:
print "Great job!"
else:
print"Unlucky pal! It was " +correct_answer+ "
question+1
I'm assuming that + and - are strings. If so, you need quotes around them. It's also good practice to space out your code to make it more legible.
if operator == '+':
correct_answer = random_number1 + number2
elif operator == '-':
correct_answer = random_number1 - number2
else:
correct_answer = random_number1 * number2
ANSWER: All that was needed were speech marks around the operator.
if operator == "+":
correct_answer=random_number1+number2
elif operator == "-":
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2
Ans:
When you wrote + and - , python took it as a real for integer operator and gave it an error because there were no numbers. Adding " " will define it as a string and should not give a error.
Corrected version:
if operator == "+":
correct_answer=random_number1+number2
elif operator == "-":
correct_answer=random_number1-number2
else:
correct_answer=random_number1*number2

Taking apart strings in Python

So I am making a quick calculator script in Python, and I need to take apart a short string. The program first displays a short welcome message, then a prompt asks What they want to do calculate, and shows them the correct format. The functionality is there to do the calculation but unfortunately, I can not get the string dissecting bit working.
Here's my code
print ("--------------------------------------")
print (" ")
print ("Advanced Quick Calculator")
print ("By Max M, licenced under GPLv3")
print (" ")
print ("--------------------------------------")
statement = raw_input ("Please enter your mathematical statement [3 3 plus minus times divide]: ")
strnum1 = statement[:1]
print ("strnum1 : " + strnum1)
#num1 = int (strnum1)
strnum2 = statement[:4]
print ("strnum2 : " + strnum2)
#num2 = int (strnum2)
operation = statement[5:11]
print ("operation : " + operation)
#if operation == "+":
# ans = num1 + num2
#if operation == "-":
# ans = num1 - num2
#if operation == "*":
# ans = num1 * num2
#if operation == "/":
# ans = num1 / num2
#print ("The answer is : "), ans
This looks like a job for regular expressions:
>>> import re
>>> match = re.search(r'(\d+)\s*([+*/-])\s*(\d+)', '42 + 7')
>>> match.group(1) # <-- num1
'42'
>>> match.group(2) # <-- operation
'+'
>>> match.group(3) # <-- num2
'7'
Slicing the input like you're currently doing is probably not a good idea as it greatly restricts the allowed formats. For instance, what if the user accidentally precedes his input with a couple of spaces? Regular expressions can handle such cases well.
I'm not going to do your homework for you, but I will point you to the answer to your question (hint: it looks like you're trying to split on spaces instead of comma's like in the link, so adjust the code accordingly).
How to read formatted input in python?

Categories

Resources