python using the "if" statement [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Take in two numbers and a letter. If the letter is "a", the numbers will be added, if "s", subtracted, if "m", multiplied, and if "d", divided.
This is what I have:
num1 = int(input("please enter the first number"))
num2 = int(input("please enter the second number"))
lettler = input("please enter the operation")
a = int(num1 + num2)
s = int(num1 - num2)
m = int(num1 * num2)
d = int(num1 / num2)
if lettler + str(a):
print(num1 + num2)
else:
if lettler + str(s):
print(num1 - num2)
else:
if lettler + str(m):
print(num1 * num2)
else:
if lettler + str(d):
print(float(num1) / num2)
But my professor is telling me it is wrong. What can I do to fix it?

Your real problem here is that you're thinking out of order. You read the problem, and then started writing a solution before you really understood what it was asking for. That's actually really common to do when you see a big blob of text, and it takes practice and skill to go from there to a correctly working program.
Let's take this step by step:
Take in two numbers and a letter. If the letter is "a", the numbers will be added, if "s", subtracted, if "m", multiplied, and if "d", divided.
Here's the assignment. Rather than leave it in this form, let's convert it to a form that's easier to think about piece by piece:
Take in two numbers and a letter
if the letter is 'a', the numbers will be added
if the letter is 's', subtracted
if 'm', multiplied
and if 'd', divided
You'll notice that I didn't change any of the text here, I just shifted the formatting around. If you read the two, you'll see that there's no difference between them.
Now we can think about turning that into code, because it's layed out like code. You may have heard the term "pseudocode", which means "something that is code-like". We could even do that here.
# Take in two numbers and a letter
num_one, num_two, letter = get_two_numbers_and_letter()
if letter is a: # if the letter is 'a'
print(num_one+num_two) # the numbers will be added
if letter is s: # if the letter is 's'
print(num_one-num_two) # the numbers will be subtracted
if letter is m: # if 'm'
print(num_one*num_two) # multiplied
if letter is d: # and if "d", divided
print(num_one/num_two)
You'll notice that this already looks an awful lot like Python. We can clean it up a little:
# take in two numbers
num_one = int(input('First number: '))
num_two = int(input('Second number: '))
# and a letter
letter = input('(a)dd, (s)ubtract, (m)ultiply, or (d)ivide? ')
# if the letter is 'a', the numbers will be added
if letter == 'a':
print(num_one + num_two)
# if the letter is 's', subtracted
if letter == 's':
print(num_one - num_two)
# if 'm', multiplied
if letter == 'm':
print(num_one * num_two)
# and if 'd', divided
if letter == 'd':
print(num_one / num_two)
Of course now the comments are a bit superfluous - all they describe is exactly what the code is doing. We're also using if instead of elif, which is a bit ambiguous and less efficient (not that that really matters at this point, but it's still true). So let's clean up the code just a little bit more:
num_one = int(input('First number: '))
num_two = int(input('Second number: '))
letter = input('(a)dd, (s)ubtract, (m)ultiply, or (d)ivide? ')
if letter == 'a':
print(num_one+num_two)
elif letter == 's':
print(num_one-num_two)
elif letter == 'm':
print(num_one*num_two)
elif letter == 'd':
print(num_one/num_two)
else:
print("I'm sorry, I don't recognize letter", repr(letter))
Bonus - On Debugging
If your professor has not been teaching you about the REPL then they're doing you a disservice. The REPL is great, and especially for beginners. You can experiment and get feedback immediately. Let's consider part of your original code:
num1 = int(input("please enter the first number"))
num2 = int(input("please enter the second number"))
lettler = input("please enter the operation")
a = num1+num2
if lettler + str(a):
print(num1 + num2)
You could just copy and paste this into the REPL, or even better, skip out on the input part, and just assign the values you want:
>>> num1 = 3
>>> num2 = 5
>>> lettler = 'a'
>>> a = num1 + num2
>>> if lettler + str(a):
... print(num1 + num2)
...
8
Great! We got what we expected! But... that's not actually how you verify an experiment. You have to design something that should fail. So what if we try lettler = 's'?
>>> if lettler + str(a):
... print(num1+num2)
...
8
Huh. Well, that's not right. We should have just got nothing. Luckily, this is pretty simple, it's just an if statement and a call to the print function. We know it's not the print that's the problem, our code never should have made it to that point. So let's check on what's in the if statement:
>>> lettler + str(a)
's8'
Oh. That's a string. Hm. It's not an empty string, and it's true. Maybe you remember this from class, but maybe you don't. So let's go to google and type in 'python why is my non-empty string true?'
When I do that the first result I get is https://stackoverflow.com/a/9573259/344286 Which does a pretty good job of explaining it, and better yet, it even links us to the official documentation that tells us:
By default, an object is considered true...
Here are most of the built-in objects considered false:
...
empty sequences and collections: ''...
Ahh! So because our string is not empty ('s8') it's going to evaluate to True! Well, okay. So what do we actually want to do instead? We probably don't want to be adding strings together. Can we compare things instead? What if we try ==?
>>> lettler = 'a'
>>> lettler == str(a)
False
Hm. Well, that's not what we expected, was it? I guess let's see what the values are:
>>> lettler
'a'
>>> a
8
Oh. Well yeah, those aren't equal! And a isn't the letter 'a'. Oh that's right! We said that a = num1 + num2, so of course it's not a letter. Maybe in the future we shouldn't use letters for variable names. If we take a step back and think about what we want (if the letter is "a" the numbers should be added) then we have the answer. We want to compare lettler to "a":
>>> if lettler == 'a':
... print(num1 + num2)
...
8
>>> lettler = 's'
>>> if lettler == 'a':
... print(num1 + num2)
...
>>>
Ah. Perfect!

An if statement works by testing if the expression you put after the if keyword is true. What you’re doing is adding two strings. In python, a string with characters will always come out to true, thus, the first if is always executed. What I have done is modify your conditions to match what you want:
num1 = int(input("please enter the first number: "))
num2 = int(input("please enter the second number: "))
lettler = input("please enter the operation: ")
if lettler == 'a':
print(int(num1 + num2))
elif lettler == 's':
print(int(num1 - num2))
elif lettler == 'm':
print(int(num1 * num2))
elif lettler == 'd':
try:
print(float(num1 / num2))
except ZeroDivisionError:
print('You tried to divide by zero')
See how I test if lettler (your operation input) is equal to the corresponding letter? That’s what you want. I also added a try/except that makes sure your program doesn’t crash if you divide by zero.

num1 = int(input("please enter the first number"))
num2 = int(input("please enter the second number"))
lettler = input("please enter the operation")
a = int(num1 + num2)
s = int(num1 - num2)
m = int(num1 * num2)
d = int(num1 / num2)
if lettler == "a":
print(num1 + num2)
elif lettler == "s":
print(num1 - num2)
elif lettler == "m":
print(num1 * num2)
elif lettler == "d":
print(float(num1) / num2)

Related

Why do the math problems in my program repeat the same equation? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 months ago.
This post was edited and submitted for review 6 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
So, I'm trying to make a math problem in Python, since I'm a beginner learning how to code. Basically, it asks you how many questions you want to answer, and to answer questions of addition, subtraction, multiplication, and division correctly.
Let me show you the code I have, so far.
import random
num_question = (int)(input("Enter how many questions would you like to solve: "))
num1 = random.randint (0,20)
num2 = random.randint (0,20)
oper = ["+","-","*","/"]
operator = random.choice(oper) #chooses a variable in the "oper" list at random. Then it is used in the question
for count in range (0, num_question):
question = (num1, operator, num2) #e.g. What is 6 - 2
print (question)
guess = (int)(input("Enter here: "))
answer = 0
if operator == "+": #if the operator chooses addition, the answer will equal the sum of both numbers. The same goes for the other if statements.
answer = (num1 + num2)
elif operator == "-":
answer = (num1 - num2)
elif operator == "*":
answer = (num1 * num2)
elif operator == "/":
answer = (num1 / num2)
if guess == answer: #if the answer is equal to the question, then it's correct and proceeds. Otherwise, it doesn't.
print ("Correct!")
continue
else:
print ("Incorrect. Please try again.")
However, the drawback is that the same question repeats everytime (I am using my old laptop, so the p button and the quotation button is broken). Now my question is how to make the questions not repeat themselves.
There are a couple problems.
You are testing for equality with "==" inside the "if" statements, when you probably would like to assign the true answer to a variable to compare to the user's guess
You are comparing the answer to the question, which is a string, which will never be equal
Fix the first one by creating a new variable for the true answer to keep it separate from the guess. Fix the second by comparing the guess to the real answer.
guess = (int)(input("Enter here: "))
answer = 0
if operator == "+": #if the operator chooses addition, the answer will equal the sum of both numbers. The same goes for the other if statements.
answer = (num1 + num2)
elif operator == "-":
answer = (num1 - num2)
elif operator == "*":
answer = (num1 * num2)
elif operator == "/":
answer = (num1 / num2)
if answer == guess : #if the answer is equal to the question, then it's correct and proceeds. Otherwise, it doesn't.
print ("Correct!")
break
answer == (num1 + num2)
You're using two equal signs, which is an equality test, not an assignment.
You're overwriting the user's answer with the correct result. Then you're comparing that with the question text, not the user's answer.
Also you need to use = to assign, not ==.
Use a different variable for the correct answer, and compare that with the user's answer.
or count in range (0, num_question):
question = ("What is " + str(num1) + " " + operator + " " + str(num2) + "?") #e.g. What is 6 - 2
print (question)
answer = int(input("Enter here: "))
if operator == "+": #if the operator chooses addition, the answer will equal the sum of both numbers. The same goes for the other if statements.
correct = (num1 + num2)
elif operator == "-":
correct = (num1 - num2)
elif operator == "*":
correct = (num1 * num2)
elif operator == "/":
correct = (num1 / num2)
if correct == answer:
print ("Correct!")
break
else:
print ("Incorrect. Please try again.")

How to skip an input and make an error code?

I'm very very veryy new to python and coding in general. I'm still learning the very basics, but I'm also trying to just play around and try out different things in python. I have tried making a very basic calculator that can +, -, *, /, take a number to the power of another number, and take the square root of 1 number.
Only thing I don't know how to do is skip the third input with num2, when I put in operator "sqrt" so I only take the sqrt of num1. Also I want to tell the user that if they put in an input for num1 that is less than 0 then they get an error.
Idk if I need to learn more to do something like this? I haven't learned about loops yet so I'm still very very new. Hope I can get some helps
#Making a basic calculator
from math import*
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "/":
print(num1 / num2)
elif op == "*":
print(num1 * num2)
elif op == "^":
print(pow(num1,num2))
elif op == "sqrt":
print(sqrt(num1))
elif op == "sqrt" and num1 <= 0:
print("You cannot take the square root of numbers smaller than 0")
else:
print("Invalid operator")
The simplest thing to do is check what op is and only ask for num2 if you need it:
op = input("Enter operator: ")
if op != "sqrt":
num2 = float(input("Enter second number: "))

Calculator in Python can't print out the result I want

I wanted to create this calculator in Python and I had some problems when it printed out. The problem was that everytime that I ran the program it printed out Check for errors. When I removed it, it started to print me out numbers put together. For example 1 + 2 = 12 or 2 + 5= 25, etc.This thing happened only when I tried to add two numbers, when I tried multiplying, subtracting or dividing it didn't print out anything. This is my code:
print ("Enter your first number")
num1 = input()
print("Enter your second number")
num2 = input()
print("Enter operation")
operation = input()
if operation is "+":
print(num1 + num2)
elif operation is "*":
print(num1 * num2)
elif operation is "/":
print(num1 / num2)
elif operation is "-":
print(num1 - num2)
else:
print("Check for errors")
#Fjoni Yzeiri: Hi folk,
This is a common issue when starting with Python, as you don't declare the variable type of the input, it will save it as a String, so if you concatenate (+ in Python) it will concatenate the two Inputs.
To solve this you have to explicitly cast this values into Integers, it means:
print ("Enter your first number")
num1 = int(input()) # Cast to int here
print("Enter your second number")
num2 = int(input()) # Cast to int here
print("Enter operation")
operation = input()
if operation is "+":
print(num1 + num2)
elif operation is "*":
print(num1 * num2)
elif operation is "/":
print(num1 / num2)
elif operation is "-":
print(num1 - num2)
else:
print("Check for errors")
Of course, this is a very simple use case, if you want to learn a bit more, try to caught the exception when it tries to cast a non-integer string. It will teach you nice stuff ;)
I think you want to be using == instead of is to compare string literals with a variable. I'd expect your usage to always return false.
The problem is solved now. Someone posted the answer but he deleted it I think and I couldn't upvote it. I needed to change
num1 = input()
to
num1 = int(input())

Random Maths Program

thanks for taking time to read this.
I have to create a program that generates 10 random maths questions based around =, - and *. I have the program working but everytime I run it after the main program it prints "none" even though that's not in my program.Any help at all would be much appreciated. Thank you.
import random
print ("Welcome")
name=input("What's your name?")
print("Nice to meet you", name, ",you will be given 10 multiplication, addition and subtraction questions.")
Num1 = random.randint(1,12)
Num2 = random.randint(1,12)
sign = random.randint(1,3)
if sign == 1: # If the random number generated is 1
question = Num1 + Num2
rightanswer1 = Num1 + Num2
answer1=input(print("What is", question ,"?"))
if answer1 == rightanswer1:
print("Well Done!")
if answer1 != rightanswer1:
print("Sorry, that's incorrect, the answer was", rightanswer1)
if sign == 2:
question = Num1 - Num2
rightanswer2 = Num1 - Num2
answer2=input(print("What is", Num1, "-", Num2 ,"?"))
if answer2 == rightanswer2:
print("Well done!")
elif answer2 != rightanswer2:
print("Sorry, that's incorrect, the answer was", rightanswer2)
if sign == 3:
question = Num1 * Num2
rightanswer3 = Num1 * Num2
answer3=input(print("What is", Num1, "x", Num2 ,"?"))
if answer3 == rightanswer3:
print("Well done!")
elif answer3 != rightanswer3:
print("Sorry, that's incorrect, the answer was", rightanswer3)`
> Welcome
> What's your name? John
> Nice to meet you John ,you will be given 10 multiplication, addition and subtraction questions.
> What is 12 x 3 ?
> None 36
> Sorry, that's incorrect, the answer was 36
I think you are using python 3. In python 3 input is like raw_input in python 2. So you get the string as input. So convert it into int
var = int(input("Enter a number: "))
So in your code make it as
print("What is", Num1, "x", Num2 ,"?")
answer3 = input()
answer3 = int(answer3)
See this:
whats-the-difference-between-raw-input-and-input-in-python3-x
I'm reluctant to just give you an answer that just does it for you, so instead i'll provide you with a few hints to improve things. (i.e. this isn't an answer, just too large of a comment - and more like a codereview answer)
First off, you use a structure like this:
if x == 1:
#do something
if x == 2:
#do something else
...
In this case, which it makes no difference, it is easier to read if you use the if syntax as intended:
if <condition>:
#do this if the above test is true.
elif <more conditions>:
#do this only if the first test is false and this one is true
elif <more conditions>:
#same as above, except for the second test must be false too
else:
#do this if all the above tests are false
So you could use this something like:
if sign == 1:
...
elif sign == 2:
...
elif sign == 3:
...
else:
# something weird happened...
Which would make that section of the program easier to follow.
The same thing can be done with the if answer1 == rightanswer1: sections;
if answer1 == rightanswer1:
#correct!
else:
#incorrect.
That would be a clearer was to do it. You seem to have used the if...elif style in a couple of them, but not the first one.
Once you have this, it will be a little clearer.
The next way you could improve things is by removing duplicated code. You don't need separate branches for each sign, you can just roll it all into one:
number1 = randint(1,12)
number2 = randint(1,12)
op = randint(1,3)
question_string = "%d %s %d = ?" % (number1, number2, ["+", "-", "*"][op])
result = None
if op == 1:
result = number1 + number2
elif op == 2:
result = number1 - number2
elif op == 3:
result = number1 * number2
This will do most of the logic for you, and generate the strings you want, without duplicating all of the other code.
Small changes like this can make things much more readable.
It's printing None because the print() function returns None and you're passing that value of None from print() as the prompt to your input() functions. Eg,
answer3=input(print("What is", Num1, "x", Num2 ,"?"))
So print("What is", Num1, "x", Num2 ,"?") prints its stuff, and returns None, which then gets printed as the prompt by input().
A simple way to fix this is to just move your print() function calls out of your input() functions.
Eg,
print("What is", Num1, "x", Num2 ,"?")
answer3=input()
However, there's another major problem with your program: the rightanswer variables are ints, but the inputted answers are strings. To compare them properly they need to be the same type. So you should either convert the inputted answers to int, or alternatively, convert the rightanswers to str.
There are two problems with how you use the input function:
You misuse the prompt argument
You forget to convert the result
First, have a better look at the reference of the input function
The prompt argument
input takes a string as argument that will be displayed ("prompted") to the user to indicate that the program is waiting an input. The print function also displays a string to the user, but it doesn't return anything. It does its job and that's all (and in Python a function that returns nothing, returns None). That's what input gets to display, so it displays None. You should use format instead. It will format and return the formatted string that input can display:
answer1_as_str=input("What is {} ?".format(question))))
or
answer2_as_str=input("What is {:d} - {:d} ?".format(Num1, Num2)))
The return value
input returns the user input as a string contrary to python 2 (i.e. exactly as entered). So you have to convert the input to the desired type if you need it. If you type 10 for example, the input will return "10". If you need an int, you have to convert it yourself.
answer1 = int(answer1_as_str)
It looks like you don't really understand how input() works. You might also want to review the different datatypes and conditional statements. Other than that, it was a very good attempt. Here's my solution:
from random import randint
print("Welcome")
name = input("What's your name?\n")
print("Nice to meet you " + name + ", you will be given 10 multiplication, addition and subtraction questions.")
for i in range(10):
print("\nProblem " + str(i+1))
num1 = randint(1,12)
num2 = randint(1,12)
sign = randint(1,3)
if sign == 1:
question = str(num1) + " + " + str(num2)
answer = num1 + num2
elif sign == 2:
question = str(num1) + " - " + str(num2)
answer = num1 - num2
else:
question = str(num1) + " x " + str(num2)
answer = num1 * num2
user_answer = input("What is " + question + "? ")
if user_answer == str(answer):
print("Well done!")
else:
print("Sorry, that's incorrect, the answer was", answer)

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