I'm new to Python. When I run this code, the last part where the results should be calculated is not shown on shell. Can someone tell me how should I fix this? The last part seems a little bit awkward, but I have no idea how to convert str into operations.
# Set variables
opList = ["plus", "minus", "times", "divided-by", "equals"]
# Instrution
print("Intructions: Please enter + as plus, - as minus, * as times and / as divided-by.")
# Read user's equation as a string
equation = input("\nPlease, enter your equation by following the syntax expressed above: ")
# Echo to the screen what the user has entered
print('The equation you entered is "%s".' %equation)
# Parse the equation into a list
theParts = equation.split() # default is whitespace
# print("Here is a list containing the operands and operator of the equation: ", theParts) # For debugging purposes
if len(theParts) == 0 :
print("\nHave you simply pressed the Enter key? Please, enter an equation next time! :)")
elif len(theParts) == 1 :
print("\nThis is not a equaltion so it cannot be calculated. Please, enter an equation next time! :)")
elif len(theParts) == 2 :
print("\nThis is not a equaltion so it cannot be calculated. Please, enter an equation next time! :)")
elif len(theParts) == 3 :
print("\nThe equation entered by the user is %s %s %s." %(theParts[0], theParts[1], theParts[2]))
if theParts[1] is str("plus"):
theAnswer == theParts[0] + theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
elif theParts[1] is str("minus"):
theAnswer == theParts[0] - theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
elif theParts[1] is str("times"):
theAnswer == theParts[0] * theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
elif theParts [1] is str("divided-by"):
theAnswer == theParts[0] / theParts[2]
print('The anwser of the input equation is "%i".' %theAnswer)
print("\nBye!")
Assuming you're using Python 2.x, the main issue that's getting you hung up is that you're using input instead of raw_input. input will evaluate your equation and use the evaluation in your program, whereas raw_input will get exactly what the user types as a string. For example:
input
# what the user types
3 + 7
# what the program gets as an integer
10
raw_input
# what the user types
3 + 7
# what the program gets as a string
"3 + 7"
No matter what version of Python you're using, you'll have to fix the following:
Indentation
You'll need to indent the code for your case where theParts has three integers so it executes only then. Otherwise it will execute no matter what and give you an array out of bounds error or the you'll get an indentation formatting error.
Testing string equality
Rather than use is str("[string]") simply use ==. Don't try to over-complicate things.
Strings vs. Numbers
In order to do math, you'll have to convert your strings to numbers. You can do that using something like int("5") which is equal to 5 (integer).
Example Code
# case 3
elif len(theParts) == 3:
# do stuff
if "plus" == theParts[1]:
theAnswer = int(theParts[0]) + int(theParts[2])
Assuming you are using a modern Python, input is actually the correct function to use (there is no raw_input in 3.x, and input is always a string). But, as mentioned, there are other problems.
Here's a version with some corrections.
# Instruction
# I changed the instructions to make them more precise and get rid of the unneccesarily awkward operators
print("Instructions: Please enter a simple equation of the form 'integer [operator] integer', where [operator] is '+', '-', '*' or '/'.")
print("Instructions: Make sure to put spaces between each element.")
# Read user's equation as a string
equation = input("\nPlease, enter your equation by following the syntax expressed above: ")
# Echo to the screen what the user has entered
print('The equation you entered is "%s".' % equation)
# Parse the equation into a list
theParts = equation.split() # default is whitespace
# print("Here is a list containing the operands and operator of the equation: ", theParts) # For debugging purposes
if len(theParts) == 0 :
print("\nHave you simply pressed the Enter key? Please, enter an equation next time! :)")
# Since the two conditions warranted the same response, I just condensed them.
elif len(theParts) == 1 or len(theParts) == 2:
print("\nThis is not a equaltion so it cannot be calculated. Please, enter an equation next time! :)")
elif len(theParts) == 3 :
#print("\nThe equation entered by the user is %s %s %s." % (theParts[0], theParts[1], theParts[2]))
# I set the answer before the conditions to a float, so division can result in more meaningful answers
theAnswer = 0.0
# I cast the input strings to integers
p1 = int(theParts[0])
p2 = int(theParts[2])
if theParts[1] is str("+"):
theAnswer = p1 + p2
elif theParts[1] is str("-"):
theAnswer = p1 - p2
elif theParts[1] is str("*"):
theAnswer = p1 * p2
elif theParts [1] is str("/"):
theAnswer = p1 / p2
print('The anwser of the input equation is "{}".'.format(theAnswer))
print("\nBye!")
If you wanted division to have a more school book response, with a quotient and remainder, then instead of p1 / p2, you should use divmod(p1, p2) and parse out the two parts in your printed response.
Related
I'm new in coding or programming so I hope for respect.
How can I create a program that continually accepts input from the user. The input shall be in this format operatornumber like -3
Like
num = 0
while((a := input("Enter operatornumber like -9;")) != "-0"):
if (len(a) >= 2) and (a[0] in "/*-+"):
num = eval(f"{num}{a}")
else:
print("Invalid input, try again.")
print(num)
But how can I make the first input of the user to only use the add (+) or subtract(-) operators but in the next input they can now use the other operators.
Like
Enter operatornumber like -9; +9
Enter operatornumber like -9; -8
Enter operatornumber like -9; -0
1
And how can I combine all the input like
+9-9 is 1?
In the input statement, you're closing the "Enter operator and number like" msg. This is creating more problems after that line, where all green parts are considered as string now. Also, in while statement, "w" should be small letter, python is case sensitive. Try doing this:
Number = input("Enter operator and number like '-9' ")
Operator = ("+","-","/")
while Number == (Operator + Number):
if Number == "-0":
Total = 0
Total += Number
print(f"the result of {num} is {total} ")
You can use double quotes for the text and single quotes for the number, so they don't close each other.
You can get input forever using following code:
while True:
Number = input("Enter operator and number like '-9'")
# Place your next code here.
Here is another answer. We have to take input from user with operator as well, so len(<user_input<) should be >=2. Now, we'll take another variable h in which we'll traverse the string from index 1 to end, which means the operator gets removed and we'll convert it into int. Then we'll put if condition in which we'll check the user_input[0] is +,-,*,/ and then acc to that, we'll update the result. We'll ask the user whether he wants more operations or no, if y, then keep asking, else, break the while loop. Here's my code:
result=0
while True:
a=input("Enter operator and number= ")
if len(a)>=2 and a[0] in ["+","-","*","/"]:
h=int(a[1::])
if a[0]=="+":
result+=h
elif a[0]=="-":
result-=h
elif a[0]=="*":
result*=h
elif a[0]=="/":
result/=h
else:
print("choose only from +-/*")
else:
print("invalid input")
ch=input("Enter more?")
if ch=='n':
break
print(f"The result is {result}")
Check for indentation errors because I've copied and pasted it so it may have indentation errors
here is my code, it does run but the output is not the way it should be
formula = input("Enter a formula: ")
parenthesis = (formula.count("(,)"))
if parenthesis >= 1 :
print ("You have enteread a complete formula.")
else:
print ("You have incomplete set of parenthesis")
Maybe I'm oversimplifying in my head, but here is a simple way of doing it:
formula = input("Enter a formula: ")
open_brackets = formula.count("(")
close_brackets = formula.count(")")
if open_brackets == close_brackets:
print("You have entered a complete formula.")
else:
print("You have incomplete set of parenthesis")
I went through a lesson of creating a simple calculator using Python, and I'm trying to simplify it.
The issue is as follows:
I know that it is possible to parse a string (number) into a float using "float()", but I'm trying to parse a addition/subtraction/multiplication/division sign from a string into a float or integer or any other format that would perform the action. Here's a sample of what I'm trying to do:
while True:
user_input = input("""
quit - exit program
add - addition
sub - subtraction
mul - multiplication
div - division
Please choose function:""")
actions = ("+-*/")
user_input_1 = float(input("first number:"))
user_input_2 = float(input("second number:"))
operation = user_input_1 float(action) user_input_2
if user_input == "add":
action = actions[0]
answer = operation
print (answer)
If the user_input is "add"
user_input_1 is "5"
user_input_2 is "7"
then the print(answer) should result in 12
This is just the first part of the code, and I'm getting a syntax error. The issue is most likely the inability to parse the addition sign using "float()". Is there another way of parsing the signs?
Even though you should be posting the full traceback, the SyntaxError comes from this line:
operation = user_input_1 float(action) user_input_2
It is neither a valid Python expression nor a statement.
A solution that doesn't involve eval:
You can use the operator module and a dictionary from "sign" to the operator itself, as seen in this very basic (and error prone) example:
import operator
operations_dict = {'+': operator.add,
'-': operator.sub} # extend to other operators you see fit
a = float(input('first num'))
b = float(input('second_num'))
sign = input('operator')
print(operations_dict[sign](a, b))
>> first num
1
>> second num
2
>> operator
+
>> 3.0
You can use eval in the form eval('1 + 2'), which will give you desired result.
You can read more on eval here https://docs.python.org/2/library/functions.html#eval
but please keep in mind the following statement
The user can expose hidden values in the program, or call a dangerous
function (dangerous_function("/etc/passwd")). Of course in most cases
(desktop programs) the user can't do any more than they could do by
writing their own python script, but in some applications (web apps,
kiosk computers), this could be a risk.
which is from http://lybniz2.sourceforge.net/safeeval.html
In your case this should work :
def operation(action):
return user_input_1 + action + user_input_2
if user_input == "add":
action = actions[0]
answer = operation(action)
print (eval(answer))
but that's not the best way to do the operations. You can simply add or divide like this or you can construct a dictionary for the operations:
def operation(action):
if(action == "add"):
return user_input_1 + user_input_2
elif action == "sub":
return user_input_1 - user_input_2
elif action == "div":
return user_input_1 / user_input_2
# and so on....
answer = operation(user_input)
print (answer)
I do not recommend using eval() however; setting some rules won't hurt using eval(). This is really basic calculator and its easy to understand.
allowed_characters = "0123456789+-/*= "
print("""
Basic calculator application.
Operators:
+ addition
- subtraction
* multiplication
/ division
Type the desired operation and press ENTER.
(Example 23 and 46 to multiple
Type 23 * 46 then press ENTER.)
""")
while True:
data = input("Please enter your calculation: ")
if data == "q":
print("Exiting...")
break
for s in data:
if s not in allowed_characters:
print("Invalid character!")
quit()
calculate = eval(data)
print(calculate)
The validation doesnt work. im not sure why, is there a way to validate a string. The questions asked are endless i need 10 questions to be asked
import random
name=(input("Please enter your name"))
print("welcome",name,"the arithmetic is about to start")
question=0
while question<10:
number=random.randint(1,10)
numbers=random.randint(1,10)
arith=random.choice("+" "-" "/")
if arith=="+":
print(number,arith,numbers)
answer=number+numbers
if arith=="-":
print(number,arith,numbers)
answer=number-numbers
if arith=="/":
print(number,arith,numbers)
answer=number/numbers
while True:
try:
usersanswer= int(input())
except ValueError:
print ("That is not a valid answer")
continue
if usersanswer==answer:
print("correct")
break
else:
print("incorrct")
The validation doesnt work. im not sure why, is there a way to validate a string
I've taking silentphoenix's answer and made it somewhat more pythonic and six'ed.
You should almost never use python2's input, because on top of being massive security hole, it sometimes does things that can be...rather unexpected.
import random
import operator # contains the python operators as functions
try:
input = raw_input # rebind raw_input to input, if it exists
# so I can just use input :P
except NameError:
pass
name = input("Hi, what is your name?\n")
print("Hi {} let's get started! Question 1".format(name))
#Get out of the habit of using string concatenation and use string
#formatting whenever possible. Strings are *immutable*;
#concatenation has to produce a lot temporary strings and is *slow*
#str.join and str.format are almost always better ideas.
#Python does not have a switch-case, so emulating one with a dictionary
operator_mapping = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
#'/': operator.truediv, #hey, division exists.
#But if you want division to actually work, you'll
#have to introduce a fudge factor :P
}
for i in range(10): # If you're just going for 10 iterations, it should be a for loop
# Brevity :P This is a list comprehension
first_number, second_number = [random.randint(1,10) for _ in range(2)]
oper = random.choice(list(operator_mapping))
answer = operator_mapping[oper](first_number, second_number)
while int(input("{} {} {} = ".format(first_number, oper, second_number))) != answer:
#while abs(float(input("{} {} {} = ".format(first_number, oper, second_number)))-answer) < 0.001: if you want truediv.
print('Wrong answer! try again!')
#If I've left the loop, user has given correct (enough) answer
if i <9: # all but last
print('Well done! Now onto question number {0}'.format(i+2))
print('Well done! You are done!')
In the third line, you ask for input. But a name is a string, so you need raw_input. raw_input takes strings, input only takes numerical values.
Python 2.7 getting user input and manipulating as string without quotations
Nowhere in your code do you update the variable questions, which I am guessing is a counter. You have to update that whenever a question is asked, using question += 1.
Finally, your code at the end does not really make sense. Based off the code, it checks for whether or not it is a string, but then compares it to the answer regardless. The if statement needs to be within the try.
The else statement does not match any outer indentation.
Finally, because of the while True: your code will never exit the loop unless the answer is wrong. At the point the entire program terminates. I see what kind of program you are trying to write, but the parameters for random number generation have to be within some kind of a while question <= 10 loop. As of now, only two lines in the program are being affected by that first while loop.
EDIT: I am working on a good example code. Hopefully this answer will help until I can finish it.
EDIT: Here is code that shows how it works within a while loop.
import random
from random import randint
name = raw_input("Hi, what is your name?\n") # Asks for name
print "Hi " +name+ " let's get started!"
score_count = 0
question_count = 0 # creates counter
while question_count <= 10: # Everything MUST BE WITHIN THIS LOOP
# makes numbers and operator
first_number = randint(1,10)
second_number = randint(1,10)
oper = random.choice("+""-""*")
# determines the problem
if oper == "+":
answer = first_number + second_number
print first_number,second_number,oper
elif oper == "-":
answer = first_number - second_number
print first_number,second_number,oper
elif oper == "*":
answer = first_number*second_number
print first_number, second_number, oper
user_answer = int(raw_input("Your answer: "))
if user_answer != answer:
print 'Wrong answer! try again!'
user_answer = int(raw_input('Your answer: '))
if user_answer == answer: # exits the while loop when the correct answer is given
if question_count < 10:
print 'Well done! Now onto question number {0}'.format(question_count+1)
score_count += 1
elif question_count == 10:
print 'Well done! You are done!'
score_count += 1
else:
print 'Something is wrong.'
question_count += 1 # updates the variable
# GOES BACK TO THE BEGINNING UNTIL question_count IS GREATER THAN OR EQUAL TO 10
print "Your score was: {}".format(score_count)
Happy coding! and best of luck!
hi im Nathan and I saw this post I am 5 years to late but I figured if someone on here is knew to python I have a much easier (in my opinion) way to do this in python 3, the code is below:
import random #random module automatically downloaded when you install python
name = input("Please enter your name ")
print("welcome",name,"the arithmetic is about to start")
question=0
while question<10:
number=random.randint(1,10) #creating a random number
numbers=random.randint(1,10) #creating a random number
list = ["+","-","/"] #creating a list (or sometimes called array)
arith=random.choice(list) #getting random operators from list (+,-,/)
question += 1 #basically means add one to question variable each time in loop
if arith=="+":
print(number,arith,numbers)
answer=number+numbers
elif arith=="-":
print(number,arith,numbers)
answer=number-numbers
elif arith=="/":
print(number,arith,numbers)
answer=number/numbers
answer = int(answer)
#from HERE
useranswer = "initialising this variable"
while useranswer == "initialising this variable":
try:
usersanswer= int(input())
if usersanswer==answer:
print("correct")
break
else:
print("incorrect")
except ValueError:
print ("That is not a valid answer")
#to HERE it is input validation this takes a while to explain in just commenting
#but if you dont know what this is then copy this link https://youtu.be/EG69-5U2AfU
#and paste into google for a detailed video !!!!!!
I hope this helps and is a more simplified commented bit of code to help you on your journey to code in python
Here is my code as show below:
menu= "Welcome to the menu\n" \
+ "Please select an option below:\n" \
+ ( "0 - Enter a number\n" + "1 - Display current number\n" + \
"2 - Divisibility checking\n" + "3 - Perfect checking\n" + \
"4 - Triangular checking\n" + "5 - Quit\n" )
x == ("")
while option!=5: # <<< Q2
print(menu)
option= int(input("Enter option: "))
if option==0:
x= int(input("What is your number?: "))
while x <=0:
x= int(input("Must be positive, please! What is your number?: ")
elif option==1: # <<< Q1
print("The current number is", x)
elif (x == ""):
print("No number yet - Please input a number and try again.")
x= int(input("What is your number?: "))
Q1:
I was wondering why I kept getting an error message for line 14 of my code, for the second elif statement.
Q2:
I was also wondering how, for my first while statement, I might define "option" for option!=5 and then print the menu if I had not prompted the user to enter an option yet.
Any help on these two cases would really be appreciated.
Thank you.
concerning your second elif-statement, I think you got the nesting wrong.
You have one outer decision tree, where you go through the available option, the tree is:
if option == 0 --> do a
elif option == 1 --> do b
elif option == 2 --> do c and so on
You don't need in inner elif, because it is NOT an else statement to the chosen option. You are just starting a new decision tree (You try to find if x is already assigned and if not ask for a number, otherwise show the number). Therefore the correct code should be:
elif option == 1:
if x == "":
print("No number yet - Please input a number and try again.")
x= int(input("What is your number?: "))
else:
print("The current number is", x)
elif option == 2
--> Handling of option 2
This should work. I took the freedom to put the if-statement first, otherwise you would get the output
"The current number is "
"No number yet - Please input a number and try again."...
I think this is pretty much what Ignacio meant, when he asked, if you knew what the elif belongs to.