Below, I've inserted some code that is clearly wrong to all but the most novice of Python users.
Would people be so kind as to suggest some rookie improvements to the code, please? Such as logical variable names, adding comments, etc.
Corrections to the errors in the code will also be appreciated, as per the request in the question.
I'm having a problem with getting the loop below to work. Does anybody have a suggestion as to what's wrong? At the moment I get asked the question, and then the code shows an error.
What should happen is that I am asked a question, and then have 3 chances to answer correctly.
a = input("What is the opposite to night?")
for xx in range(0,3)
if a == Night:
print("That's right! Well done")
else:
print("Sorry, try again")
Please see below correction:
a = input("What is the opposite to night?")
for x in range(0,3): # must have colons at the end of for statement
if a.lower() == "night": # we should accept all cases
print("That's right! Well done") # indentation required in if statement
else:
print("Sorry, try again") # indentation required also
I think it would be more valuable to ask what is right:
The input(..) is only called once an not in the loop;
there is no colon at the end of the for loop;
you should use a string to compare the answer, so "Night";
the string actually should compare against "day" since that is the correct answer;
the answer is better tested case-insensitive;
one should not say "try again" if it was the last chance;
it is "opposite of" (kudos to #TemporalWolf);
there is no break if the answer is correct; and
the indentation is wrong.
So a fix would be:
for xx in range(0,3): # colon
a = input("What is the opposite of night?") # input in the loop
if a.lower() != "day": # comparing against "day" (string)
if xx < 2: #only print try again if it is not the last chance
print("Sorry, try again") #indentation
else:
print("Too bad, well goodbye.")
else:
print("That's right! Well done") # indentation
break # break if correct
Additional suggestion: you can use range(3) instead of range(0,3) which is shorter.
for _ in range(3): print(["Sorry, try again", "That's right! Well done"]
[input("What is the opposite to night?").lower()=='day'])
Not all answers will be helpful, even if they produce the "right" answer
&
If you 'borrow' code from StackOverflow, you'll probably get found out.
for xx in range(0,3)
should be
for x in range(0,3):
and furthermore can be optimized (albeit very minimally with a small range) by
for x in xrange(3)
Lastly, Night needs to be wrapped in quotations so:
if a == "Night"
Related
So I'm somewhat new to coding but I think I know basic things but I've spent a while trying different things but nothing has worked it might be something obvious that I've just over looked but I'm just not sure.
There isn't and actual error but what happens is even when I put the right answer in it only prints out the else statement. Any and all help is appreciated, thank you.
#at the end you go back through and see the ones you got wrong and it tells you the correct answer
import random
inccorrect = ["Good try but its wrong.", "Not quite the answer, you gave it a good shot though."]
correct = ["That is correct.", "Correct."]
def MQ1():
print("What does 2 + 2 =")
input("Enter the answer:")
if input == float(4):
print(random.choice(correct))
else:
print(random.choice(inccorrect))
def MQ2():
print("Lets make these questions harder.")
print("What does 4³ =")
input("Enter the answer:")
if input == "64":
print(random.choice(correct))
else:
print(random.choice(inccorrect))
def MQ3():
print("Lets see how far you can get!")
print("What does 6*10⁴ = ")
input("Enter the answer:")
if input == "60000":
print(random.choice(correct))
else:
print(random.choice(inccorrect))
#scoreboards keeps count of how many Qs you have gotten right or wrong
#need to check the answers
#need to count right and wrong answers and show above the next answer
#to avoid just printing out everything at once need to check if each question has been answered
def main():
MQ1()
MQ2()
MQ3()
main()```
Try this:
def MQ1():
print("What does 2 + 2 =")
answer = input("Enter the answer:") # STORE the input from user
if float(answer) == float(4):
print(random.choice(correct))
else:
print(random.choice(inccorrect))
You need to store the input that the user is entering.
I'll try to make a python program, convert roman to number. I believe my logic for the program is correct, but I get syntax error. maybe someone want's help me to fixed my program.
this my whole program:
bil = int(input())
if(bil<1 or bil>99):
print("no more than 3999")
else:
while(bil>=1000):
print("M")
bil-=1000
if(bil>=500):
elif(bil>500):
elif(bil>=900):
print("CM")
bil-=900
else:
print("D")
while(bil>=100):
if(bil>=400):
print("CD")
bil-400
else:
bil-=100
if(bil>=50):
elif(bil>=90):
print("XC")
bil-=90
else:
print("L")
bil-=50
while(bil>=10):
if(bil>=40):
print("XL")
bil-=40
else:
print("X")
bil-=10
if(bil>=5):
elif(bil==9)
print("IX")
bil-=9
else:
print("V")
bil-=5
while(bil>=1):
if(bil==4):
print("V")
bil-=4
else:
print("I")
bil-=1
I got syntax error in line :
elif(bil>500):
I need your opinion, thank you.
It shouldn't be elif, it should if bil>500. Because, you are trying to create a nested if condition and not an if/elif/else condition. So the final code in that block should be:
if(bil>=500):
if(bil>500):
if(bil>=900):
print("CM")
bil-=900
Also, I don't understand why you are comparing bil>500 two times at the same time. You could remove one if statement there
And there are many such if/elif blocks out there. You need to replace elif with if, if there is an indentation or you need to remove indentation for elif condition and write a condition for the if block too
I have a little piece of code in Python where I'm trying to compare a user input to a specific element in an array. Here is the code:
movies = ["movie 1", "movie2", "movie3"];
answer = raw_input("What is your guess: ")
if answer == movies[1]
then print ("yes that is correct")
else:
print ("no that is incorrect")
I know the indentation above looks wrong becasue I typed it out in the text box and I'm new to this site as well as python.
I also know that I probably need to use some sort of conditional loop, maybe a while loop, but I'm having trouble finding where I can compare user input string value to a string value in my array. Any ideas how I might accomplish this?
Have fun with Python! I guess you are trying to make a loop which keeps receiving inputs from user to compare with the desired input until user types the correct input. If so, one way, it can be implemented as following (but think of adding a break condition, like input == "Bored" , to avoid infinite loop and hard stopping your code):
movies = ["movie 1", "movie2", "movie3"]
correctAnswer = movies[1]
is_notCorrect = True
while(is_notCorrect):
answer = raw_input("What is your guess: ")
if answer == correctAnswer:
print("Yes, that is correct")
is_notCorrect = False
else:
print("No, that is incorrect")
In the code above, when is_notCorrect turns into False. At next condition checking, it will break condition, and done with the loop.
Your code has some issues
movies = ["movie 1", "movie2", "movie3"]; # No need the semi-colon in Python
answer = raw_input("What is your guess: ")
# Need a colon here after if condition, new line, and indent.
#If you don't like the colon, you need to write a different way with one line of code Eg: <Do A> if <Condition happens> else <Do B>
if answer == movies[1]
then print ("yes that is correct") # No then in if-else statement in Python
else:
print ("no that is incorrect")
myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
ready = input("Are you readyyyy!?")
if ready = "yes" or "yeah" or "totally" or "hell yeah" or "yupp" or "yepp" or "uhumm" or "sure": <-- here's the problem it says, at "sure"'s 1st "-sign
print("Let's go!")
loop = "y"
else:
print("I'm sorry to hear that.")
loop "n"
Could please anyone help, beginner here. I tried to delete and add new word, I restared the program and the computer because there's something clearly wrong. If I delete a word like "sure" the pointer will still point to the same exact place but there's nothing there...
You're using a single = sign in your if statement. That's not allowed. If you want to check for equality, you'll need to use ==. The = operator is only for assignment statements.
While changing = to == will fix the syntax error, your code still won't work exactly right. That's because == will not be distributed over all the or options you show. The expression a == b or c gets interpreted as (a == b) or c, and if c is "truthy" (as any non-empty string will be), the expression will be considered true.
Instead, you probably want to use something like if ready in {"yes", "yeah", "totally"}. This creates a constant set object and tests if the value of the ready variable is in the set (which is a fast check).
You are using a = instead of a == in your if statement. However, I would recommend doing if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp"} to account for them using all uppercase.
Also, you seem to be missing your actual loop statements. I noticed you had variables named loop that are 'y' and 'n' but don't actually use them. You should also do something like this:
myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
loop = True
while loop:
ready = input("Are you readyyyy!?")
if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp", "uhumm", "sure"}:
print("Let's go!")
loop = False
#To break out of the while loop that will keep asking them when they are ready
else:
print("I'm sorry to hear that.")
In the book "Python for the absolute beginner" by Michael Dawson, in the chapter on Lists and Dictionaries I have learned a great deal and am trying to make a new program as practice using the old Magic 8-Ball as my inspiration. Below is the code I have come up with so far.
It works up to a point...the random generated number gets generated but the elif doesn't seem to work. I know there are better ways and simpler ways, but I am doing this to reinforce my understanding of dictionaries.
I have put several print statements in to see if I was getting a number selected and the else statement is if all goes bad. As the code stands now all I get is the number printed and the else produces "Does not compute. Exit works fine. I have also confirmed the dictionary is fine using the commented out print "ball" statement.
So my issue is why does the elif statement seem to not process the random number generated. Whom ever answers has my heartfelt thanks and appreciation.
# Import the modules
import sys
import random
# define magic 8-ball dictionary
ball = {"1" : "It is certain.",
"2" : "Outlook is good.",
"3" : "You may rely on it.",
"4" : "Ask again later.",
"5" : "Concentrate and ask again.",
"6" : "Reply is hazy, try again later.",
"7" : "My reply is no.",
"8" : "My sources say no"}
# for items in ball.items():
# print(items)
ans = True
while ans:
question = input("Ask the Magic 8 Ball a question: (press enter to quit) ")
answer = random.randint(1,8)
print(answer)
if question == "":
sys.exit()
elif answer in ball:
response = ball[answer]
print(answer, response)
else:
print("\nSorry", answer, "does not compute.\n")
random.randint() returns an integer. Your dictionary's keys are all strings. Thus, when you do answer in ball, it will always be False, because "1" != 1
What you can do is either make all the keys integers (remove the quotation marks), or make answer a string by doing:
answer = str(random.randint(1,8))
Note that you shouldn't be using an elif here. If your input is nothing, both your if and elif will be True, and most of the time you don't want this. Instead, change your elif/else to just an if/else:
if question == "":
sys.exit()
if answer in ball:
response = ball[answer]
print(answer, response)
else:
print("\nSorry", answer, "does not compute.\n")
One final thing. answer will always be in ball, because you dynamically created the dictionary. Here, you can use dict.get(). Eg:
if not question: # You can do this instead
sys.exit()
print(ball.get(answer))
You are looking up on the dictionary with a number whereas the keys are strings in the dict. So, you have to convert the number to string with str.
Change
answer = random.randint(1,8)
to
answer = str(random.randint(1,8))
The string "1" is not the int 1. So answer is actually not in ball.
Try converting it like answer = str(random.randint(1,8))