This is my code, why won't it work for me? It asks the questions but misses the if statement that I have created.
print("What is your name?")
name = input("")
import time
time.sleep(1)
print("Hello", name,(",Welcome to my quiz"))
import time
time.sleep(1)
import random
ques = ['What is 2 times 2?', 'What is 10 times 7?', 'What is 6 times 2?']
print(random.choice(ques))
# Please note that these are nested IF statements
if ques == ('What is 2 times 2?'):
print("What is the answer? ")
ans = input("")
if ans == '4':
print("Correct")
else:
print("Incorrect")
elif ques == ('What is 10 times 7?'):
print("What is the answer? ")
ans = input("")
if ans == '70':
print("Correct")
else:
print("Incorrect")
elif ques == ('What is 6 times 2?'):
print("What is the answer? ")
ans = input("")
if ans == '12':
print("Correct")
else:
print("Incorrect")
import time
time.sleep(1)
import random
ques = ['What is 55 take away 20?', 'What is 60 devided by 2?', 'What is 500 take away 200']
print(random.choice(ques))
if ques == ('What is 55 take away 20?'):
print("What is the answer? ")
ans = input("")
if ans == '35':
print("Correct")
else:
print("Incorrect")
elif ques == ('What is 60 devided by 2?'):
print("What is the answer? ")
ans = input("")
if ans == '30':
print("Correct")
else:
print("Incorrect")
elif ques == ('What is 500 take away 200'):
print("What is the answer? ")
ans = input("")
if ans == '300':
print("Correct")
else:
print("Incorrect")
ques is at all times still equal to the full list, not to a single element of the list.
If you want use this method, I suggest doing the following:
posedQuestion = random.choice(ques)
print(posedQuestion)
if posedQuestion == "First question":
elif ...
In addition you only need to do your imports once, so only one line saying import time will do ;)
As well as the key error identified by MrHug, your code has the following problems:
Enormous amounts of unnecessary repetition;
Incorrect use of import;
Enormous amounts of unnecessary repetition;
A frankly bewildering attempt at string formatting; and
Enormous amounts of unnecessary repetition.
Note that the following code does what you are trying to do, but in a much more logical way:
# import once, at the top
import random
# use functions to reduce duplication
def ask_one(questions):
question, answer = random.choice(questions):
print(question)
if input("") == answer:
print("Correct")
else:
print("Incorrect")
# use proper string formatting
print("What is your name? ")
name = input("")
print("Hello {0}, welcome to my quiz".format(name))
# store related information together
ques = [('What is 2 times 2?', '4'),
('What is 10 times 7?', '70'),
('What is 6 times 2?', '12')]
ask_one(ques)
You could go further by storing the minimum information (i.e. the two numbers and the operator) in the list of ques, then formatting the question and calculating the outputs in the code itself.
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 5 months ago.
from fileinput import close
from random import Random, random
print('Do you want to play a game?')
input1 = input("yes or no? ")
if input1 == "yes" or input1 == "Yes":
print("You have 3 tries to guess a random integer between 0-10. If you guess right
you win. If not I do. Ready?")
import random
def repeat():
number = random.randint(1,10)
print(number)
guess1 = input('Your first guess: ')
if guess1 == number:
print('You are correct! You only needed one try!')
else:
print('Wrong two tries left!')
guess2 = input('Your second guess: ')
if guess2 == number:
print('You are correct! You needed two tries!')
else:
print('Wrong one try left!')
guess3 = input('Your third and last guess: ')
if guess3 == number:
print('You are correct! It took you all three tries!')
else:
print('You are wrong! You lost! The number was:')
print(number)
input2 = input('Do you want to play again? Yes or No? ')
if input2 == 'Yes' or 'yes':
repeat()
else:
close()
else:
close()
repeat()
I have no clue where the mistake is, but when I guess number correctly it still says its wrong.
You need to convert all guesses into integers to compare since the default input type is string.
from fileinput import close
from random import Random, random
print('Do you want to play a game?')
input1 = input("yes or no? ")
if input1 == "yes" or input1 == "Yes":
print("You have 3 tries to guess a random integer between 0-10. If you guess right you win. If not I do. Ready?")
import random
def repeat():
number = random.randint(1,10)
print(number)
guess1 = int(input('Your first guess: '))
if guess1 == number:
print('You are correct! You only needed one try!')
else:
print('Wrong two tries left!')
guess2 = int(input('Your second guess: '))
if guess2 == number:
print('You are correct! You needed two tries!')
else:
print('Wrong one try left!')
guess3 = int(input('Your third and last guess: '))
if guess3 == number:
print('You are correct! It took you all three tries!')
else:
print('You are wrong! You lost! The number was:')
print(number)
input2 = input('Do you want to play again? Yes or No? ')
if input2 == 'Yes' or 'yes':
repeat()
else:
close()
else: close() repeat()
New to programming and not sure how to print if the users answer to the list questions is correct or not and then add it to their ongoing score which will be displayed at the end of the program.
#number list test program
import random
import statistics
choosequestion = random.randint(1,4)
print('Welcome to the number list test')
print('e) Easy')
print('m) Medium')
print('h) Hard')
difficulty = input('Difficulty: ')
if difficulty == 'e':
print('Easy difficulty selected')
score = 0
questions = 2
quantity = 3
minimum = 1
maximum = 5
lists = random.sample(range(minimum, maximum), quantity)
if choosequestion == 1:
print ('What is the smallest number in this list?', lists)
finalmin = min = int(input(""))
elif choosequestion == 2:
print ('What is the biggest number in this list?', lists)
finalmax = max = int(input(""))
elif choosequestion == 3:
print ('What is the sum of numbers in this list?', lists)
finalsum = sum = int(input(""))
elif choosequestion == 4:
print ('What is the average of the numbers in this list?', lists)
average = statistics.mean = int(input(""))
##elif difficulty == 'm':
## print('Medium difficulty selected')
##
##elif difficulty == 'h':
## print ('Medium difficulty selected')
Any help will be great, thanks (when running the program select 'e' to start, I've commented out all other options)
Use for loops to ask questions repetitively.
As user enters answer, calculate the real answer in program and compare the result, to score.
You can refer below code.
#number list test program
import random
import statistics
choosequestion = random.randint(1,4)
print('Welcome to the number list test')
print('e) Easy')
print('m) Medium')
print('h) Hard')
difficulty = input('Difficulty: ')
if difficulty == 'e':
print('Easy difficulty selected')
score = 0
questions = 2
quantity = 3
minimum = 1
maximum = 5
for i in range(0,questions):
lists = random.sample(range(minimum, maximum), quantity)
if choosequestion == 1:
print ('What is the smallest number in this list?', lists)
if int(input(""))==min(lists):
score+=1
print("Correct answer")
else:
print("Wrong answer")
elif choosequestion == 2:
print ('What is the biggest number in this list?', lists)
if int(input(""))==max(lists):
score+=1
print("Correct answer")
else:
print("Wrong answer")
elif choosequestion == 3:
print ('What is the sum of numbers in this list?', lists)
if int(input(""))==sum(lists):
score+=1
print("Correct answer")
else:
print("Wrong answer")
elif choosequestion == 4:
print ('What is the average of the numbers in this list?', lists)
if int(input(""))==sum(lists)/len(lists):
score+=1
print("Correct answer")
else:
print("Wrong answer")
print("Your final score is : "+str(score))
The input() function in python returns a string of what the user types in a console. You can then compare the input string with the correct answer with an equal operator ==. (True if it matches, of course) I've finished a couple lines of code to demonstrate:
#Ask the User the Question
print ('What is the smallest number in this list?', lists)
#Get the User's response
userAnswer = int(input(""))
#Compare the response with the right answer
if(userAnswer == min(lists)):
#User was right
print("Correct")
score += 1
else:
#User was wrong
print("Wrong")
Change the min() function to max(), sum(), or your own function to get the right answer for each question.
For the future, many things could help improve this code:
Comment your code to give a main idea of what it is doing. I'm not talking one comment for each line, just a summary of sections of code.
When using an user input in any language, make sure to stress test it. The int(input("")) crashes the program when the user inputs a string.
Take advantage of functions, loops, and variables. I've seen programmers go down the rabbit hole of using if else statements too much. Do not avoid if else statements necessarily, but use patterns in answers and code to your advantage.
I would like my program to loop back up to the original question if a user would like to place a second order. Unfortunately, I cannot figure it out and am beyond frustrated.
import pprint
sizes = {'1':"tiny",'2':"small",'3':"normal",'4':"American"}
print('Welcome to The Tropical Shaved Ice Emporium\n')
print('Here are the sizes available')
print('Code','Size')
for code,size in sizes.items():
print('{} {}'.format(code, size))
result = input('\n\nPlease choose a size by typing the numeric code: ')
if int(result) == 1 or int(result) == 2 or int(result) == 3 or int(result) == 4:
print('\nThank you for your order.')
else:
print('There is not a size with that code\nPlease try again')
###woulld like this to go up to line 7 or 11 so they can try again###
result2 = input('\nWould you like to order another item?\nY or N? ')
if result2 == 'Y':
###woulld like this to go up to line 7 or 11 so they can try again###
if result2 == 'N':
print('Thank you for your order')
the program just ends! I have absolutely no idea how to take it back up to the original question, 'Please choose a size by typing the numeric code: '
Wrap the whole thing in a while loop.
# keep looping forever, until the user wants to stop
while True:
# ask for size etc.
# now ask if they want another order
answer = input('Would you like to place another order? (y/n) ')
if answer == 'n':
# end the loop
print('Thank you.')
break
You can put the question for what size to get in a function, and call that function when the user enters yes.
I also improved your code to not be case sensitive and ask again if the y/n answer is invalid
import pprint
sizes = {'1':"tiny",'2':"small",'3':"normal",'4':"American"}
print('Welcome to The Tropical Shaved Ice Emporium\n')
def ask():
print('Here are the sizes available')
print('Code','Size')
for code,size in sizes.items():
print('{} {}'.format(code, size))
result = input('\n\nPlease choose a size by typing the numeric code: ')
if int(result) == 1 or int(result) == 2 or int(result) == 3 or int(result) == 4:
print('\nThank you for your order.')
else:
print('There is not a size with that code\nPlease try again')
###woulld like this to go up to line 7 or 11 so they can try again###
ask_to_continue()
def ask_to_continue():
result2 = input('\nWould you like to order another item?\nY or N? ')
if result2.upper() == 'Y':
ask()
elif result2.upper() == 'N':
print('Thank you for your order')
else:
ask_to_continue()
ask()
I have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on.
import random
from time import sleep
#Introduction & Instructions
print ("Welcome to guess the number")
print ("A random number from 0 - 1000 will be generated")
print ("And you have to guess it ")
print ("To help find it you can type in a number")
print ("And it will say higher or lower")
guesses = 0
number = random.randint(0, 1)#Deciding the number
while True:
guess = int (input("Your guess: "))#Taking the users guess
#Finding if it is higher, lower or correct
if guess < number:
print ("higher")
guesses += 1
elif guess > (number):
print ("lower")
guesses += 1
elif guess == (number):
print ("Correct")
print (" ")
print ("It took you {0} tries".format(guesses))
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ('Invalid input.')
if answer == 'y':
continue
if answer == 'n':
exit()
First of all, when you check :
if answer in ('y','n'):
This means that you are checking if answer exists in the tuple ('y','n').
The desired input is in this tuple, so you may not want to print Invalid input. inside this statement.
Also, the break statement in python stops the execution of current loop and takes the control out of it. When you breaked the loop inside this statement, the control never went to the printing statement or other if statements.
Then you are checking if answer is 'y' or 'n'. If it would have been either of these, it would have matched the first statement as explained above.
The code below will work :
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
exit()
else:
print ('Invalid input.')
continue
Also, you might want to keep the number = random.randint(0, 1)#Deciding the number statement inside the while loop to generate a new random number everytime the user plays the game.
This is because of the second while loop in your code. Currently when you put y or n it will break and run again (you don't see the invalid message due to the break occurring before reaching that code), it should be correct if you change it to the following:
while True:
answer = input('Run again? (y/n): ')
# if not answer in ('y', 'n'):
if answer not in ('y', 'n'): # edit from Elis Byberi
print('Invalid input.')
continue
elif answer == 'y':
break
elif answer == 'n':
exit()
Disclaimer: I have not tested this but it should be correct. Let me know if you run into a problem with it.
I'm working on a Python script where a user has to guess a random number, selected by the script. This is my code:
import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)
while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break
It works... Sort of... I was trying it and came across this:
User enters 2, it says it's incorrect, but then displays the same number!
I have the feeling that, every time I call the variable 'number', it changes the random number again. How can I force the script to hold the random number picked at the beginning, and not keep changing it within the script?
As far as I understand it, you want to pick a new random integer in every loop step.
I guess you are using python 3 and so input returns a string. Since you cannot perform comparisson between a string and an int, you need to convert the input string to an int first.
import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
try:
antwoord = int(antwoord)
except:
print ("You need to type in a number")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)
while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break