Iteration counter Python3x - python

So I've built a simple calculator in Python where the user inputs two numbers and an operator and the answer is given. They also have the option to run the calculator again. I want to number the answers so each answer reads "Answer 1 equals x", "Answer 2 equals x", etc. depending on how many times the calculator is run. Everytime I try to format the counter to count iterations, it won't work and is stuck just labeling them "Answer 1" over and over. Any help would be greatly appreciated. I'm super new to Python.
answer = "y"
while ((answer == "Y") or (answer == "y") or (answer == "Yes") or (answer == "yes")):
numones = input ("Give me a number: ")
numtwos = input ("Give me another number: ")
numone = float(numones)
numtwo = float(numtwos)
operation = input ("Give me an operation (+,-,*,/): ")
counter = 0
for y in answer:
counter += 1
if (operation == "+"):
calc = numone + numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "-"):
calc = numone - numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "*"):
calc = numone * numtwo
print ("Answer " + str(counter) + " is " + str(calc))
elif (operation == "/"):
calc = numone / numtwo
if (numtwo != 0):
print ("Answer " + str(counter) + " is " + str(calc))
else:
print ("You can't divide by zero.")
else:
print ("Operator not recognized.")
answer = input ("Do you want to keep going? ")
if ((answer == "Y") or (answer == "y") or (answer == "Yes") or (answer == "yes")):
print ()
else:
print ("Goodbye.")
break

Remove assigning counter = 0 in your while loop. And move this declaration above your while loop.
also lines:
for y in answer:
counter += 1
are really confusing and sure are wrong, because if you got 'yes' as an answer you would get +3 increase. Just increment(counter += 1) counter without any for-loop.

Related

Python- print() code running when its not supposed to

Disclaimer: I am VERY inexperienced in python(if you couldn't tell by the question)
I made this basic code where you type in a given password. Once you type it in, you can either take a test or change the password. Each choice leads to different dialogue options, and so on(I used a lot of if: else and while: statements).
However, for my code, after getting the test question right, it'll print the "wrong" message WITH the "you got it right" message. Then, when signing in again, you have to type in the password TWICE before it registers your input. Anyone know how to fix this? I'm using Pycharm btw
Code:
k = 1
t = 1
s = 1
passcodes = ["stanley"]
while s == 1:
while k == 1:
ans = input("Enter your password: ")
if ans in passcodes:
while t <= 10:
print("Logging in.. [" + "*" * t + (10 - t) * " " + "]")
t = t + 1
if t > 10:
print("Logged in")
k = 2
else:
print("ACCESS DENIED")
while k == 2:
ans2 = input("Take test(1) or change password(2)? ")
if ans2 == "1":
ans3 = input("What is the square root of 4? ")
if ans3 == "2":
print("Correct. Thanks for participating!")
k = 1
t = 1
if ans3 == "-2":
print("Correct. Thanks for participating!")
k = 1
t = 1
else:
print("Wrong answer. Thanks for participating!")
k = 1
t = 1
if ans2 == "2":
change = input("New password: ")
passcodes.clear()
passcodes.append(change)
print("New password " + change + " saved. Please sign back in.")
k = 1
t = 1
ans = input("Enter your password: ")
else:
print("Signing out..")
Error message:
hi there you have a small mistake in the sequence of the if statement
when the ans3 is 2 the program rechecks if ans3 is -2 and it finds it false so it runs the code in the else statement to fix this you simply need the program to run else just in case that the two if statements are false
this is achieved by using elif statement in the line " if ans3 == "-2":"
it should be "elif ans3 == "-2":"
In this code here you have a small mistake in last if statement. In last if statement you use 'ans' statement its not needed bcz already you use this for printing a new answer so try my code and run it.its give proper output what ever you need.
k = 1
t = 1
s = 1
passcodes = ["stanley"]
while s == 1:
while k == 1:
ans = input("Enter your password: ")
if ans in passcodes:
while t <= 10:
print("Logging in.. [" + "*" * t + (10 - t) * " " + "]")
t = t + 1
if t > 10:
print("Logged in")
k = 2
else:
print("ACCESS DENIED")
while k == 2:
ans2 = input("Take test(1) or change password(2)? ")
if ans2 == "1":
ans3 = input("What is the square root of 4? ")
if ans3 == "2":
print("Correct. Thanks for participating!")
k = 1
t = 1
if ans3 == "-2":
print("Correct. Thanks for participating!")
k = 1
t = 1
else:
print("Wrong answer. Thanks for participating!")
k = 1
t = 1
if ans2 == "2":
change = input("New password: ")
passcodes.clear()
passcodes.append(change)
print(" New password " + change + " saved. Please sign back in.")
k = 1
t = 1
else:
print("Signing out..")

how to convert str to int

I'm making a guessing game and i need to know how to stop it from putting my answers in lexicographical order as that makes a bug in my game.
I've tried instead of having elif Guess < str(value): making it elif Guess < int(value): but i get the error message "'<' not supported between instances of 'str' and 'int'" and i'm having no luck with anything else
Here is the code im working with
from random import *
from random import randint
import os
numbers = []
Guesses = []
dif = []
os.system('CLS')
print("I want you to guess my number")
print("\n \n \n \nIf you give up type 'give up' word for word")
f = open("Data.txt", "a")
print("Say 'yes' If You're Ready")
YN = input()
if YN == "yes":
os.system('cls')
print("Select a difficulty")
print('impossible 1 - 10000')
print('annoying 1 - 1000')
print('hard 1 - 500')
print('medium 1 - 200')
print('easy 1 - 99')
print('beginner 1 - 10')
diff = input()
if diff == 'easy':
os.system('CLS')
value = randint(1, 99)
numbers.append(value)
dif.append(diff)
elif diff == 'beginner':
os.system('CLS')
value = randint(1, 10)
numbers.append(value)
dif.append(diff)
elif diff == 'medium':
os.system('CLS')
value = randint(1, 199)
numbers.append(value)
dif.append(diff)
elif diff == 'hard':
os.system('CLS')
value = randint(1, 499)
numbers.append(value)
dif.append(diff)
elif diff == 'annoying':
os.system('CLS')
value = randint(1, 1000)
numbers.append(value)
dif.append(diff)
elif diff == 'impossible':
os.system('CLS')
value = randint(1, 10000)
numbers.append(value)
dif.append(diff)
os.system('cls')
while True:
Guess = input()
if Guess == "give up":
print("The Number Was " + str(numbers))
f.write("------------------------------------------------------------- \n \r")
f.write("Guesses " + str(Guesses) + "\n \r")
f.write("Difficulty: " + str(dif) + "\n \r")
f.write("[USER GAVE UP] \n \r")
f.write("Correct Answer: " + str(numbers) + "\n \r")
f.write("------------------------------------------------------------- \n \r")
break
elif Guess < str(value):
print("Higher")
Guesses.append(Guess + " - Higher")
elif Guess > str(value):
print("Lower")
Guesses.append(Guess + " - Lower")
elif Guess == str(value):
os.system('CLS')
length = len(Guesses)
f.write("------------------------------------------------------------- \n \r")
f.write("Guesses " + str(Guesses) + "\n \r")
f.write("Difficulty: " + str(dif) + "\n \r")
f.write("Number Of Guesses [" + str(length) + "]\n \r")
f.write("Correct Answer: " + str(numbers) + "\n \r")
f.write("------------------------------------------------------------- \n \r")
print("That Was Correct!")
for x in Guesses:
print(x)
break
input()
You may try to convert Guess from str to int, and compare in integer.
elif int(Guess) < value:
As maruchen notes you should be casting the Guess variable and not the value variable.
However, that alone is still going to leave you with problems. The user isn't forced to enter an integer and indeed string answers such as "give up" are expected. If you try an cast a string to an integer and the string contains non-numerics, then you will be faced with a ValueError. So best is to define a function like this:
def guess_less_than_value(guess, value):
try:
return int(guess) < int(value)
except ValueError:
return False
Then you can but in the body of your code:
if guess_less_than_value(Guess, value):
....
And likewise with greater than.

How do I return to the previous while loop?

x, y = raw_input("Enter 2 numbers separated by a space.").split()
answer = 0
#Enter the 2 numbers to be calculated.
print "You have selected, A = "+ x + " and B = " + y + "."
while int(y):
if (not int(y) % 2 == 0):
# this checks if y is even or odd
answer = int(answer) + int(x)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is odd so we'll add A to the total."
print "The running total is " + str(answer) + "."
else: (int(y) % 2 == 0)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is even, so we'll ignore that number."
x = int(x) * 2
y = int(y) / 2
print "The product is " + str(answer) + "."
while True:
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
I'm trying to get my program to go back to the top while loop if "Y" or "y" is entered for 'Would you like to make another calculation?'. So far what I have returns me to the bottom while loop. Any help? Thanks!
It looks like your second loop should actually be an outer loop (in this case often called a "game loop"). The entire application loops until the user specifies to end the application. Something like this:
a = "Y"
while (a == "Y"):
##########
# All of your "first loop" logic goes here.
# This is the primary "step" of any given instance of the "game".
##########
# Then, prompt the user to continue or not...
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
(Note: This is freehand code and I'm not entirely familiar with Python, so there may need to be some tweaking on the specifics. This is meant to demonstrate the structure, not to be copied/pasted as production code.)
Try nesting the first while loop inside of the second. It'll run your calculation code first, check to see if you'd like to do another, and then return to the top of the while True: loop to do another calculation.
Like this:
while True:
x, y = raw_input("Enter 2 numbers separated by a space.").split()
answer = 0
#Enter the 2 numbers to be calculated.
print "You have selected, A = "+ x + " and B = " + y + "."
while int(y):
if (not int(y) % 2 == 0):
# this checks if y is even or odd
answer = int(answer) + int(x)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is odd so we'll add A to the total."
print "The running total is " + str(answer) + "."
else: (int(y) % 2 == 0)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is even, so we'll ignore that number."
x = int(x) * 2
y = int(y) / 2
print "The product is " + str(answer) + "."
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
Hope that helps
Depending on what you're trying to do, and where this particular code appears in your program, it's usually advised to wrap your code inside of functions. That way, it doesn't automatically run when you import your module. You have to call a function to make the code run.
If you want to make this an executable script, you'd want to wrap the main loop code in a if __name__ == '__main__: block so that it only executes if it's being executed directly.
e.g.:
def perform_calculation():
while True:
x, y = raw_input("Enter 2 numbers separated by a space.").split()
answer = 0
#Enter the 2 numbers to be calculated.
print "You have selected, A = "+ x + " and B = " + y + "."
while int(y):
if (not int(y) % 2 == 0):
# this checks if y is even or odd
answer = int(answer) + int(x)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is odd so we'll add A to the total."
print "The running total is " + str(answer) + "."
else: (int(y) % 2 == 0)
print "A = " + str(x) + " and B = " + str(y) + "."
print "B is even, so we'll ignore that number."
x = int(x) * 2
y = int(y) / 2
print "The product is " + str(answer) + "."
def run_loop():
while True:
perform_calculation()
a = raw_input("Would you like to make another calculation? Y or N")
if str(a) == "Y" or str(a) == "y":
continue
if str(a) == "N" or str(a) == "n":
print "Thank you have a nice day!"
break
else:
print "Invalid entry. Ending program."
break
if __name__ == '__main__':
run_loop()

my code won't save inputs to a file

my code wont save the file
#ask for name
name=input("what is your name?")
print("start your quiz " + name + "!")
user=input
class123=('1','2','3')
class123=input("what class are you in 1,2 or 3")
#get random number
import random
#ask number of questions you want
score=0
count=10
#start while loop
while count != 0:
num1=random.randint(1,8)
num2=random.randint(1,8)
symbol=random.choice(['*','+','-'])
if symbol=="*":
user=int(input(str(num1) + "*" + str(num2)))
count=count-1
answer=num1 * num2
if user==answer:
print("well done your score goes up by 1")
score=score+1
else:
print("this is wrong next question")
elif symbol=="+":
user=int(input(str(num1) + "+" + str(num2)))`enter code here`
count=count-1
answer=num1 + num2
if user==answer:
print("well done your score goes up by 1")
score=score+1
else:
print("this is wrong next question")
elif symbol=="-":
user=int(input(str(num1) + "-" + str(num2)))
count=count-1
answer=num1 - num2
if user==answer:
print("well done your score goes up by 1")
score=score+1
else:
print("this is wrong next question")
#get final score
print(" your score was " + str(score) + " well done ")
#save data into 3 classes
while score == 10 and score >= 0:
if class123 == '1':
inFile = open("Class1.txt", 'a')
inFile.write("\n" + name + ":" + str(score))
inFile.close()
score = -1
elif class123 == '2':
inFile = open("Class2.txt", 'a')
inFile.write("\n" + name + ":" + str(score))
inFile.close()
score = -1
elif class123 == '3':
inFile = open("Class3.txt", 'a')
inFile.write("\n" + name + ":" + str(score))
inFile.close()
score = -1
If you want your code to work, first off remove or comment out the 'enter code here' part on line 26. It can be done with '#'. The reason is '' is a string and will be interpreted as a string in a place where it shouldn't be.
user=int(input(str(num1) + "+" + str(num2))) #enter code here
2nd, it's not saved because while never runs, as while score == 10 is not true, so the loop where you write the score never runs.
You can just change it to something like:
while score <= 10 and score >= 0:
I tested the 2 adjustments I made and, well, your code would run and create the Class?.txt file
Yet as others mention, it's not quite the right structure. Not quite the right usage of stuff. So you may want to improve your code, but here I just gave you a few fixes how to actually get it to run, if you don't mind.

python - ask random mathematical questions not quite working

I need help with this program that I'm writing. It asks random mathematical questions. It chooses between +, - and x. Here's my code
import random
def questions():
name=input("What is your name: ")
print("Hello there",name,"!")
choice = random.choice("+-x")
finish = False
questionnumber = 0
correctquestions = 0
while finish == False:
if questionnumber < 10 | questionnumber >= 0:
number1 = random.randrange(1,10)
number2 = random.randrange(1,10)
print((number1),(choice),(number2))
answer=int(input("What is the answer?"))
questionnumber = questionnumber + 1
if choice==("+"):
realanswer = number1+number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
if choice==("x"):
realanswer = number1*number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
elif choice==("-"):
realanswer = number1-number2
if answer==realanswer:
print("That's the correct answer")
correctquestions = correctquestions + 1
else:
print("Wrong answer, the answer was",realanswer,"!")
else:
finish = True
else:
print("Good job",name,"! You have finished the quiz")
print("You scored " + str(correctquestions) + "/10 questions.")
questions()
The output:
What is your name: s
Hello there s !
6 - 9
What is the answer?-3
That's the correct answer
9 - 8
What is the answer?1
That's the correct answer
9 - 7
What is the answer?2
That's the correct answer
8 - 3
What is the answer?4
Wrong answer, the answer was 5 !
5 - 6
What is the answer?1
Wrong answer, the answer was -1 !
8 - 7
What is the answer?1
That's the correct answer
3 - 5
What is the answer?2
Wrong answer, the answer was -2 !
4 - 5
What is the answer?1
Wrong answer, the answer was -1 !
7 - 2
What is the answer?5
That's the correct answer
7 - 1
What is the answer?6
That's the correct answer
Good job s ! You have finished the quiz
You scored 6/10 questions.
Now the program is running fine but it asks the questions with the same operator (+, -, x) every time I start the program a different operator questions happen but I want to run it so it actually asks different adding, subtracting, multiplication questions inside the program so all the questions that it asks it will be different questions like x, + and - every different question.
It should help if you move the choice part inside the loop:
while not finish: # better than finish == False
choice = random.choice("+-x")
# etc
import random
correct = 0
name = input("Please enter your name: ")
for count in range(10):
num1 = ranom.randint(1, 100)
num2 = radom.randint(1, 100)
symbol = rndom.choice(["+", "-", "*"])
print("Please solve:\n", num1, symbol, num2)
user = int(input(""))
if symbol == "+":
answer = num1 + num2
elif symbol == "-":
answer = num1 - num2
elif symbol == "*":
answer = num1 * num2
if user == answer:
print("Wong u wetard")
correct = correct + 1
else:
print("correct")
print(name, ", You Got", correct, "Out Of 10")
After while finish == false put this !
choice = random.choice("+-x")
I have attempted the same problem that you face, and after looking at your code I made the changes detailed below. the code works and it is (relatively) neat and concise.
def name_enter():
global name
name = ""
while name == "" or len(name) > 25 or not re.match(r'^[A-Za-z0-9-]*$', name):
name = input("Please enter your name: ")
enter_class()
def enter_class():
global class_choice
class_choice = None
while class_choice not in ["1","3","2"]:
class_choice = input("Please enter you class (1, 2, 3): ")
print("\nClass entered was " + class_choice)
mathsquestion()
def mathsquestion():
global qa, score
qa, score = 0, 0
for qa in range(0,10):
qa = qa + 1
print("The question you are currently on is: ", qa)
n1, n2, userans = random.randrange(12), random.randrange(12), ""
opu = random.choice(["-","+","x"])
if opu == "+":
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " + %d" % (n2) + " = ")
prod = n1 + n2
elif opu == "-":
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " - %d" % (n2) + " = ")
prod = n1 - n2
else:
while userans == "" or not re.match(r'^[0-9,-]*$', userans):
userans = input("Please solve this: %d" % (n1) + " x %d" % (n2) + " = ")
prod = n1 * n2
userans = int(userans)
prod = int(prod)
if prod == userans:
score = score + 1
print("Well done, you have got the question correct. Your score is now: %d" % (score))
else:
print("Unfortunatly that is incorrect. The answer you entered was %d" % (userans) + " and the answer is actually %d" % (prod))
print("Your final score is: %d" % (score))
name_enter()
This is a very different code but should do the same thing. It's also much shorter and neater.
import random
correct = 0
name = input("Please enter your name: ")
for count in range(10):
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
symbol = random.choice(["+", "-", "*"])
print("Please solve:\n", num1, symbol, num2)
user = int(input(""))
if symbol == "+":
answer = num1 + num2
elif symbol == "-":
answer = num1 - num2
elif symbol == "*":
answer = num1 * num2
if user == answer:
print("Correct!")
correct = correct + 1
else:
print("Incorrect")
print(name, ", You Got", correct, "Out Of 10")

Categories

Resources