Python3 How do I make randomized multiple choice questions/answers? - python-3.x

Basically I'm doing a multiple choice question president quiz on who served before the others in said multiple choice question. I've gotten it down fully looped with out the randomness but now I've incorporated arrays and random questions, basically I need to figure out how to make multiple choice questions and then define the logic so that when a person inputs 1,2, or 3 the game will look at all three listed options and know which one is the lowest on the presidents list to identify the correct answer.
lives = True
import array
import random
print("Welcome to Ahmed's U.S Presidential Quiz!")
print("Please enter your name!")
userName = input()
def answer():
if response == presidents
def lifeCount():
if livesRemaining == 0:
print("You're out of lives! Good luck trying again!")
quit()
if livesRemaining == 0:
quit()
while lives:
presidents = ["George Washington","John Adams","Thomas Jefferson","James Maddison","James Monroe","John Quincy Adams",
"Andrew Jackson","Martin Van Buren","William Henry Harrison","James K. Polk","Zachary Taylor","Franklin Pierce","James Buchanan","Abraham Lincoln",
"Ulysses S. Grant","Rutherford B. Hayes","James A. Garfield ","Grover Cleveland","Herbert Hoover","Calvin Coolidge","Franklin D. Roosevelt","Harry S. Truman",
"Dwight D. Eisenhower","John F. Kennedy","Richard Nixon","Jimmy Carter","Ronald Reagan","Bill Clinton","George W. Bush","Lyndon B. Johnson"]
livesRemaining = 3
print("Nice to meet you", userName,)
print("Today you'll be taking a quiz on which U.S President served first out of three options!")
print("You'll have only three chances to mess up! Let's get started!")
print("Choose either number 1 2 or 3 on your keyboard!")
print(random.choice(presidents)); print(random.choice(presidents)); print(random.choice(presidents))
response = input()
if response == "1":
print("Correct! 1/10!")
else:
livesRemaining -= 1
print("Incorrect!")
lifeCount() ```

Related

You have to build a dictionary (Or any other container of your choice) . Using python

You have to build a dictionary (Or any other container of your choice) which contains multiple True/false type quiz questions.
Every participant/user will attempt 5 rounds and in each round random quiz questions will be displayed to the user/participant.
If the participant answers the quiz question correct, then congratulate him and add the scores.
At the end display the details and score of the participant.
I have tried but I am not getting expected output.
I hope it can be useful for you. There are many other ways to do it but i think in this way you can understand easier what the script is doing.
import requests
import random
import numbers
def get_quiz_questions():
response = requests.get('https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json')
if response.status_code != 200:
return [
["The Mars Rover \"Spirit\" is powered by six small motors the size of \"C\" batteries. It has a top speed of 0.1 mph.", True],
["Burt Reynolds was originally cast to be Han Solo in the first Star Wars film. He dropped out before filming.", True]
]
return response.json()
# Get questions
quiz_questions = get_quiz_questions()
# Get numeric value, retry if it's not valid.
def get_numeric_value(message):
print(message)
value = input()
if not(value and value.isnumeric()):
print('Entered value is not valid\n')
# using recursion to prompt again for a valid value
return get_numeric_value(message)
return int(value)
def request_boolean_answer():
print('Enter answer: [ 0: false | 1: true]')
answer = input()
# Check if the value entered is numeric and if it's not 1 or 0
if answer.isnumeric() and ( 0 != int(answer) != 1):
print('Entered answer is not valid\n')
# using recursion
return request_boolean_answer()
return bool(answer)
# Start Game
num_players = get_numeric_value('\nEnter number of players: ')
num_questions = get_numeric_value('\nEnter number of questions: ')
score = {}
for player in range(num_players):
print("\nPlayer #:", player )
# initialize score for current user
score[f'player_{player}'] = 0
for question in range(num_questions):
question, answer = random.choice(quiz_questions)
print(question)
user_answer = request_boolean_answer()
print(f'Your answer: {user_answer}, correct answer: {answer}\n')
# Add a point if the answer is correct
if answer == user_answer:
score[f'player_{player}']+=1
print(f'\nScore: {score}')

JUMBLE WORDS ,I want that if once the word is asked to any player should not repeat

I dont want to reapt the word once aksed with one player
i am creating jumble words game but the proble is the word once used are repeating again and again so what should i do to avoid it
please explain what to do
i tried using del also but it did not worked out ,also i tried all pop but still unable to excute
kindly suggest
import random
def choose():
words=["rainbow","computer","science","mathmatics","player","condition","water","reverse","board","education","sharemarket","mango","magnum","mirchi"]
pick=random.choice(words) #to choose random words we have used random library
return pick
def jumble(word):
jumbled="".join(random.sample(word,len(word))) #join function is used to join words together,also random.sample word
return jumbled #randmoly select the word
def thank(p1name,p2name,points_p1,points_p2):
print(p1name,"your score is :", points_p1)
print(p2name,"your score is :", points_p2)
print("THANKS FOR PLAYING\n Have a nice day!!!!!!!")
def play():
p1name=input("player 1, Please enter your name ")
p2name=input("player 2, Please enter your name ")
points_p1=0
points_p2=0
turn=0
while(1):
#computer will give question to players picked words
picked_word=choose()
#now create the question
Q=jumble(picked_word)
print(Q)
#PLAYER 1
if turn%2==0:
print(p1name,"your turn. ")
answer=input("What's in your mind\n")
if answer==picked_word:
points_p1=points_p1+1
print("your score is :" , points_p1)
else:
print("better luck next time", picked_word)
c=int(input("press 1 to continue and 0 to quit"))
if c==0:
thank(p1name,p2name,points_p1,points_p2)
break
#player 2
else:
print(p2name,"your turn. ")
answer=input("What's in your mind\n")
if answer==picked_word:
points_p2=points_p2+1
print("your score is :" , points_p2)
else:
print("better luck next time", picked_word)
c=int(input("press 1 to continue and 0 to quiet "))
if c==0:
thank(p1name,p2name,points_p1,points_p2)
break
turn=turn+1
play()
To not repeat words add below code. It will maintain a list of already chosen words so far and if it's already used then it will again go to choose till it gets unused word.
def play():
p1name = input("player 1, Please enter your name ")
p2name = input("player 2, Please enter your name ")
points_p1 = 0
points_p2 = 0
turn = 0
chosen_words = []
while (1):
# computer will give question to players picked words
while (1):
picked_word = choose()
if picked_word in chosen_words:
pass
else:
chosen_words.append(picked_word)
break
# now create the question
Q = jumble(picked_word)
print(Q)
word not repeated once asked to any player
Output:
Connected to pydev debugger (build 193.6494.30)
player 1, Please enter your name Pooja
player 2, Please enter your name Meera
rchimi
Pooja your turn.
What's in your mind
mirchi
your score is : 1
ecnscie
Meera your turn.
What's in your mind
science
your score is : 1
ayeprl
Pooja your turn.
What's in your mind
player
your score is : 2
stcithmmaa
Meera your turn.
What's in your mind
mathmatics
your score is : 2
mharreeakts
Pooja your turn.
What's in your mind
sharemarket
your score is : 3
waret
Meera your turn.
What's in your mind
water
your score is : 3
noiitcdno
Pooja your turn.
What's in your mind
condition
your score is : 4
ndiueocta
Meera your turn.
What's in your mind
education
your score is : 4
gammun
Pooja your turn.
What's in your mind
magnum
your score is : 5
uertocpm
Meera your turn.
What's in your mind
computer
your score is : 5
servere
Pooja your turn.
What's in your mind
reverse
your score is : 6
nogma
Meera your turn.
What's in your mind
mango
your score is : 6
iraownb
Pooja your turn.
What's in your mind
rainbow
your score is : 7
abdor
Meera your turn.
What's in your mind
board
your score is : 7

Python : How to get the respective age and balance of the matching name?

Objective A mini bank simulation using only python basics list,while loop,if else.
Issues 2. Search account.
Notes I want my program to return the respective age and balance of the matching name.Thanks in advance.
print("""1. Add Account
2. Search Account"
3. Exit \n\n""")
name = []
age = []
balance = []
while True:
choice = input("What is your choice ? : ")
if choice == "1":
name.append(input("Name : "))
age.append(input("Age : "))
balance.append(input("Balance : "))
print("Account Registration Done\n\n")
if choice == "2":
y = input("What is your Account Name ? > : ")
if y in name: # i want my program to return the respective age and balance of the matching name.
print(name[0]) # Here is the issue and i don't know how to fix.Please Kindly enlighten me
print(age[0])
print(balance[0])
else:
print(
f"Your name[{y}] have't registered yet.Please register first")
if choice == "3":
break
The most recently added bank account in your code will be the bank account at the end of the lists. You can access it by name[-1], age[-1], and balance[-1]. Negative indices in Python mean searching backwards so -1 gives you the last element of a list.
To search for an account you can do:
if y in name:
found = name.index(y)
Then you can do age[found] and balance[found] to get the respective age and balance.
If you're adding new elements to the end of the list (ie .appending() them), you can list[-1] to get the last (therefore newest) element in the list.

working on code to see if the input car model is there in the collection provided... however only else block working

The for loop is working eventhough the provided value is in the list
Tried to run the code in different IDEs. but code did not work in any of these environments
#Check whether the given car is in stock in showroom
carsInShowroom = ["baleno", "swift", "wagonr", "800", "s-cross", "alto", "dezire", "ciaz"]
print("Please enter a car of your choice sir:")
carCustomer = input()
carWanted = carCustomer.lower()
for i in carsInShowroom:
if i is carWanted:
print("Sir we do have the Car")
break
else:
print("Sorry Sir we do not currently have that model")
Only else block running. when I enter wagonr, the output says "Sorry Sir we
do not currently have that model"
Change this,
if i is carWanted: # `is` will return True, if
to
if i == carWanted.strip(): # strip for remove spaces
Why?
is is for reference equality.
== is for value equality.
*Note: Your input should be wagonr not wagon r

Python how do you get a particular part of code to run again

Okay so I'm very new to the programming world and have written a few really basic programs, hence why my code is a bit messy. So the problem i have been given is a teacher needs help with asigning tasks to her students. She randomly gives the students their numbers. Students then enter their number into the program and then the program tells them if they have drawn the short straw or not. The program must be able to be run depending on how many students are in the class and this is where i am stuck, I can't find a way to run the program depending on how many students are in the class. Here is my code
import random
print("Welcome to the Short Straw Game")
print("This first part is for teachers only")
print("")
numstudents = int(input("How many students are in your class: "))
task = input("What is the task: ")
num1 = random.randint(0, numstudents)
count = numstudents
print("The part is for students") #Trying to get this part to run again depending on number of students in the class
studentname = input("What is your name:")
studentnumber = int(input("What is the number your teacher gave to you: "))
if studentnumber == num1:
print("Sorry", studentname, "but you drew the short straw and you have to", task,)
else:
print("Congratulations", studentname, "You didn't draw the short straw")
count -= 1
print("There is {0} starws left to go, good luck next student".format(count))
Read up on for loops.
Simply put, wrap the rest of your code in one:
# ...
print("The part is for students")
for i in range(numstudents):
studentname = input("What is your name:")
#...
Also, welcome to the world of programming! :) Good luck and have fun!

Resources