My problem is that when you answer a question the while loop keeps on repeating until all 10 questions are answered BUT this is only true for getting the answer correct
For getting it wrong it loops on forever
correct answer:
what is
7 * 2
Answer here: 14
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
you got the answer right,well done
Welldone you have answered all 10 questions and managed to get correct: 10
press enter to exit
Wrong answer:
wrong
wrong
wrong
and this repeats on and on and it doesn't end
This is the code for the program
import random
correct,number,left,right = 0,0,random.randint(6,10),random.randint(1,5)
add =(left+right)
sub =(left-right)
mul =(left*right)
StrAdd =("+")
StrSub =("-")
StrMul =("*")
StrOp=StrAdd,StrSub,StrMul
StrRandOp=random.choice(StrOp)
print("\n\nwhat is\n",left,"",StrRandOp,"",right,)
given = float(input("\nAnswer here: "))
while number < 10:
if given == add:
print("you got the answer right,well done")
correct=correct+1
number=number+1
elif given == sub:
print("you got the answer right,well done")
correct=correct+1
number=number+1
elif given == mul:
print("you got the answer right,well done")
correct=correct+1
number=number+1
else:
print("wrong")
print("""Welldone you have answered all 10 questions and managed to get
correct:""", correct)
input("press enter to exit")
This is what you want:
import random
correct,number,left,right = 0,0,random.randint(6,10),random.randint(1,5)
add =(left+right)
sub =(left-right)
mul =(left*right)
StrAdd =("+")
StrSub =("-")
StrMul =("*")
StrOp=StrAdd,StrSub,StrMul
StrRandOp=random.choice(StrOp)
print("\n\nwhat is\n",left,"",StrRandOp,"",right,)
given = float(input("\nAnswer here: "))
while number < 10:
if given == add:
print("you got the answer right,well done")
correct=correct+1
elif given == sub:
print("you got the answer right,well done")
correct=correct+1
elif given == mul:
print("you got the answer right,well done")
correct=correct+1
else:
print("wrong")
number = number + 1
print("""Welldone you have answered all 10 questions and managed to get
correct:""", correct)
input("press enter to exit")
When you want to iterate for a specific number of times it's better to use the for loop:
for number in range(0,10,1):
print "sth"
Related
import random
num=int(input("What is the highest number you want? "))
r=random.randint(0,num)
answer=int(input("Guess the number! "))
if answer!= r:
if answer < r:
print("More!")
if answer > r:
print("Less!")
if answer==r:
print("Correct!")
quit()
if answer !=r:
answer = int(input('Second guess out of 3! '))
if answer != r:
if answer < r:
print('Lower!')
if answer > r:
print('Higher!')
if answer == r:
print('Correct!')
quit()
answer = int(input('Final guess! '))
if answer == r:
print('Finally!')
quit()
else:
print('Damn... you lost.')
quit()
My limit was 5, and it said it was between 3 and 4.
I guessed 3 and it said it was too low.
I guessed 4 and it said it was too high.
Please help!
It may be the variables or possibly my limited understanding of the random module.
Am relatively new to programming so much explanation would be much appreciated.
You can never reach your "Correct" condition:
if answer!= r:
# etc
if answer==r:
print("Correct!")
quit()
It's not possible for answer == r to be true inside a block that's already conditional on answer != r.
What you probably want to do is check for answer == r immediately so you can quit() on a correct answer and otherwise continue. That way you don't even need to explicitly check for answer != r, which makes the code simpler by removing a lot of extra indentation:
import random
num = int(input("What is the highest number you want? "))
r = random.randint(0,num)
answer = int(input("Guess the number! "))
if answer == r:
print("Correct!")
quit()
if answer < r:
print("More!")
if answer > r:
print("Less!")
answer = int(input('Second guess out of 3! '))
if answer == r:
print('Correct!')
quit()
if answer < r:
print('Lower!')
if answer > r:
print('Higher!')
answer = int(input('Final guess! '))
if answer == r:
print('Finally!')
quit()
print('Damn... you lost.')
The problem you might be running into when you actually play your game is that you're using different words to indicate a wrong guess:
if answer < r:
print("More!")
if answer > r:
print("Less!")
# etc
if answer < r:
print('Lower!')
if answer > r:
print('Higher!')
In one case you're saying that the answer is more than the guess, and in the other you're saying that the guess is lower than the answer, and in both case you're meaning the same thing but saying something entirely different. (This is also made more confusing when reading the code because the answer is r and the guess is answer -- I had to reread it a few times when writing the above sentence to make sure I had it straight in my own head.) Maybe that's intentionally confusing to make the game harder, but if not you probably want to clarify the wording of your clues, or use the same wording both times.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 11 months ago.
I've been playing about with this for a few hours now and have tried a few variations and am still getting nowhere and am not sure what I'm getting wrong. I'm trying to make it so users can only give input values of a, b or c. If anyone could advise that would be greatly appreciated. Thanks.
def run_quiz(questions):
"""
Function loops through questions and checks answer given
against correct answer. If correct answer given
then score increases by 1.
"""
score = 0
for question in questions:
answer = input(question.prompt)
answer = answer.lower()
if answer == question.answer:
score += 1
while answer not in {'a', 'b', 'c'}:
return "Invalid answer, try again"
else:
return f"You guessed {answer}"
print(f"{name} got {score} out of {str(len(questions))} questions correct")
There's no need for those return statements.
def run_quiz(questions):
score = 0
for question in questions:
answer = input(question.prompt).lower()
while answer not in {'a','b','c'}:
answer = input("Invalid answer, try again").lower()
if answer == question.answer:
score += 1
print("Correct")
else:
print("Incorrect")
print(f"{name} got {score} out of {len(questions)} questions correct")
Every time I put in a number, it only prints the first input everytime instead of it being random. This is the code I used:
import random
import sys
answer = True
while answer:
question = input("Roll the di to get your fortune: ")
answers = random.randint(1,6)
if question == "":
sys.exit()
elif answer == 1:
print("You will get a new friend. ")
elif answer == 2:
print("You will go to disneyland. ")
elif answer == 3:
print("You will receive kindess.. ")
elif answer == 4:
print("Your will get a dog. ")
elif answer == 5:
print("You will suffer. ")
elif answer == 6:
print("You will have bad luck. ")
roll()
I really need help, I cant seem to figure out what I am doing wrong.
As a side note, you could make your code easier to work with if you replace your elifs with a dictionary of responses:
import random
import sys
responses = {
1: "You will get a new friend. ",
2: "You will go to disneyland. ",
3: "You will receive kindess.. ",
4: "Your will get a dog. ",
5: "You will suffer. ",
6: "You will have bad luck. "
}
answer = True
while answer:
question = input("Roll the di to get your fortune: ")
answer = random.randint(1,6)
if question == "":
sys.exit()
else:
print(responses[answer])
roll()
Change these lines in your code :
elif answer == 1:
print("You will get a new friend. ")
elif answer == 2:
print("You will go to disneyland. ")
elif answer == 3:
print("You will receive kindess.. ")
elif answer == 4:
print("Your will get a dog. ")
elif answer == 5:
print("You will suffer. ")
elif answer == 6:
print("You will have bad luck. ")
to these:
elif answers == 1:
print("You will get a new friend. ")
elif answers == 2:
print("You will go to disneyland. ")
elif answers == 3:
print("You will receive kindess.. ")
elif answers == 4:
print("Your will get a dog. ")
elif answers == 5:
print("You will suffer. ")
elif answers == 6:
print("You will have bad luck. ")
Where you went wrong: You were using answer variable defined as True in your conditions. In Python, True has a value of 1 this is why it was always running the condition "You will get a new friend. ". Also, you were storing the random dice digits in answers variable. Hope you understood!
You have a typo here where you're assigning to answers instead of answer:
answers = random.randint(1,6)
The True value you assigned to answer is the only one it will ever have; True is considered equal to 1 which is why you only ever get the first answer.
Using answer as your loop condition as well as for the die roll is a little confusing -- once you fix the typo above, it kind of works because all of the die rolls are "truthy", but it would work just as well (and be less prone to causing mistakes like this one) to use while True for the loop rather than using a variable whose value can never be false. Note that if you hadn't set answer = True at the start of your script, you would have spotted the answers typo immediately because checking answer == 1 would have raised a NameError. In general, the fewer variables you have to keep track of, and the less time you have to keep track of them for, the fewer chances there are for something to go wrong!
You don't need the question variable either since you immediately break the loop if it's empty and don't do anything else with it -- and for that matter you don't really need to keep track of answer and have a bunch of if statements based on it, since all you're really doing is picking one out of six possibilities -- there's a function called random.choice that makes that easy!
import random
while True:
if not input("Roll the die to get your fortune: "):
break
print(random.choice([
"You will get a new friend. ",
"You will go to disneyland. ",
"You will receive kindess.. ",
"Your will get a dog. ",
"You will suffer. ",
"You will have bad luck. ",
]))
Roll the die to get your fortune: ok
You will suffer.
Roll the die to get your fortune: ok
You will receive kindess..
Roll the die to get your fortune: ok
You will suffer.
Roll the die to get your fortune: ok
You will receive kindess..
Roll the die to get your fortune: ok
Your will get a dog.
Roll the die to get your fortune: ok
You will have bad luck.
Roll the die to get your fortune: ok
You will go to disneyland.
Roll the die to get your fortune:
You have an extra s when you roll the die on answers.
It should be:
answer = random.randint(1,6)
Making an IT quiz for school and I don't want it to be case sensitive, so I'd have 2 if statements if I want there to be 2 possible answers. My problem is that only one answer works.. May sound confusing.
a = input("And the answer is...")
if a == "answer1":
print("Correct!")
if a == "answer2":
print("Correct!")
else:
print("Incorrect!")
The outcome if you enter "answer1" is:
Correct!
Incorrect!
However, "answer2" will give you:
Correct!
Basically, I want both "answer1" and "answer2" to have the outcome of "Correct!"
A couple of different ways:
if a == "answer1" or a == "answer2":
print("Correct!")
else:
print("Incorrect!")
or
if a in ["answer1", "answer2"]:
print("Correct!")
else:
print("Incorrect!")
or
if a == "answer1":
print("Correct!")
elif a == "answer2":
print("Correct!")
else:
print("Incorrect!")
You can read more about in the "Flow Control" section of the Python tutorial.
While isowen's answer is correct, and is a better way of writing the function, it doesn't explain why the first one is wrong.
The actual problem is that the else only applies to the second if statement, not the first one. If you wanted to have different behavior for each case, you could do:
a = input("And the answer is...")
if a == "answer1":
print("Correct!")
elif a == "answer2":
print("Also Correct!")
else:
print("Incorrect!")
edit: isowen wasn't done yet when I wrote this.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
import random
number= random.randint(1,10)
count=0
guess=""
guess=int(input("please guess:")
while guess!= number:
if guess < number:
print("lower")
count++
elif guess > number:
print("higher")
count++
elif guess==number:
print("Good job, you got my number")
print("You got it in,",count,"tries")
FOr some reason when i try to run it, it says I have invalid syntax. Please help.
This is Python, not C or JS. This:
count++
Should be written as:
count += 1
Also, your keep in mind that Python is indentation-sensitive.
while guess!= number:
if guess < number:
print("lower")
count++
elif guess > number:
print("higher")
count++
elif guess==number:
print("Good job, you got my number")
print("You got it in,",count,"tries")
And lastly, you're missing a closing parenthesis:
guess=int(input("please guess:"))
Well, good luck learning!
You're missing an end parenthesis
guess=int(input("please guess:")
Should be:
guess=int(input("please guess:"))
Hope that helps
You also need to change your indenting on this:
elif guess==number:
print("Good job, you got my number")
print("You got it in,",count,"tries")
Also do increment correctly