I'm in school, and since we are rather young students, some of my 'colleagues' do not grasp what case sensitivity is. We are making a quiz in Python. Here is the code:
score = 0 #this defines variable score, and sets it as zero
print("What is the capital of the UK?")
answer = input ()
if answer == "London":
print("Well done")
score = score + 1 #this increases score by one
else:
print("Sorry the answer was London")
print("What is the capital of France?")
answer = input ()
if answer == "Paris":
print("Well done")
score = score + 1 #this increases score by one
else:
print("Sorry the answer was Paris")
print("Your score was ",score)
They are inputting 'london' as an answer instead of 'London' and still getting the answer wrong. Any workaround?
You can use .upper() or .lower()
if answer.lower() == 'london':
You can use string1.lower() on answer and you can then make a variable for London and it string1.lower().
example:
string1 = 'Hello'
string2 = 'hello'
if string1.lower() == string2.lower():
print "The strings are the same (case insensitive)"
else:
print "The strings are not the same (case insensitive)"
You can use .capitalize()
answer = raw_input().capitalize()
Related
I was working on a small quiz recently and I have been trying to figure out why it inputs one answer and tries to answer all the questions with one answer I have been trying to figure this out for 2 to 3 days now, sorry if there is a simple solution I am a new coder
TLDR; code takes one answer and tries to solve all questions
import random
score = 0
n = ["What is the capital of Arizona: ", "What thing in Arizona is a part of the 7 natural wonders of the world (ABRIVEATE ANSWER TO THE 1ST LETTER OF EACH WORD): ", "what is the timezone in Arizona: "]
i = 0
answer = input(random.choice(n))
while (i < 3):
if [0]:
if answer == "Phoenix" or "phoenix":
print("Correct")
score += 1
print(score)
else:
print("incorrect")
if [1]:
if answer == "TGC" or "TGC":
print("Correct")
score += 1
print(score)
else:
print("incorrect")
if [2]:
if answer == "GMT":
print("Correct")
score += 1
print(score)
else:
print("incorrect")
i += 1
Compare your original to the below.
Note: I tried to change as little as possible and I'm not saying this is how to do it but to pass back your code with the minimum changed. It assumes you would like to ask all questions (I may have got that incorrect!).
import random
# track score
score = 0
# keep a list of which questions have been asked already
asked = []
# list of questions
n = ["What is the capital of Arizona: ", "What thing in Arizona is a part of the 7 natural wonders of the world (ABBREVIATE ANSWER TO THE 1ST LETTER OF EACH WORD): ", "what is the timezone in Arizona: "]
# loop while there are unasked questions
while len(asked) < len(n):
# set initial choice of 0,1,2 (same as positions in n)
choice = random.randint(0,2)
# if the choice has already been asked loop
while choice in asked:
choice = random.randint(0,2)
# add the valid choice to the asked list so the question in that position doesn't get asked again
asked.append(choice)
# ask the question from the list n, index position 'choice'
answer = input(n[choice])
if choice == 0:
if answer.lower() == "phoenix":
print("Correct")
score += 1
print(score)
else:
print("incorrect")
# note the 'elif' which (for reading at least) makes the code less prone to errors
elif choice == 1:
# note the '.lower()' so you don't need Tgc or TGc or TGC or tgC or ...you get it :o)
if answer.lower() == 'tgc':
print("Correct")
score += 1
print(score)
else:
print("incorrect")
elif choice == 2:
if answer.lower() == "gmt":
print("Correct")
score += 1
print(score)
else:
print("incorrect")
# print the user's score starting with a couple of line returns for separation
print('\n\nYou scored {score} points for 3 questions!'.format(score=score))
Example:
What thing in Arizona is a part of the 7 natural wonders of the world (ABBREVIATE ANSWER TO THE 1ST LETTER OF EACH WORD): TgC
Correct
1
what is the timezone in Arizona: gMt
Correct
2
What is the capital of Arizona: A
incorrect
You scored 2 points for 3 questions!
I am writing a code for class due tomorrow(sorry for the late notice) but my number filter will not loop or detect the numbers. Could someone help please, also explain thoroughly as possible cause I have to the same when i present as well.
tryagain = True
print("Welcome to Hangman: The Game. Made by Matt, Will and Dom")
while tryagain:
print("To play please have player one input a word for player two to guess")
Input = input("Player one, Please input a word: ").lower()
Answer = Input.lower()
numbers = ("123456789!##$%^&*()_+{}:<>?|/.,';\][")
if numbers in Answer:
print("No numbers or speicals characters please")
continue
game = "_" * len(Answer)
alreadySaid = set()
mistakes = 7
print("Player two, Your word is", " ".join(game))
guess = False
while not guess and mistakes > 0:
attempt = input("Player two, please guess a letter: ")
if attempt in Answer:
alreadySaid.add(attempt)
game = " ".join([char if char in alreadySaid else "*" for char in Answer])
if game == Answer:
guess = True
else:
mistakes -= 1
print ("Wrong letter", "You have", mistakes, "left")
if mistakes == 0:
print("You have lost player Two")
break
print(" ".join(Answer))
tryagain = (input("Again [y/n]: ").lower() == 'yes')
if tryagain == "yes":
continue
The expression numbers in Answer will evaluate to True only if Answers contains the entire String numbers. It doesn’t return True if Answers only contains one or more characters in numbers.
A regular expression would be useful to you in this context.
I have just finished this code , added my final print line and now suddenly when I test it , it doesn't print out what I want it to print.
import random
name=input("Welcome to this Arithmetic quiz,please enter your name:")
score = 0
for i in range(10):
number1=random.randint(20,50)
number2=random.randint(1,20)
oper=random.choice('+-*')
correct_answer = eval(str(number1)+oper+str(number2))
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer)
if answer == correct_answer:
print('Correct!')
score +=1
else:
print('Incorrect!')
print("You got",score,"out of 10")
When I ever I give the right answer it still gives me Incorrect leading it to tell me that I got 0/10.
To match the symptoms reported I believe that your code is actually:
import random
name=input("Welcome to this Arithmetic quiz,please enter your name:")
score = 0
for i in range(10):
number1=random.randint(20,50)
number2=random.randint(1,20)
oper=random.choice('+-*')
correct_answer = eval(str(number1)+oper+str(number2))
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer)
if answer == correct_answer:
print('Correct!')
score +=1
else:
print('Incorrect!')
print("You got",score,"out of 10")
Note the indentation of the else statement is aligned with the if, not the for. Given that this line:
answer = (int(input('What is:'+str(number1)+oper+str(number2)+'=')) == correct_answer
assigns a boolean to the variable answer, not the answer that the user entered. You can do 2 things:
remove the == correct_answer part resulting in:
answer = int(input('What is:'+str(number1)+oper+str(number2)+'='))
or
change the if statement to:
if answer:
Here are the problems with your code:
You are incrementing score regardless of whether the answer is correct or not. Increase the indentation of score += 1 so that it lines up with the print that indicates a correct answer.
The else is bound to the for statement. Indent it so that it is bound to the if statement. Indent the print that follows it accordingly.
Your assignment to answer isn't just picking up the answer, but it's comparing it to the expected answer. So it will be True or False. You are then comparing that boolean value to the answer again, so of course the result if False. Change the assignment to:
answer = int(input('What is:'+str(number1)+oper+str(number2)+'='))
Probably the first two items were just posting errors, and the last one is what's preventing your code from working.
My code is:
import random
WORDS = ('python', 'football', 'facebook', 'photo') #list of words that will be riddled
word = random.choice(WORDS)
correct = word
jumble = ''
hint = 'hint'
score = 0
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):] #creating jumble of correct words
print('Welcome to the game "Anagrams"')
print('Here`s your anagram:', jumble) #Welcoming and giving a jumble to a player
guess = input('\nTry to guess the original word: ')
if guess == correct:
score += 5
print('You won! Congratulations!') #end of game in case of right answer
if guess == hint: #situation if player asks a hint
if correct == WORDS[0]:
print('snake')
elif correct == WORDS[1]:
print('sport game')
elif correct == WORDS[2]:
print('social network')
elif correct == WORDS[3]:
print('picture of something')
score += 1
while guess != correct and guess != '': #situation if player is not correct
print('Sorry, you`re wrong :(')
guess = input('Try to guess the original word: ')
print('Thank you for participating in game.')
print('Your score is', score)
input('\nPress Enter to end')
When asking hint string :
'Sorry, you`re wrong :('
repeats.
It looks like:
Try to guess the original word: hint
sport game
Sorry, you`re wrong :(
How to make this string appear only in case of wrong guess?
change you last while to this:
while guess != correct and guess != '':
guess = input("Sorry, you`re wrong:( ")
In your code, when the player types hint the player gets a hint, but then the program tests the 'hint' string against the correct word. Of course, 'hint' isn't the correct answer, so your program tells them that it's wrong.
Just for fun, I've optimized your code a little, and improved the scoring logic. :)
Your letter-jumbling for loop is quite clever, but there's a more efficient way to do this, using the random.shuffle function. This function shuffles a list, in place. So we need to convert the chosen word into a list, shuffle it, and then join the list back into a string.
I've also replaced your hints logic. Rather than having to do a whole bunch of if tests to see which hint goes with the current word it's much simpler just to store each word and its associated hint as a tuple.
import random
#Words that will be riddled, and their hints
all_words = (
('python', 'snake'),
('football', 'sport game'),
('facebook', 'social network'),
('photo', 'picture of something'),
)
#Randomly choose a word
word, hint = random.choice(all_words)
#Jumble up the letters of word
jumble = list(word)
random.shuffle(jumble)
jumble = ''.join(jumble)
print('Welcome to the game "Anagrams"\n')
print('You may ask for a hint by typing hint at the prompt')
print('Wrong guesses cost 2 points, hints cost 1 point\n')
print("Here's your anagram:", jumble)
score = 0
while True:
guess = input('\nTry to guess the original word: ')
if guess == word:
score += 5
print('You won! Congratulations!')
break
if guess == 'hint':
#Deduct a point for asking for a hint
score -= 1
print(hint)
continue
#Deduct 2 points for a wrong word
score -= 2
print('Sorry, you`re wrong :(')
print('Thank you for participating in game.')
print('Your score is', score)
input('\nPress Enter to end')
Your special logic for a correct guess and for the special input "hint" is only run once on the very first guess. Your loop for incorrect values always runs after that. I think you want to move all the logic into the loop:
while True: # loop forever until a break statement is reached
guess = input('\nTry to guess the original word: ')
if guess == correct:
score += 5
print('You won! Congratulations!')
break # stop looping
if guess == hint: # special case, asking for a hint
if correct == WORDS[0]:
print('snake')
elif correct == WORDS[1]:
print('sport game')
elif correct == WORDS[2]:
print('social network')
elif correct == WORDS[3]:
print('picture of something')
score += 1
else: #situation if player is not correct, and not askng for a hint
print('Sorry, you`re wrong :(')
I've left out the situation where your code would exit the loop on an empty input. If you want that, you should add it explicitly as an extra case, with a break statement.
Lets try to fix some problems:
this
if guess == hint: #situation if player asks a hint
should probably be
elif guess == hint: #situation if player asks a hint
And also this seems wrong to me
while guess != correct and guess != '': #situation if player is not correct
print('Sorry, you`re wrong :(')
guess = input('Try to guess the original word: ')
should be probably changed into that (indentation is important):
guess = input('Try to guess the original word: ')
if guess != correct and guess != '': #situation if player is not correct
print('Sorry, you`re wrong :(')
I have not tried this corrections in a complete program.
Okay, so i'm trying to keep track of how many questions the player got right, but when I say 'score = +1' it adds nothing to the score. How do I do this? Here is my code:
score = 0
print('This is a 10 question quiz. Please do not use any capitol letters when answeringquestions'
)
print('1. Can elephants jump? (yes or no)')
answer_1 = input()
if answer_1 == 'yes':
print('Wrong! Elephants cannot jump.')
if answer_1 == 'no':
print('Correct! Elephants cannot jump!')
score = +1
print('(true or false) Karoake means \"Empty Orchestra\" In Japanese')
answer_2 = input()
if answer_2 == 'true':
print('Correct! Karoake does in fact mean \"Empty orchestra\" in Japanese')
score = +1
if answer_2 == 'false':
print('Wrong! Karoake does in fact mean \"Empty orchestra\" in Japanese')
print('Solve the math problem: What is the square root of 64?')
answer_3 = input()
if answer_3 == 8:
print('Good job! The square root of 64 is 8!')
score = +1
else:
print('Incorrect! the square root of 64 is 8.')
print(score)
score += 1
or
score = score + 1
Much better detailed answer:
Behaviour of increment and decrement operators in Python
It should be score += 1 you have the operator reversed.
When you say score = +1 you are saying set score to positive one.
What you're writing, score = +1, simply sets the 'score' variable to positive 1 (+1) over and over.
You really want to write, as samrap already said, either:
score += 1 - Sets the variable 'score' to one higher than what it was before
score = score + 1 OR score = (score + 1) - Sets the variable to the previous value plus 1 (The brackets, although not very python-like, help add clarity)