syntax error using "if and elif" in python - python

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

Related

Check if a condition is respect instantly

I have a complex project and I will try to simplify one of the main problem of the project. So there is the simplification:
We can Imagine a while loop like this:
while(condition):
statement1
statement2
statement3
...
statementn
In this loop there n statements, and each statement can be whatever(function, loop, if statement,...) and there is a condition in the loop, this condition i want to check it BEFORE the while loop do it. Because if the condition is respect since the first statement I have to wait until the end of the while to check if the condition is respect... So there is my question is possible to check the condition BEFORE the loop without have a check-function between EACH statements of the whileloop ?
Because in fact, it's work... BUT the code isn't clear, I really think this way we pollute my code and i want to work more efficiently and with a beautiful code, so how can I solve my problem without this constraint ?
PS: I think about event listener like javascript but i found poor information about them on python, but if there is a tool which act like event listener it would be great !
It sounds like you want to clean up all your if-then-break statements into a single function that handles the "checking" of the value of a. For that purpose you could use exceptions:
import random
class ItIsFiveException(Exception): pass
def check(a):
if a == 5:
raise ItIsFiveException
try:
a = 0
while(a != 5):
a = random.randint(1,5); check(a)
a = random.randint(1,5); check(a)
a = random.randint(1,5); check(a)
a = random.randint(1,5); check(a)
except ItIsFiveException:
print("I saw a five!")
You just have to define your own python Exception as a class, and the raise it in your manually-defined check(a) function. Then you can wrap your entire while loop in a try-except block and catch your exception.
I am not sure if I understand you right, but this is what I'd do:
flag = False
while not flag:
for i in range(4):
a = random.randint(1, 5)
if a == 4:
flag = True
break
I don't know exactly what it happens with "a" but if if you can chain the conditions and will stop when the first one fails
while(checkRandom()):
...
def checkRandom(a):
return random.randint(1,5) == 5 and random.randint(1,5)....
If you can loop the generation of random values you can use
while(a!=5):
for item in range(1, 5):
a=random.randint(1,5)
if a==5:
break

Can't get FOR loop to work

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"

Python 3.x - Input only returns first item

I have been having problems with a block of code in a little project and I can't seem to fix it.
In the below code, I define inputrace() so that a process is carried out where the player types in a number that is above 0 and below 13 (there are 12 choices, each dictated by a number); it also checks for blank lines and strings and has the program state that there is an error and ask for user input again if they are detected. If it passes the check, RaceInp is returned and set to RaceChoice which allows the code below it to assign a Race to the player based on their selection.
#race check
def inputrace():
print ("Input number")
RaceInp = input()
Check = RaceInp
try:
int(RaceInp)
except ValueError:
print("Numbers only!")
inputrace()
if not int(Check)>12 or int(Check)<1:
return RaceInp
print (RaceInp) #this is here so I can check the value returned
Race = "NA"
RaceChoice = inputrace()
print (RaceChoice)
#assign race
if RaceChoice == "1":
Race = "Human"
#continues down to twelve
Everything works when valid strings are put in (any number 1-12), but things break when I purposefully put in an invalid string. It seems like RaceInp only retains the first user input and does not change, even after the function is recalled from an error. That means if I were to put in "a," the program will tell me it is wrong and ask again. However, when I put in "1" in an attempt to correct it, it accepts it but still keeps RaceInp as "a."
Is there any fix to this? I have no clue what's going on.
I appreciate the help and sorry if I got anything wrong in the question!
It seems that the problem is that you put the inputrace in a recursion instead of a loop. Something like this would probably be better:
def input_race():
while True:
print("Input a number between 1 and 12.")
race_input = input()
try:
race_input = int(race_input)
if race_input >= 1 and race_input <= 12:
return race_input
except ValueError:
pass
print ("'{input}' is not a number.".format(input=race_input))
race = "NA"
race_choice = input_race()
if race_choice == 1:
race = "Human"
print(race)

In this very basic code i can't figure out what's the sytax error here in line 6 is (python)

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

(Python) For loop syntax - execute for only one item?

Pretty new to python/programming in general, this is my biggest project yet.
I am writing a program that will do SUVAT equations for you. (SUVAT equations are used to find the displacement, start/end velocity, acceleration and time travelled by an object with constant velocity, you may call them something different.)
I made this list:
variables = ["Displacement", "Start Velocity", "End Velocity", "Acceleration", "Time"]
which is used in the following while/for loop:
a = 0
while a==0:
for variable in variables:
# choice1 is what the user is looking to calculate
choice1 = raw_input("Welcome to Mattin's SVUVAT Simulator! Choose the value you are trying to find. You can pick from " + str(variables))
# will execute the following code when the for loop reaches an item that matches the raw_input
if choice1 == variable:
print "You chave chosen", choice1
variables.remove(variable) #Removes the chosen variable from the list, so the new list can be used later on
a = 1 # Ends the for loop by making the while loop false
# This part is so that the error message will not show when the raw_input does not match with the 4 items in the list the user has not chosen
else:
if choice1 == "Displacement":
pass
elif choice1 == "Start Velocity":
pass
elif choice1 == "End Velocity":
pass
elif choice1 == "Acceleration":
pass
# This error message will show if the input did not match any item in the list
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
Hopefully the comments I have written in the code should explain my intentions, if not, feel free to ask anything.
The problem is that when I run the code, and input choice1, the for loop activates the last line of code:
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
and then prompts me to enter the input again, and will do this as many times as it needs to get to the item on the list that I am typing.
However, I specifically coded that if what I input does not match the item on the list the for loop is currently checking, but does match one of the other items on the list, then it should pass and loop round to checking the next item.
I am probably doing something stupid, but I don't see it, so please help me figure out what I have to do to get my desired result? I assumed it was the syntax I had wrong so that is why that is the title.
Thanks for any help, I appreciate it.
Besides the problem with the indentation in your pasted code, I would rewrite it as such:
while True:
choice = raw_input('...')
if choice in variables:
print "You chave chosen", choice
# Remove the chosen member from the list
variables = [v for v in variables if v != choice]
# Break out of loop
break
# Print error messages etc.
Also remember that string comparisons are case sensitive. I.e 'Displacement' != 'displacement'.

Categories

Resources