How to skip an input and make an error code? - python

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: "))

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.")

Do i have to create nested loops or can i do it with the try function?

Can someone explain to me why is asks for an input the second time someone enters an operator and a number?
It is an calculator and i want to except the Valueerror the sedcond time but the code always repeats twice and doenst exit the try function.
Can someone please help me in the right direction?
import locale
## Defining the calculator functions
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
## Asking for the first user input
while number_2 = None :
try:
operation, number_2 = input('''
Starting at zero
Please enter an operator and a number
Enter: ''').split()
continue
except ValueError:
print('Please put a space between the operator and the number!')
else:
break
##Making the input calculatable
number_1 = float(0)
number_2 = float(number_2)
## Calculating the outcome
i = 0
while i < 1:
if operation == '+':
number_1 = add(number_1, number_2)
print('Answer is: ', round(number_1, 4))
elif operation == '-':
number_1 = subtract(number_1, number_2)
print('Answer is: ', round(number_1, 4))
elif operation == '*':
number_1 = multiply(number_1, number_2)
print('Answer is: ', round(number_1, 4).format)
elif operation == '/':
number_1 = divide(number_1, number_2)
print('Answer is: ', round(number_1, 4))
else:
print("Invalid input")
## Asking for the second number
try:
operation, number_2 = input('''
Starting at the previous outcome
Please enter an operator and a number
Enter: ''').split()
except ValueError:
print('nee gap')
number_2 = float(number_2)
if operation == 'q':
break
enter image description here
You've written continue in the first try section, which means, if the condition is satisfied, it'll continue the loop again, and check for number_2 and if the input is correct, again it will continue the loop. So try deleting the continue statement, if the error is occured, it'll directly go to except section
Also, you've to write == to compare the values in while number_2 == None
And you've to define number_2 and operation before using it in while loop. It'll give you error that number_2 is not defined
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}")
Here, the user has to input both parameters as well as the number, I'm taking it as a string because you can traverse it later on and can seperate the operator and number. Initial result is 0. As the user puts the input, we'll traverse the string and seperate number and operator, (say "+9") operator will be <input>[0] and number will be int(<input>[1::]). Now we have seperated the numbers. Let's check for operator using if condition and calculate according. Hope this answer satisfies your aim, if not let me know your aim, I'll surely design a new one

python using the "if" statement [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 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)

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())

Python: How to prevent questions with negative answers being randomly generated

My task is to create a maths quiz for primary school children. this is what I have done so far:
import random
import math
def test():
num1=random.randint(1, 10)
num2=random.randint(1, 10)
ops = ['+', '-', '*']
operation = random.choice(ops)
num3=int(eval(str(num1) + operation + str(num2)))
print ("What is {} {} {}?".format(num1, operation, num2))
userAnswer= int(input("Your answer:"))
if userAnswer != num3:
print ("Incorrect. The right answer is {}".format(num3))
return False
else:
print ("correct")
return True
username=input("What is your name?")
print ("Welcome "+username+" to the Arithmetic quiz")
correctAnswers=0
for question_number in range(10):
if test():
correctAnswers +=1
print("{}: You got {} answers correct".format(username, correctAnswers))
What I now need to do is make my program only create questions with positive answers. e.g nothing like 3-10=-7
I've tried searching everywhere online but I cant find anything so I've turned to you guys for help. Any help will be appreciated :)
What I would recommend is:
#Random code...
if num1<num2:
num1, num2 = num2, num1
#Rest of program
So that 3 - 7 = -4 becomes 7 - 3 = 4
The reason I recommend doing this is that the answer would still be the same as the previous equation, just positive instead of negative, so you are still testing the same numbers.
Keep the larger number on the left of the expression, also use operator instead of eval:
from operator import add, sub, mul
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
d = {"+": add, "-": sub, "*": mul}
operation = random.choice(list(d)))
num1 = max(num1, num2)
num2 = min(num1, num2)
num3 = d[operation](num1, num2)
print("What is {} {} {}?".format(num1, operation, num2))
userAnswer = int(input("Your answer:"))
if userAnswer != num3:
print("Incorrect. The right answer is {}".format(num3))
return False
else:
print("correct")
return True
username = input("What is your name?")
print("Welcome {} to the Arithmetic quiz".format(username))
correctAnswers = sum(test() for question_number in range(10))
print("{}: You got {} answers correct".format(username, correctAnswers))
Or as #jonclements suggests sorting will also work:
num2, num1 = sorted([num1, num2])
On another note you should really be using a try/except to verify the user input and cast to an int otherwise the first value that cannot be cast to an int your program will crash.
You can choose the numbers such that num2 will be between 1 and num1 like:
num1=random.randint(1, 10)
num2=random.randint(1, num1)
or that num1 > num2:
n1=random.randint(1, 10)
n2=random.randint(1, 10)
num1 = max(n1,n2)
num2 = min(n1,n2)
i would go with the first option. no extra variables, no extra lines.
after the code that chooses the random numbers you can add this while loop:
while num3<0:
num1=random.randint(1, 10)
num2=random.randint(1, 10)
ops = ['+','-','*']
operation = random.choice(ops)
num3=int(eval(str(num1) + operation + str(num2)))
It will enter this loop every time the answer is negative. This will ensure that the answer is positive when the program quits the loop.
A change in one line should do it:
if num1 > num2:
num3=int(eval(str(num1) + operation + str(num2)))
else:
num3=int(eval(str(num2) + operation + str(num1)))

Categories

Resources