When comparing 2 variables output always the same - python-3.x

this is my code for a quiz with ten question.the problem is that whenever I write the answer (the answer gets printed before asking the question) it always say incorrect. please take into consideration that I am very bad at the language and don't correct what doesn't need to be fixed. Thankyou.
from random import randint
name = input("what is your name?")
score = 0
qn = 0
def q():
global qn
global name
global score
qn += 1
if qn < 11:
num1 = randint(1,12)
s = randint(1,3)
num2 = randint(1,12)
if s == 1:
symbal = '+'
answer = num1 + num2
elif s == 2:
symbal = '-'
answer = num1 - num2
elif s == 3:
symbal = '*'
answer = num1 * num2
print(answer)
print(num1 ,symbal ,num2)
sanswer = input("= ?")
if answer == sanswer:
score += 1
print("correct!!!")
else:
print("incorrect")
q()
else:
global name
print("""welldone""")
print(name)
q()

from random import randint
name = input("what is your name?")
score = 0
qn = 0
def q():
global qn
global name
global score
qn += 1
if qn < 11:
num1 = randint(1,12)
s = randint(1,3)
num2 = randint(1,12)
if s == 1:
symbal = '+'
answer = num1 + num2
elif s == 2:
symbal = '-'
answer = num1 - num2
elif s == 3:
symbal = '*'
answer = num1 * num2
print(num1 ,symbal ,num2)
sanswer = int(input("= ?"))
print(answer)
if answer == sanswer:
score += 1
print("correct!!!")
else:
print("incorrect")
q()
else:
global name
print("""welldone""")
print(name)
q()
2 mistake you have:
first: you shouldn't put print(answer) before input
second: you should sanswer = int(input("= ?")) use int() because what you take with input is string
and a simple suggestion try not to use global when coding.

Related

ask the user whether they want to start the quiz again or quit the quiz after answering 5 questions

All the code is fine except the restart part.the purpose of this part is to ask the user whether they want to do the quiz again or quit the quiz after they answer 5 questions ,however i just cant do it.
import random
**restart == "yes"
while restart == "yes":**------this is the main part of the problem.whenever i run the program it says that restart is not defined and i just get even more confused.please,please help.
print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")
print("5.exit")
score = 0
choice1=int(input("please select an option by entering the number\n"))
if choice1 == 1:
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"+",num2)
answer = num1 + num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"+",num2)
answer = num1 + num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score =score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"+",num2)
answer = num1 + num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score +1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"+",num2)
answer = num1 + num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
if q1 != answer:
score = score + 1
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"+",num2)
answer = num1 + num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
print(score)
if q1 != answer:
print("incorrect")
print("your score out of 5 is")
print(score)
if choice1 == 2:
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"-",num2)
answer = num1 - num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"-",num2)
answer = num1 - num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score =score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"-",num2)
answer = num1 - num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"-",num2)
answer = num1 - num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"-",num2)
answer = num1 - num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
print(score)
if q1 != answer:
print("incorrect")
print("your score out of 5 is"/n)
print(score)
if choice1 == 3:
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"*",num2)
answer = num1 + num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"*",num2)
answer = num1 + num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score =score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"*",num2)
answer = num1 + num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score +1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"*",num2)
answer = num1 + num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
if q1 != answer:
score = score + 1
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"*",num2)
answer = num1 + num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
print(score)
if q1 != answer:
print("incorrect")
print("your score out of 5 is",score)
if choice1 == 4:
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"/",num2)
answer = num1 - num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"/",num2)
answer = num1 - num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score =score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"/",num2)
answer = num1 - num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"/",num2)
answer = num1 - num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
if q1 != answer:
print("incorrect")
num1 = random.randint(1,5)
num2 = random.randint(1,5)
print ("what is",num1,"/",num2)
answer = num1 - num2
q1 = int(input(""))
if q1 == answer:
print ("good")
score = score + 1
print(score)
if q1 != answer:
print("incorrect")
print("your score out of 5 is"/n)
print(score)
if choice1 == 5:
print("bye,bye")
exit()
restart=input("Do you want to start the quiz again?Yes?No?")
if restart == "no":
quit-----this is one part of the problem as well as the one below.
look at the definition of restart:
restart == "yes" # incorrect!
this is correct:
restart = "yes" #correct
#rest of the code
and you should use \n instead of /n for new lines

Writing to file using data from variables

import random # imports the random module
user_class = "" # Global variable
question_counter = int(0) # sets counter
amount_correct = int(0) # sets score
possible_operators = ("+","-","x") # creates a list of operators
while user_class == "": # Indefinite iteration - Runs until a valid class is given
user_class = str(input("Please enter your class"))
if user_class == "Rainbow": # Testing variable class - Will not crash the program
class_file = open("RainbowClass.txt","a")
elif user_class == "Sun":
class_file = open("SunClass.text","a")
elif user_class == "Moon":
class_file = open("MoonClass.text","a")
else:
print("Not quite. Try again:")
user_class = ""
name = str(input("Please enter your name"))
while question_counter < 10: # Indeffinate iteration – number of questions
num1 = random.randint(1,10) # random number generation
num2 = random.randint(1,10)
operator = random.choice(possible_operators) # Chooses one of the operators from the list
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "x":
answer = num1 * num2
print("What is the answer to ", num1," "+operator+"" ,num2,"?")
user_answer = int(input())
if user_answer == answer:
question_counter = question_counter + 1
amount_correct = amount_correct + 1
print("Correct!")
else:
print("Incorrect")
question_counter = question_counter + 1
final_score = amount_correct
print("Well Done! You scored",amount_correct,"out of",question_counter,".")
amount_correct = str(amount_correct)
class_file.write(user_class)
class_file.write(name)
class_file.write(amount_correct + "\n")
class_file.close
This is my code. It does not get any errors when I run it but I am trying to get the user's class and open a text file according to the input. The file is opening but when it comes to the bottom it is not writing the data from the quiz that is inside the variables that I want it to.
What is the solution to this?
Untested crack at this (sorry, Python is on another system). Ill break it up into chunks:
import random
# Got rid of your global 'user_class'
# Moved the counter(s) to local function variables
# Moved the operator options to local function variables
Now to tackle your first while, I would do:
def get_class_file():
while True:
# Don't need to call str(); input() returns a 'str'
user_class = input("Please enter your class: ")
if user_class == "Rainbow":
class_file = "RainbowClass.txt"
break
elif user_class == "Sun":
class_file = "SunClass.txt"
break
elif user_class == "Moon":
class_file = "MoonClass.txt"
break
else:
print("Not quite. Try again...")
return class_file
Keep this:
# Don't need to call str(); input() returns a 'str'
name = input("Please enter your name: ")
Now for the second while, a similar function:
def get_score():
# Don't need to call int()
question_counter = 0
amount_correct = 0
# Make this a tuple sequence; they are immutable
possible_operators = ("+","-","x",)
while True:
if question_counter < 10:
num1 = random.randint(1,10) # random number generation
num2 = random.randint(1,10)
operator = random.choice(possible_operators)
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "x":
answer = num1 * num2
user_answer = int(input("What is the answer to: "
+ str(num1) + operator + str(num2) + "?\n"))
# Take out of the if/else since we always increment
question_counter += 1
if user_answer == answer:
amount_correct += 1
print("Correct!")
else:
print("Incorrect!")
else:
break
return amount_correct
Lets put it all together, and see how we get the variables and then how to write them to your files:
import random
def get_class_file():
while True:
# Don't need to call str(); input() returns a 'str'
user_class = input("Please enter your class: ")
if user_class == "Rainbow":
class_file = "RainbowClass.txt"
break
elif user_class == "Sun":
class_file = "SunClass.txt"
break
elif user_class == "Moon":
class_file = "MoonClass.txt"
break
else:
print("Not quite. Try again...")
return class_file, user_class
def get_score():
# Don't need to call int()
question_counter = 0
amount_correct = 0
# Make this a tuple sequence; they are immutable
possible_operators = ("+","-","x",)
while True:
if question_counter < 10:
num1 = random.randint(1,10) # random number generation
num2 = random.randint(1,10)
operator = random.choice(possible_operators)
if operator == "+":
answer = num1 + num2
elif operator == "-":
answer = num1 - num2
elif operator == "x":
answer = num1 * num2
user_answer = int(input("What is the answer to: "
+ str(num1) + operator + str(num2) + "?\n"))
# Take out of the if/else since we always increment
question_counter += 1
if user_answer == answer:
amount_correct += 1
print("Correct!")
else:
print("Incorrect!")
else:
break
return amount_correct, question_counter
class_file, user_class = get_class_file()
name = input("Please enter your name: ")
final_score, num_asked = get_score()
print("Well Done!\n"
"You scored " + str(final_score) + " out of " + str(num_asked) + ".")
# In all methods you called 'a' mode so set that here
# Using 'with open()' automatically closes the file after completion
with open(class_file, 'a') as f:
f.write(user_class + "\n")
f.write(name + "\n")
f.write(str(final_score) + "\n")
Let me know if anything comes up, errors and such. Again, wasn't able to test.

Novice Coder with issue properly looping

So I'm a novice coder having never coded before and am teaching myself Python on the guidance of my CS instructor. I'm walking myself through "Automating the Boring Stuff with Python" and I'm having issues with the Collatz sequence portion at the end of Chapter 3. I've got the sequence down but I'm having issues properly looping the code in order to get the result I want which is looping the sequence until the answer is == to integer 1. This is what I have and I would love some feedback and assistance.
def collatz(number): #defines the collatz sequence
if number%2 == 0:
num1 = number//2
else:
num1 = 3 * (number + 1)
return num1
print("Let's try the collatz sequence. Enter a number")
num = int(input())
num3 = collatz(num)
while num3 != 1: #loops collatz sequence until it equals 1
num2 = collatz(num3)
if num2 == 1:
break
else:
num3 = collatz(num2)
print("ta da!")
You need this code:
def collatz(number):
if number % 2 == 0:
num1 = number//2
else: num1 = 3 * number + 1 # Do not use brackets!!! Or you will have infinite loop
return num1
print("Let's try the collatz sequence. Enter a number")
num = int(input())
while num != 1:
num = collatz(num)
print(num)
if num == 1: break
print("ta da!"); input()

My program is not recognizing its using a negative number

I just started programming for school and this assignment requires me to enter a number and then use it to count from 0 up to the number, then choose a math operation, and then use that math operation.
The problem occurs when I enter a negative number, it gives me the correct message "Too small - Try again: " . but once I enter a positive number it still assigns my original negative number to the program.
Here is my noobie code:
num1 = int(input("\nEnter a number 1 or greater:\t"))
counting = num1 + 1
def count():
print("Counting from 0 to", num1,":")
for i in range(0,counting):
print(i, end = ' ')
math_op()
def reset():
num1 = int(input("Too small - Try again: "))
if num1 <= 0:
reset()
else:
count()
def math_op():
ops = input("\n\nChoose math operation (+, -, *)")
if ops in ('+'):
print("Table for",num1,"using +:")
for i in range(1,11):
print(num1 ,'+', i ,'=', num1 + i)
if ops in ('-'):
print("Table for",num1,"using -:")
for i in range(1,11):
print(num1 ,'-', i ,'=', num1 - i)
if ops in ('*'):
print("Table for",num1,"using *:")
for i in range(1,11):
print(num1 ,'*', i ,'=', num1 * i)
if num1 <= 0:
reset()
else:
count()
Yes, you're missing a while loop:
num1 = -1
while num1 < 1:
num1 = int(input("\nEnter a number 1 or greater:\t"))
# remaining code after here
you never set the number to count when the correction is positive:
def reset():
num1 = int(input("Too small - Try again: "))
if num1 <= 0:
reset()
else:
counting = num1 + 1
count()

Python v3.3.5 maths questions program

Does anybody know why the score counter isn't working in this program? The program is designed to run 10 random maths questions and then display the score. However although it asks the questions, it will always display the score as being '0'
name = input('Type in your name')
questioncount = 0
score = 0
import random
for questioncount in range(0,10):
number1 = random.randrange(1,13)
number2 = random.randrange(1,13)
sign = random.randrange(1,4)
if (sign) == 1 :
print('{}x{}'.format(number1, number2))
elif (sign) == 2 :
print ('{}+{}'.format(number1, number2))
elif (sign) == 3 :
print ('{}-{}'.format(number1, number2))
answer = input('What is the answer?')
if (sign) == 1:
if (answer) == number1*number2:
score == score+1
else:
pass
if (sign) == 1:
if (answer) == number1+number2:
score == score+1
else:
pass
if (sign) == 1:
if (answer) == number1-number2:
score == score+1
else:
pass
pass
print('you got {} answers right!'.format(score))
There are some problems:
You forgot to change the numbers in the if statements.
You have to parse the input of the answer into int because input returns a string.
score == score+1 is a comparison and it always returns false. It should be "=". score = score + 1 or in a shorter way score += 1 is exactly the same
2 ifs nested for just one thing could be written in the same if statement.
You wrote this:
if (sign) == 2:
if (answer) == number1+number2:
score += 1
else:
pass
It could be:
if (sign) == 2 and (answer) == number1+number2:
score += 1
You should use if/elif statements instead of else:pass
This way
if (sign) == 1 and (answer) == number1*number2:
score += 1
elif (sign) == 2 and (answer) == number1+number2:
score += 1
elif (sign) == 3 and (answer) == number1-number2:
score += 1
and even better
if (sign == 1 and answer == number1 * number2) or (sign == 2 and answer == number1 + number2) or (sign == 3 and answer == number1 - number2) :
score += 1
That said, I would write this program like this:
import random
name = input('Type in your name\n')
score = 0
for _ in range(10):
number1 = random.randrange(1,13)
number2 = random.randrange(1,13)
sign = random.choice(["*", "+", "-"])
expression = "{0} {1} {2}".format(number1,sign,number2)
print(expression)
answer = int(input('What is the answer?\n'))
print("-------------")
if answer == eval(expression):
score += 1
print('{}, you got {} right answers!'.format(name, score))
Notes:
The use of _ it's because it is not important. You can call it whatever you want and you don't even have to declare it before.
The \n means carriage return.
You should do some more changes to prevent user from writting others characters in the answer, but I think you have work enough to do with this.

Resources