Python- Simple random selector - python

I am creating a simple game in python where it asks you questions and then uses the answers to fill in the gaps in a story. I want to make it so that it will ask the questions in a random order each time but I want to have all of the questions asked.
I am using python 2.7.8 on Mac OSX and would like to know what I can do to get this result?
Thanks in advance for any help!
Code below if it helps :
while True:
print "Welcome to Consequences"
print ' '
print "Game is more fun in groups!"
print''
print "Group instructions :"
print "Get in a circle and let each person enter one thing each without the rest of the group seeing what they enter"
print ' '
print ' '
print raw_input("Press enter to start")
hide(str)
nameb = raw_input("Enter a boys name then press enter ")
hide(str)
nameg = raw_input("Enter a girls name then press enter ")
hide(str)
place = raw_input("Enter a place that two people meet then press enter ")
hide(str)
saidtg = raw_input("Enter what the boy said to the girl then press enter ")
hide(str)
saidtb = raw_input("Enter what the girl said to the boy and then press enter ")
hide(str)
end = raw_input("Enter what happened in the end and then press enter ")
hide(str)
print "Here is your story:"
print ' '
print nameb, "met", nameg
print "they met at", place
print "then",nameb,"said to", nameg, saidtg
print "then",nameg,"replied with", saidtb
print "in the end", end
raw_input("Press enter to start again")
print ' '
print ' '
print ' '
print ' '

You could store the questions in a list and use a dictionnary to store the variables:
questions = [('Enter name of boy', 'nameb') , ('Enter place', 'place'),...]
then shuffle the list and ask for each questions:
>>> import random
>>> random.shuffle(questions,random.random) #shuffle list in place
>>> d = {}
>>> for (q,v) in questions:
... d[v] = raw_input(q)
... #more stuff like hide(str)
Then instead of:
print nameb, "met", nameg
print "they met at", place
You only have to do
print d['nameb'], "met", d['nameg']
print "they met at", d['place']

Related

Python 3: How do I add input and a string to the same line?

I have to put the input on the same line as the string and can't figure out how.
Here's the code:
print('Hello! My name is Awesome Computer.')
print('What is your name?')
name = input()
print('It is good to meet you ' + name + '.')
print('How are you today?')
input()
print('Okay.')
print('I am doing great!')
The function input() takes in a string to print so you can do this:
name = input("What is your name? ")
And it will print the string before taking input without adding a newline
You can put a string into the input function parameters like I did below and it will print the string and get the input on the same line. Also, your second input function call wasn't being saved into a variable.
print('Hello! My name is Awesome Computer.')
name = input('What is your name? ')
print('It is good to meet you ' + name + '.')
# don't forget to save your input into a variable
mood = input('How are you today? ')
print('Okay.')
print('I am doing great!')
print('Hello! My name is Awesome Computer.')
# print('What is your name?')
name = input('What is your name? ')
print('It is good to meet you ' + name + '.')
# print('How are you today?')
input('How are you today? ')
print('Okay.')
print('I am doing great!')
Test Results
Hello! My name is Awesome Computer.
What is your name? John Doe
It is good to meet you John Doe.
How are you today? Healthy
Okay.
I am doing great!

I'm trying to make a quiz on Python but my code keeps repeating

So, I'm trying to make a basic quiz in Python and when I get to a certain point when I'm testing the program my code will repeat for reasons I can't seem to work out...
My code:
`if choice == "2": #If the user enters 2 they will be taken here.
print (" ") #Makes a break between lines.
username=input ("Please enter your username:")
print (" ") #Makes a break between lines.
password=input ("Please enter your password:")
file=open ("userinformation.txt","r")
for line in file:
if username and password in line:
print (" ") #Makes a break between lines.
print ("Thank you for logging in " + username+".")
time.sleep (3)
#file.close()
print (" ") #Makes a break between lines.
print ("Please choose a topic and a difficulty for your quiz.")
time.sleep (4)
print (" ") #Makes a break between lines.
print("a.History - Easy.")
print (" ") #Makes a break between lines.
print("b.History - Medium.")
print (" ") #Makes a break between lines.
print("c.History - Hard.")
print (" ") #Makes a break between lines.
print("d.Music - Easy.")
print (" ") #Makes a break between lines.
print("e.Music - Medium.")
print (" ") #Makes a break between lines.
print("f.Music - Hard.")
print (" ") #Makes a break between lines.
print("g.Computer Science - Easy.")
print (" ") #Makes a break between lines.
print("h.Computer Science - Medium.")
print (" ") #Makes a break between lines.
print("i.Computer Science - Hard.")
print (" ") #Makes a break between lines.
topic = input("To choose a topic please enter the corrosponding letter:")
if topic == "a":
print (" ") #Makes a break between lines.
time.sleep(2)
print ("You have selected option a, History - Easy.") #Tells the user what subject they picked (Same result but with a different topic and difficulty displayed for each one
print (" ")
print ("Rules: You have an unlimited amount of time to anwser each question. You will be anwsering 2 questions and each question anwsered correctly")
print ("will reward you with 10 points.")
time.sleep(9)
print (" ")
print ("The maximum amount of points you can get is 20.")
time.sleep(3)
print (" ")
print ("Good luck!")
print (" ")
time.sleep(2)
print ("Question 1 -")
print ("When did World War 1 begin and end?")
print ("a. 1913 - 1917") #Incorrect anwser
print (" ")
print ("b. 1914 - 1919") #Incorrect anwser
print (" ")
print ("c. 1914 - 1918") #Correct anwser
anwserq1he = input ("Please pick an anwser:")
if anwserq1he == "b":
print(" ")
print("Sorry, that's the wrong anwser...")
time.sleep(3)
print(" ")
hisready = input ("Type ok when you are ready to proceed to the next question.")
elif anwserq1he == "a":
print(" ")
print("Sorry, that's the wrong anwser...")
time.sleep(3)
print(" ")
hisready = input ("Type ok when you are ready to proceed to the next question.")
elif anwserq1he == "c":
print(" ")
print ("That's the right anwser!")
print(" ")
time.sleep(2)
print ("Adding 10 points to your score...")
score = score +10
print(" ")
time.sleep(3)
hisready = input ("Type ok when you are ready to proceed to the next question.")
if hisready == "ok":
print(" ")
time.sleep(2)
print ("Question 2-")
print ("Which historical figure is commonly known as 'The lady with the lamp'?")
print ("a. Margaret Fuller")
print (" ")
print ("b. Florence Nightingale")
print (" ")
print ("c. Rosa Luxemburg")
anwserq2he = input ("Please pick an anwser:")
if anwserq2he == "a":
print ("Sorry, that's the wrong anwser...")
results = input("Please type results to get your results")
elif anwserq2he == "c":
print ("Sorry, that's the wrong anwser...")
results = input("Please type results to get your results")
elif anwserq2he == "b":
print (" ")
time.sleep(2)
print ("That's the right anwser!")
print(" ")
time.sleep(2)
print ("Adding 10 points to your score...")
score = score + 10
results = input("Please type results to get your results.")
if results == "results":
print(" ")
time.sleep(3)
print ("Getting your results...")
if score == 20:
print ("Congratulations, you scored 20 points. That's the best score you can get!")
elif score == 10:
print ("Well done, you scored 10 points. Almost there!")
elif score == 0:
print ("You scored 0 points. Try again and you might do better!")`
When I complete the quiz everything beyond print ("Thank you for logging in " + username+".")repeats...I'd appreciate it if anyone could help me. Thank you.
Sidenote: The #file.close is intentional.
Alright, so first of all we need to improve the program layout , maybe call in some functions would be useful. Here is some tips to fix the program.
First of all use : if username.strip() and password.strip() in line: [Use the .strip() function so it will match a word.
Your program is inefficient because if you press another value as in 2 it will break the program. You want to loop it and loop it over and over again therefore use the while True statement and create a function.
Add a function called exampleFunction() (I.E) and then on the bottom of the code ad this line but obviously indent it.
while True:
exampleFunction()
You don't need to use a or r just do file=open("your file.txt")
For example,
genre=input("What is the film you would like to search?: ")
f=open("Films.txt")
for line in f:
if genre in line.strip():
print(line)
I would personally fix this myself and post a copy of the code however this is too minor to fix therefore i'm leaving it to you.
Goodluck,
Matin

I'm having problems whilst creating a quiz using python loops

The start of my code works fine but,the bottom part consisting on the score and answer doesn't. I'm doing a school project on this and need a solution quick. But I have to be using loops! The part where i'm trying to tell the user that the answer is correct isn't working. The part where i'm revealing the right answer isn't working as well. The score isn't working as well.
print ('WELCOME TO THE MULTIPLE CHOICE TEST\n')
name = input('WHAT IS YOUR NAME? ')
print ('\nHI THERE ' + name + '! LET''S PLAY A GAME!\n')
print ('I will ask you 10 questions and give you three choices for each question.\n\nYou select which choice is the correct answer. Eg. A, B,C or D\n')
score = 0
score = int(score)
qn1 = ["What's color of sky?", "a)Red", "b)Blue", "c)White", "d)Black"]
def print_question(qn_num):
print(qn_num[0])
print(qn_num[1])
print(qn_num[2])
print(qn_num[3])
print(qn_num[4])
print_question(qn1)
answer = input ()
answer =int(answer)
if answer == 2:
print ("good work")
score = score + 1
else:
print ("better luck next time")
score = score - 1
You can ask the answer in an infinite loop, and also show the score
print ('WELCOME TO THE MULTIPLE CHOICE TEST\n')
name = input('WHAT IS YOUR NAME? ')
print ('\nHI THERE ' + name + '! LET''S PLAY A GAME!\n')
print ('I will ask you 10 questions and give you three choices for each question.\n\nYou select which choice is the correct answer. Eg. A, B,C or D\n')
score = 0
score = int(score)
qn1 = ["What's color of sky?", "a)Red", "b)Blue", "c)White", "d)Black"]
def print_question(qn_num):
for st in qn_num:
print(st)
print_question(qn1)
allowed_answers = ["a", "b", "c", "d"]
wrong_answer = True
while(wrong_answer):
answer = input ("select answer: ")
if answer == 'b':
print ("good work")
score = score + 1
wrong_answer = False
elif answer not in allowed_answers:
print ("Bad input, you have to chose between " + ",".join(allowed_answers) )
else:
print ("better luck next time")
score = score - 1
print("Your score is: " + str(score))

Python joke or chat error

when i run this, if i type chat it runs the punchline from the joke above how do i fix this?
enter image description here
print ("whats your name?")
firstname = input()
print ("hello,", firstname)
print ("what's your surname?")
surname = input()
fullname = (firstname +" "+ surname)
print ("hello,", fullname)
print ("what shall i call you on a daily basis?")
name = input()
print ("Glad to meet you,", name)
print ("is there anything you would like to do?")
print (" you can 'hear a joke' or 'have a chat'")
question = input("joke or chat?")
if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")
if question == "chat":
print("what games do you like?")
game = input()
print ("NO way i love,", game)
In the absence of proper indentation, Python is assuming that the lines
idk = input()
print ("Dead!!! LOL!!!!")
are outside the if statement. Indent them like you did for the print statement for the punchline.
Your spacing / indentation is off:
if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")
In your code should be:
if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")
PS: You should use more than 1 space for indenting to make it easier to read. Such as:
if question == "joke":
print("what do you call a deer with no heart?")
idk = input()
print ("Dead!!! LOL!!!!")

Python - NameError name [variable] is not defined

Original question for context:
I was working on a quick little password program and came across the error:
NameError name 'confirm' is not defined.
I am using Python 3.3, I am trying to use a password then enter no (2) it then supplys me with the error.
Here is my code:
password=input ("Enter a password: ")
print ('Are you sure ' +password+ ' is a safe password?')
print ("1. YES")
print ("2. NO")
confirm=input ("Insert a number: ")
if comfirm is 2:
password=input ("Enter a password: ")
print ('Are you sure ' +password+ ' is a safe password?')
print ("1. YES")
print ("2. NO")
confirm=input ("Insert a number: ")
if confirm is 2:
password=input ("Enter a password: ")
print ('Are you sure ' +password+ ' is a safe password?')
print ("1. YES")
print ("2. NO")
confirm=input ("Insert a number: ")
Edit, a few years later:
Please ensure you always look over your code for spelling and syntaxical mistakes, especially in new lines of code you have just deployed/built/executed. Mistakes can range from spelling mistakes to incorrect case or to syntax and beyond.
Just a typo error-if comfirm is 2:

Categories

Resources