My program not showing question or taking inputs in Python - python

I made this simple Python Maths Quiz Program for some reason sometimes when it is supposed to ask a question it doesn't display the question or allow any input and just says it is incorrect. The problem doesn't happen every time I run the program just sometimes.
import random
def RandomNum():
import random
ran= random.randint(1,10)
return (ran)
def RanOperation():
import random
operation = ['+','-','x']
RanOp = random.choice(operation)
return (RanOp)
stop = False
while stop == False:
Name= input("Hello, what is your name?").title()
print("Hello,", Name, "Welcome to ARITHMETIC QUIZ")
score=0
for i in range(1, 11):
print(str(i)+".")
num1 = RandomNum()
num2 = RandomNum()
operation = RanOperation()
if operation == "+":
ans = num1+num2
elif operation == "-":
if num1 > num2:
ans = num1-num2
elif num2>num1:
ans = num2-num1
elif operation == "x":
ans = num1*num2
if num1 > num2:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num1+operation+num2+"=")))
elif num2 > num1:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num2+operation+num1+"=")))
if Answer == ans:
print("Correct!")
score += 1
elif Answer != ans:
print("The correct answer is", ans)
print("Sorry this is incorrect!")
length = int(len(Name))
print("You got", score, "correct out of 10,", Name)
File1 = open('Class_Scores.txt','a')
File1.write("\n %-20s %10d" %(Name , score))
File1.close()
Ask = input("Do you want to continue? Y/N").upper()
if Ask == "N":
stop = True
elif Ask == "Y":
stop = False

Your input() line only runs in two situations:
if num1 > num2:
and
elif num2 > num1:
What happens when num1 and num2 are the same? You won't enter the if block, because num1 > num2 is False; And you won't enter the elif block, because num2 > num1 is also False.
That means the input() won't run at all;

Your code's problem is that you do not always call the input:
if num1 > num2:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num1+operation+num2+"=")))
elif num2 > num1:
num1 = str(num1)
num2 = str(num2)
Answer = int(input((num2+operation+num1+"=")))
if num1 == num no input is done and the one from before is used (again).
You can solve it by changing one of them to >= or use an additional else: ....
You can shorten/improve your code a lot if you
do not import random multiple times
use a dictionary to decide which function to call (reduces if .. elif .. else
use input validation to avoid crashing on bad input
use string.format() or even better f-strings instead of python 2.7 % formatting
use with open(...) for file operations
structure the code with some more functions
import random
def RanOperation():
return random.choice(['+','-','x'])
def plus():
# get both numbers with one random call
a,b = random.choices(range(1,11),k=2)
return (a,b,a+b)
def minus():
# only operation where a > b matters to not get negative results
# sorting (low to high) and choosing b,a ensures a is at least b or more
# the other operations are cummutative so its better to leave then unsorted
# to train 8x4 as as well as 4x8
b,a = sorted(random.choices(range(1,11),k=2) ) # a > b
return (a,b,a-b)
def mult():
a,b = random.choices(range(1,11),k=2)
return (a,b,a*b)
def get_answer(a,operation,b):
while True:
try:
k = int(input( "{} {} {} = ".format(a,operation,b)))
return k
except Exception:
print("Input a valid number.")
Usage:
# call which function for what ops?
# using mapper["+"]() --> calls the plus() function - this reduces if/else's
mapper = {"-": minus, "+":plus, "x":mult}
while True:
Name= input("Hello, what is your name?").title()
print("Hello,", Name, "Welcome to ARITHMETIC QUIZ")
score=0
for i in range(10):
print(str(i+1)+".")
operation = RanOperation()
a,b,ans = mapper[operation]()
answer = get_answer(a,operation,b)
if answer == ans:
print("Correct!")
score += 1
else:
print("The correct answer is {:>10d}".format(ans))
print("Sorry this is incorrect!")
length = int(len(Name))
print("You got", score, "correct out of 10,", Name)
with open('Class_Scores.txt','a') as File1:
File1.write("\n -{:20s} {:10d}".format(Name , score))
Ask = input("Do you want to continue? Y/N").upper()
if Ask == "N":
break
Output:
Hello, what is your name?Enya
Hello, Enya Welcome to ARITHMETIC QUIZ
1.
10 - 5 = 5
Correct!
2.
8 - 6 = 9
The correct answer is 2
Sorry this is incorrect!
3.
10 - 2 = 8
Correct!
# ...snipp 4-9...
10.
4 - 4 = 0
Correct!
You got 9 correct out of 10, Enya
Do you want to continue? Y/Nn

Related

how to make a calculator with a loop until I choose to break

I'm trying to build a calculator with a loop until I choose to break it or end it.
Can you please suggest?
Thank you in advance,
Max
new_operation = input("press enter to make a new operation or type the word exit to finish")
num1 = int(input("Enter a number: "))
op = input("Enter the operator: ")
num2 = int(input("Enter a second number: "))
while new_operation != ("no"):
if op == ("+"):
print (num1 + num2)
elif op == ("-"):
print (num1 - num2)
elif op == ("*"):
print (num1 * num2)
elif op == ("/"):\
print (num1 / num2)
else:
print ("Invalid operation")
new_operation = input("make a new operation")
Your code looks good, but need some tweak to make it "do while" loop kind of implementation.
while True:
num1 = int(input("Enter a number: "))
op = input("Enter the operator: ")
num2 = int(input("Enter a second number: "))
if op == ("+"):
print (num1 + num2)
elif op == ("-"):
print (num1 - num2)
elif op == ("*"):
print (num1 * num2)
elif op == ("/"):\
print (num1 / num2)
else:
print ("Invalid operation")
new_operation = input("press enter to make a new operation or type the word exit to finish")
if(new_operation == ("no")):
break
Some suggestions:
Check your indentation, as commented above. Python is sensitive to that.
Make sure your inputs and outputs are more consistent and useful. Your prompt says I should type exit, but your code requires them to type no...
Your looping structure is a bit broken. This is to be expected for somebody new to coding. One of my favorites for this case is:
print('Welcome to the calculator!')
do_run = True
while do_run:
...
do_run = input('Would you like to continue [y/n]: ')[0].lower() == 'y'

I am Facing a problem i Python where a user says "yes" or "no" the loop still executes anyhow. Why is it so?

I am making a python calculator program that asks a user after completing one calculation whether they want to continue or not. If the user says Yes the loop should run or else it should stop. I am Facing a problem where a user says yes or no the loop still executes anyhow. Why is it so ???
print("This is a Calculator In Python. !!!")
print("I Can Do Addition, Subtraction, Multiplication and Division.!!")
def addition():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number. !!"))
result = num1 + num2
return result
def subtraction():
print("Please Don't Enter Float Values Here.")
num1 = int(input("Enter First Number.!!"))
num2 = int(input("Enter Second Number.!!"))
result = num1 - num2
return result
def multiplication():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 * num2
return result
def division():
print("You Can Enter Float Values Here.")
num1 = float(input("Enter First Number.!!"))
num2 = float(input("Enter Second Number.!!"))
result = num1 / num2
return result
print("""1. a for Addition
2. s for subtraction
3. m for multiplication
4. d for Division""")
select = "Yes"
while select:
choice = str(input("You Choose The Operation."))
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select=str(input('Continue Yes or No '))
print("Thank you..!")
You've defined your loop as while select, which means as long as select is considered to not be None, it will continue looping
In your loop, you assign the user input to select, which means as long as the user inputs anything, it will always keep looping.
To fix this, you should have the while loop check if select is "yes":
while select.lower().strip() == "yes":
choice = input("You Choose The Operation. ")
if choice == "a":
print(addition())
elif choice == "s":
print(subtraction())
elif choice == "m":
print(multiplication())
elif choice == "d":
print(division())
else:
print("Invalid Input")
select = input("Continue Yes or No ")
print("Thank you..!")
Also, input() returns a string so you don't need to wrap it in a str() call.

Error in this python code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
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.
Improve this question
while True:
print ("Options")
print ("Write 'Quit' if you want to exit")
print ("Write '+'if you want to make an addition")
print ("Write '-' if you want to make a sottration")
print ("Write '*' if you want to make a moltiplication")
print ("Write '/' if you wantto make a division")
user_input == input(":")
if user_input == ("+")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1+num2)
print("The result is"+ result)
elif user_input == ("-")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1-num2)
print("The result is"+ result)
elif user_input == ("*")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
result = str(num1*num2)
print("The result is"+ result)
elif user_input == ("/")
num1 = float(input("Enter a number...")
num2 = float(input("Enter the second number...")
print ("The result is"+ result)
This is the code I have created in python 2.7, but it does not work. I think there's an indentation error. Can you help me?
Fix your indentation and add a colon after each if-statement as the following and change user_input == input(':') to user_input = input(':'):
while True:
print ("Options")
print ("Write 'Quit' if you want to exit")
print ("Write '+'if you want to make an addition")
print ("Write '-' if you want to make a sottration")
print ("Write '*' if you want to make a moltiplication")
print ("Write '/' if you wantto make a division")
user_input = input(":") # fix this line
if user_input == ("+"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1+num2)
print("The result is"+ result)
elif user_input == ("-"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1-num2)
print("The result is"+ result)
elif user_input == ("*"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1*num2)
print("The result is"+ result)
elif user_input == ("/"):
num1 = float(input("Enter a number..."))
num2 = float(input("Enter the second number..."))
result = str(num1/num2)
print ("The result is"+ result)
EDIT:
Below is a better version of your code that fixes few errors, like reading string input, avoid dividing by zero exception and removing float() type casting because in python 2.7 input() already does that for you.
while True:
print("Options")
print("Write 'Quit' if you want to exit")
print("Write '+'if you want to make an addition")
print("Write '-' if you want to make a sottration")
print("Write '*' if you want to make a moltiplication")
print("Write '/' if you wantto make a division")
user_input = raw_input(":")
if user_input == '+':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1+num2))
elif user_input == '-':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1-num2))
elif user_input == '*':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
print('The result is {}'.format(num1*num2))
elif user_input == '/':
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
if num2 == 0:
print("Can't divide by zero.")
else:
print("The result is {}".format(num1/num2))
Also as suggested by other users here is an improved version:
while True:
print("Options")
print("Write 'Quit' if you want to exit")
print("Write '+'if you want to make an addition")
print("Write '-' if you want to make a sottration")
print("Write '*' if you want to make a moltiplication")
print("Write '/' if you wantto make a division")
user_input = raw_input(":")
num1 = input("Enter a number...")
num2 = input("Enter the second number...")
if user_input == "+":
result = str(num1+num2)
elif user_input == "-":
result = str(num1-num2)
elif user_input == "*":
result = str(num1*num2)
elif user_input == "/":
if num2 == 0:
result = "Can't divide by zero"
else:
result = str(num1/num2)
print("The result is", result)

Repeating code 3 times, and making sure input is only a number in Python 2.7

I am trying to find out how to make my code repeat its self 3 times at the end of the set of questions and also I'm trying to make sure my validation is correct so that the input to the questions is only a number.
This is my code...
import random
correct = 0
name = raw_input("Please enter your name: ")
print 'ok',name, 'I need you to answer these 10 math simple maths questions'
for counter in range(10):
num1 = float(random.randint(1, 10))
num2 = float(random.randint(1, 10))
Math = random.choice(["+", "-", "*","/"])
print("Please solve:", num1, Math, num2)
user = int(input(""))
if Math == "+":
answer = num1 + num2
elif Math == "-":
answer = num1 - num2
elif Math == "*":
answer = num1 * num2
elif Math == "/":
answer = num1 / num2
if answer!= int:
print ("Please reenter a number")
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print(name, " You Got", correct, "Out Of 10")
Your answer != int should be if not isinstance(answer, int)
Furthermore, you will get ValueError each time user tries to insert characters.
Because of this, you should edit your code to look like this:
from __future__ import division
import random
for i in xrange(3):
correct = 0
name = raw_input("Please enter your name: ")
print 'ok',name, 'I need you to answer these 10 math simple maths questions'
for counter in xrange(3):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
Math = random.choice(["+", "-", "*","/"])
print("Please solve: {} {} {}".format(num1, Math, num2))
while True:
try:
user = int(raw_input(""))
except ValueError:
print ("Please reenter a number")
continue
break
if Math == "+":
answer = num1 + num2
elif Math == "-":
answer = num1 - num2
elif Math == "*":
answer = num1 * num2
elif Math == "/":
answer = round(num1 / num2, 1)
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print("{} You Got {} Out Of 10".format(name, correct))
As you can see there was a lot things that you needed to change.

Python - looping

I am trying to build a simple calculator. I just want the user to enter two numbers and an operation, then for the calculation to be shown, then to loop back to entering two numbers again. If the user enters an operation that is not recognized I want to loop back to 'enter operation'.
Why is this not working:
def add (a,b):
return a + b
def minus (a,b):
return a - b
def multi (a,b):
return a * b
def div (a,b):
return a / b
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
def opPic():
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
opPic ()
print ("Hello User")
numPic()
opPic()
You have a few bugs. First, num1 and num2 are local to numPic--not
global. So you need to return them to the caller, and the caller has to pass
them to opPic():
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
return num1, num2
def opPic(num1, num2):
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
opPic (num1, num2)
num1, num2 = numPic()
opPic (num1, num2)
To make it loop-based, you could do something like:
def opPic(num1, num2):
while True:
op = input("Type an operation (add,minus,multi,div):" )
if op == "add":
print (add (num1,num2))
elif (op == "minus"):
print (minus(num1,num2))
elif (op == "multi"):
print (mulit(num1,num2))
elif (op == "div"):
print (div(num1,num2))
else :
print ("operation not recognised")
continue
break
Hopefully, you can figure out the other bit on your own, as this looks like a school assignment.
The num1 and num2 you define in numPic are local to that function. You need to return them and pass them to the opPic function for them to be used.
def numPic():
num1 = int(input("Type a number: "))
num2 = int(input("Type another number: "))
return num1, num2
def opPic(num1, num2):
#the same code as before
#except changing opPic() to opPic(num1, num2)
print ("Hello User")
num1, num2 = numPic()
opPic(num1, num2)
There are better ways of doing what you seem to be aiming for though. You haven't actually used a loop and have used recursion instead.

Categories