Errors pertaining to the "!==" function in Python - python

I'm currently trying to make a program in Python that basically asks you math problems. For some reason, there's a lot of errors, and I have no idea why, such as the "!==" function, which seems to be incorrect. There might also be some other issues as I've only just started Python. Could someone direct me to how to use the !== function correctly and also my other issue: Making my input for "addition, subtraction, or multiplication" into a possible command?
# import random
import time
choice = 0
counterright = 0
counterwrong = 0
def add_question_to_file(a, b):
with open("wrong_answers.txt", 'a') as f:
f.write(f"{a} {operation} {b}\n")
def test(a,operation,b):
user_input = int(input(f"{a} {operation} {b} = "))
if user_input == a + b:
print("You got it right!")
counterright += 1
while user_input != a + b:
if user_input == a + b:
print("You got it right!")
counterwrong += 1
break
else:
add_question_to_file(a, b)
print("Try Again!")
user_input = int(input(f"{a} + {b} = "))
def get_question():
a = random.randint(1, 10)
b = random.randint(1, 10)
with open("calc_log.txt", 'a') as f:
if a<b: #insures a is always greater than b
a, b = b, a
f.write(f"{a} {operation} {b}\n")
def check_operation():
if operation !==t "+" or "-" or "*"
print("Sorry, that's invalid. You have to choose of the three operations!")
t1=time.perf_counter() #
m = input("What mode would you like to use? Review/Normal. Choose Normal if this is your first time!")
operat ion = input("Which operation would you like to use? +,-,or *?")
if m == "review":
with open("wrong_answers.txt", 'r') as f:
for line in f:
a, operation, b = line.split()
test(int(a), int(b))
elif m == "normal":
num_questions = int(input("How many questions would you like to do? "))
for i in range(num_questions):
print(f"You are on question {i + 1}: ")
get_question()
t2=time.perf_counter() #
print("It took you", t2-t1, "seconds for you to solve this problemset") #
print ("You got",counterright,"correct and",counterwrong,"wrong.")

The reason !== isn't working is because this is not an operator in python. Try using !=. It means not equal too.

The does not equal function in python is !=. The double equal sign (==) is only used when you want to check for equality. I hope this helps!

Related

Python while loop ask more than once for input

I've been trying to solve the issue with guessing the number program,
The first number the program has to print Ans which is (Startlow + Starthigh)/2 and then Ans gets updated depends on the input
I can't figure out why my while loop keeps waiting for the input for at least 2 times until it prints the results even if I press l or h (unless I press c) which breaks the loop
Startlow = 0
Starthigh = 100
Ans = (Startlow + Starthigh)/2
print("Please think of a number between 0 and 100!")
while True:
print("Is your secret number " + str(int(Ans)))
if input() == "c":
print("Game over,Your secret number was: "+str(int(Ans)))
break
elif input() == "l":
Startlow = Ans
Ans = (Startlow + Starthigh)/2
elif input() == "h":
Starthigh = Ans
Ans = (Startlow + Starthigh)/2
else:
print("Sorry, I did not understand your input.")
any help appreciated :)
You should be asking for input once in the loop, and then comparing that answer to the items you want.
You are instead requesting a (potentially different) answer at each of your conditionals.
The number of questions asked depends on how many conditionals you fall through.
Just do:
x = input()
if x == "c":
#And so on...

How to restart for while loops after user input

I've just started coding and I'm slowly understanding it. For my class we have to make a children's program to practice their math and ask them if they would like to try again if it is correct. I cannot understand how to get my while True loop to restart if they input Y. Any tips? Here is my code:
#Addition
A = int(input("What is %i + %i =" %(N1, N2)))
while add != N1 + N2:
add = int(input("Incorrect, what is %i + %i = " %(N1,N2)))
while add == N1 + N2:
repeat =(input("Correct! would you like to try again? Y/N "))
if repeat == 'n':
break
if repeat == 'y':
continue
if op == "-":
#Subrtraction
s = int(input("What is %i - %i =" %(N1, N2)))
while s != N1 - N2:
s = int(input("Incorrect, what is %i - %i = " %(N1,N2)))
while s == N1 - N2:
repeat =(input("Correct! would you like to try again? Y/N "))
if op == "*":
#Multiply
m = int(input("What is %i - %i =" %(N1, N2)))
while m != N1 * N2:
m = int(input("Incorrect, what is %i - %i = " %(N1,N2)))
while m == N1 * N2:
repeat =(input("Correct! would you like to try again? Y/N "))
This program structure does not make sense.
You can do:
while True:
num1 = int(input("num1 "))
num2 = int(input("num2 "))
op = '+'
calc = -1
if op == "+":
while calc != num1 + num2:
calc = int( input(f"Whats {num1} {op} {num2}?"))
elif op == "-":
pass # code the others
elif op == "*":
pass # code the others
elif op == "/":
pass # code the others - use float where needed instead of int
# comparing floats is difficult due to float math rounding imperfection
print("Correct!" , num1, op, num2,"=",calc)
again = input("Again? Y to do it again: ").lower()
if again != "y":
break # leaves the while True
for doing it you can define a function. Maybe it's little more complicated than what you do in class, but still it's pretty basic, so you can learn it easly :)
when using a function, remember to call it in the first time so it'll work.
here's an example:
def function_name():
while True:
'''your code'''
repeat =(input("Correct! would you like to try again? Y/N "))
if repeat == "y":
function_name() # wach time the user say "y" the code calls the function again.
break # the break will finish the while loop and will close the program.
function_name() # that's where I call the function the first time.
by the way, you don't actually have to use the while loop if you are using the function. but I assume it was your work in class so I'll leave it that way :)
I think it is better to enter a while loop first and then take input from the user or determining whether the answer is correct or not and other questions...
# coding: utf-8
# Start of the 1st Question
redo="y"
A1=-1 # can be any integer but not the correct answer
n1, n2 = 2, 3
while (A1 != n1 + n2) or redo.lower()=="y":
# ask the question
A1 = int(input("What is the sum of %i and %i : " % (n1, n2)))
# if answer is correct
if A1 == n1 + n2:
redo = input("Correct ! Would you like to try again? (Y/[N]) : ")
if redo.lower() == "y":
continue
else:
break
else:
print("Your Answer : %d is Incorrect!" % A1)

Making a mathematics quiz in python

import random
def mathquiz():
name = str(input("Whats your name?:"))
a = random.randint(1,10)
b = random.randint(1,10)
c = (a * b)
timesby = ("*")
print('what is', + a, timesby, + b)
ans = input("Enter your answer here")
if ans == c:
print("Thats correct")
else:
print ("Incorrect the answer is", + c)
I am trying to create a maths quiz using random numbers and just say the question is 10 * 10 if i enter 100 if will say i have the wrong answer. Everything else works fine just this bit is wrong.
ans and c are of different types. Since you read ans from the console, it is a string, and not a number, while c is calculated through multiplying 2 numbers, so it is a number. there are 2 ways to fix this, convert ans to an int with int(ans) instead of ans, or convert c to a string with str(c) instead of c.

User interaction via while-loops / jumping out of 2 while loops

Hello fellow programmers,
I'm quite a Python and overall programming newbie and I don't know how to process user input the bestimmt. A friend of mine suggested while loops and they worked quite well but now I have a serious problem.
The program is about asking the user which one of 3 ways to calculate Pi he wants. After his/her selection, e.g. the way to calculate Pi using a polygon which doubles the number of corners after each iteration, it asks how many digit the user wants to see or how many loops should be calculated etc. I also have added some code that checks what the user has written, e.g. if the user is asked to either type y or n but types b the program reminds him of that and asks again.
This style has led to whiles, inside whiles, inside whiles and now looks more like HTML code than Python and is a little complicated to understand...
Take a look:
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
prgrm_ctrl_main_while_start = 0
while prgrm_ctrl_main_while_start == 0:
print "Please select the type of algorithm you want to calculate Pi."
usr_ctrl_slct_algrthm = raw_input("'p' to use polygons, 'm' to use the Monte-Carlo algorithm or 'c' for the Chudnovsky algorithm: ")
print " "
if usr_ctrl_slct_algrthm == 'p':
#import libraries
import time
from mpmath import *
#starting values
n_corners = mpf(8)
counter = 0
while_loop_check_itertions = 0
while while_loop_check_itertions == 0:
print "Pi will be calculated more precisely the more iterations you select but it'll also take longer!"
loops = int(input("Please select number of iterations (1 - 10.000.000): "))
print " "
if 1 <= loops <= 10000000:
loops = loops - 1
decimals = int(input("Please select the amount of decimals you want to see: "))
print " "
decimals = decimals + 1
starttime = time.clock()
mp.dps = decimals
while counter <= loops:
counter = counter + 1
n_corners = mpf(n_corners) * mpf(2)
circle = mpf(360)
alpha = mpf(circle) / mpf(n_corners)
beta = mpf(alpha) / mpf(2)
radiansBeta = mpf(mp.radians(beta))
opp_leg = mpf(mp.sin(radiansBeta))
edge_lngth = mpf(opp_leg) * mpf(2)
circmfrnce = mpf(n_corners) * mpf(edge_lngth)
pi = mpf(circmfrnce) / mpf(2)
print "Pi: ", mpf(pi)
print "Time to calculate: ", time.clock() - starttime, "seconds"
print " "
prgrm_ctrl_p_algrthm_while_start = 0
while prgrm_ctrl_p_algrthm_while_start == 0:
usr_ctrl_slct_p_algrthm = raw_input("Would you like to try this algorithm again? (y/n): ")
print " "
if usr_ctrl_slct_p_algrthm == 'y':
usr_ctrl_slct_p_algrthm_slction = 0
break
elif usr_ctrl_slct_p_algrthm == 'n':
usr_ctrl_slct_p_algrthm_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_p_algrthm_slction == 0:
continue
else:
usr_ctrl_slct_diffrt_algrthm_while_start = 0
while usr_ctrl_slct_diffrt_algrthm_while_start == 0:
usr_ctrl_slct_diffrt_algrthm = raw_input("Do you want to use another algorithm? (y/n): ")
print " "
if usr_ctrl_slct_diffrt_algrthm == 'y':
usr_ctrl_slct_diffrt_algrthm_slction = 0
break
elif usr_ctrl_slct_diffrt_algrthm == 'n':
print "See you next time!"
print " "
usr_ctrl_slct_diffrt_algrthm_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_diffrt_algrthm_slction == 0: #The program gets to this line and in case of the user selecting 'y' should continue in the first while-loop
continue
else: #if the user says 'n' the program should interrupt and stop, in the best case it should close the command line (in my case IDLE)
break #instead of doing all this the code gets executed again in the 2nd while loop not the 1st
"""NOTE: I also know the lines above continue or quit the 2nd while-loop"""
elif loops < 1:
print "Please select at least one iteration!"
while_loop_check_algrthm_slct = 0
while while_loop_check_algrthm_slct == 0:
usr_ctrl_slct_algrthm_p_try_agn = raw_input("Do you want to try it again? (y/n): ")
print " "
if usr_ctrl_slct_algrthm_p_try_agn == 'y':
usr_ctrl_slct_algrthm_p_try_agn_slction = 0
break
elif usr_ctrl_slct_algrthm_p_try_agn == 'n':
usr_ctrl_slct_algrthm_p_try_agn_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_algrthm_p_try_agn_slction == 1:
break
else:
continue
else:
print "The maximum amount of iterations is 10 million!"
while_loop_check_algrthm_slct = 0
while while_loop_check_algrthm_slct == 0:
usr_ctrl_slct_algrthm_p_try_agn = raw_input("Do you want to try it again? (y/n): ")
print " "
if usr_ctrl_slct_algrthm_p_try_agn == 'y':
usr_ctrl_slct_algrthm_p_try_agn_slction = 0
break
elif usr_ctrl_slct_algrthm_p_try_agn == 'n':
usr_ctrl_slct_algrthm_p_try_agn_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_algrthm_p_try_agn_slction == 1:
break
else:
continue
I have commented the lines that are effected...
I can't solve the problem with the main-while-loop therefore I'm asking you how I can solve this. Is there a better way of handling user input and checking if it's correct? I'm stuck at a point where I wish I had goto because I can't imagine any other solution.
Hopefully you can help me and thank you for reading this long code! I appreciate that! :)
holofox
My first thought is simplify things, please see this "pseudo-code":
while True: #select algorithm type
#code: ask for algorithm
if answer not in "pmc":
#some message
continue #non-valid algorithm selected, ask again
#...
if answer == 'p':
while True: #select iteration range
#code: ask for iteration
if answer_not_in_range:
#some message
continue #non-valid iteration value, ask again
#...
#perform calculation upon valid selections
#...
#calculation ends
#code: ask for try again with other iteration (algorithm stays same)
if answer != "yes":
break #break out of "iteration" loop
#else loop continues asking for new iteration
#code: ask for try again with other algorithm
if answer != "yes":
break #"algorithm" loop ends, program ends
As Robert Rossney says in an answer to another question:
My first instinct would be to refactor the nested loop into a function and use return to break out.

Python "if" statement not working

I was writing a complex program and I was getting an if statement...
(this isn't the complex code, this is just an example)
print("The 24 game will give you four digits between one and nine")
print("It will then prompt you to enter an ewuation one digit at a time.")
import random
a = random.randint(1,9)
b = random.randint(1,9)
c = random.randint(1,9)
d = random.randint(1,9)
print(a,b,c,d)
f=input("Enter one of the above numbers")
if f==a:
print("ok")
elif f != a:
print("No")
No matter what I type it always outputs "NO".
It would work after converting the user input string to a number:
if int(f) == a:
print("ok")

Categories