What's wrong with this Python code?
I am very new, so just learn, so please, please!
start = int(input('How much did you start with?:' ))
if start < 0:
print("That impossible! Try again.")
print(start = int(input('How much did you start with:' )))
if start >= 0:
print(inorout = raw_input('Cool! Now have you put money in or taken it out?: '))
if inorout == in:
print(in = int(raw_input('Well done! How much did you put in?:')))
print(int(start + in))
Does this always result in a syntax error? I'm sure I am doing something obvious wrong!
Thanks!
-1
a source to share
3 answers
- You cannot assign variables in expressions in Python, like in C: print (start = int (input ('blah'))) is wrong. First complete the assignment on a separate statement.
- The first line should not be indented, but it might just be a copy and paste error.
- Word
in
is a reserved word, so you cannot use it for variable names
+7
a source to share
- Consider prompting for input using a function that wraps a loop.
- Don't use input for generic user input, use raw_input instead
- Wrap your script execution in a main function so it doesn't execute on import
def ask_positive_integer(prompt, warning="Enter a positive integer, please!"):
while True:
response = raw_input(prompt)
try:
response = int(response)
if response < 0:
print(warning)
else:
return response
except ValueError:
print(warning)
def ask_in_or_out(prompt, warning="In or out, please!"):
'''
returns True if 'in' False if 'out'
'''
while True:
response = raw_input(prompt)
if response.lower() in ('i', 'in'): return True
if response.lower() in ('o', 'ou', 'out'): return False
print warning
def main():
start = ask_positive_integer('How much did you start with?: ')
in_ = ask_in_or_out('Cool! Now have you put money in or taken it out?: ')
if in_:
in_amount = ask_positive_integer('Well done! How much did you put in?: ')
print(start + in_amount)
else:
out_amount = ask_positive_integer('Well done! How much did you take out?: ')
print(start - out_amount)
if __name__ == '__main__':
main()
0
a source to share