Python joke or chat error - python

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!!!!")

Related

How to break a function to a specific spot after a failed test

def joe():
while True:
name = ""
answer = ""
print("What is your name? ")
name = input()
if name != "Joe":
continue
print("What is your password? (it is a fish) ")
answer = input()
if answer == "swordfish":
break
print("nice job, Joe")
joe()
If I pass the frist statement and type in "Joe" i continue with the function, and all is good. but if I fail the second test, I break the function and get retrieved back to the "what is your name?" part of the function. How can I write a test that will upon failiure retreive me back to the "what is your password"? instead of the name test?
or try this:
def joe():
name = ""
answer = ""
print("What is your name? ")
name = input()
if name == "Joe":
print("What is your password? (it is a fish) ")
answer = input()
if answer == "swordfish":
return print("nice job, Joe")
joe()
joe()
Try using the combination of a while True and `return statement my bro!
def joe():
while True:
print("What is your name? ")
name = input()
if name != "Joe":
continue
while True:
print("What is your password? (it is a fish) ")
answer = input()
if answer == "swordfish":
print("nice job, Joe")
return
joe()
Add another while loop for the password part.
def joe():
while True:
print("What is your name? ")
name = input()
if name == "Joe":
break
while True:
print("What is your password? (it is a fish) ")
answer = input()
if answer == "swordfish":
break
print("nice job, Joe")

I'm trying to make a simple program in python, but im stuck

I'm trying to make a very simple program in python, but it says syntax invalid in an error window. I cant understand what's wrong with it:
print('What is your name?')
YourName = input()
if YourName == "Alice":
print('Hello Alice')
elif print('How old are you?')
age = input()
elif age < 4:
print('And you know how to write at young age!')
Try this:
print('What is your name?')
YourName = input()
if YourName == "Alice":
print('Hello Alice')
else:
print('How old are you?')
age = int(input())
if age < 4:
print('And you know how to write at young age!')
And a one-liner:
print("Hello Alice") if input("What is your name ")=="Alice" else print('And you know how to write at young age!') if int(input("How old are you? "))<4 else None
Problem with your Code
Welcome! The following line is wrong:
elif print('How old are you?')
There are two main reasons behind this:
print('How old are you?') is not a normal condition. Although this is technically fine since your compiler will evaluate it as type None and treat it as if it is False, you might want to replace that part with something that is conceptually meaningful.
You're missing a colon after the elif. For example:
elif (int(input()) < 4):
#your code
Solution
print('What is your name?')
YourName = input()
if YourName == "Alice":
print('Hello Alice')
else:
print('You are not Alice! How old are you?')
if int(input()) < 4:
print('You know how to write at young age!')

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

Python write to file maths generator

hello i have my code for a random maths quiz and i want it to save the name and there score next to the file and i want it to keep the data and not write over it every time could someone please help me and add this in i would like it so it could reocrd it like this let say i played it i would like the file to be like this then if someone else took the quiz it just adds there name to the list not erase the list first
name score
def quiz():
import random
import time
name=input("What is your name?")
print ("Alright",name,"Welcome to your maths quiz")
score=0
question=0
for question in range (1,11):
ops=['*','+','-']
rand=random.randint(1,10)
rand2=random.randint(1,10)
operation=random.choice(ops)
maths = eval(str(rand) + operation + str(rand2))
print ("Question",question)
time.sleep(0.5)
print (rand,operation,rand2)
question=question+1
d=int(input ("What is your answer:"))
if d==maths:
print ("Correct")
score=score+1
else:
print ("Incorrect. The actual answer is",maths)
if score >=7:
print ("Well done you got",score,"out of 10")
else:
print ("Unlucky you got",score,"out of 10")
percentage=score/10*100
print ("You got",percentage,"%")
f = open('results.txt','w')
f.write('%d' % score)
f.close()
playagain = 'yes'
while playagain == 'yes':
quiz()
print('Do you want to play again? (yes or no)')
playagain = input()
Change
f = open('results.txt','w')
to
f = open('results.txt','a')
Read the python docs for File I/O. 'w' overwrites an existing file
if you want the name with the score
f.write('{} : {}\n'.format(name, score) )

Python- Simple random selector

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']

Categories

Resources