Suggestions on improving my code. - python

Hello I am a fairly novice programmer. And I have a simple code
name=raw_input("Hello I am Bob. What is your name?")
print("It is very nice to meet you,", name)
response=raw_input("what do you want to do today?")
if response == "price match":
However on the fourth line I get SyntaxError: unexpected EOF while parsing error and I did look into it and I found that using the raw_input for inputted strings is much better than using the input function.I don't know why the error keeps popping up. Could I get some help and perhaps some suggestions as to how I can improve the code.

You have to do something in the if statement. For example, print a price:
if response == "price match":
print "Yes, we can do that for you".
But, you can't just leave a block (the stuff that is indented after a :) empty, or Python will give you an error.
In rare cases (and not in your case here), you may want to do absolutely nothing, but still have a block (e.g. if required to by an except:). In that case, you still have to put something in the block, but you can use the word pass which does nothing. (This is almost never used in an if block).

I'm no Python expert.. But it looks like your problem is here:
response=raw_input("what do you want to do today?") if response == "price match":
You are defining an if statement, but if this value is true, how do you handle it?
I'm guessing you would need something like:
if response == "price match":
print('Match')
else:
print('Did not match')
Hope this helps a little

If you need a placeholder for just having valid syntax before putting in the body of your if/else/functions/etc, use pass.
http://docs.python.org/release/2.5.2/ref/pass.html
As for your code, a valid if statement must always have a body. So put some code there or use pass.

Related

Is it ok to use multi split function in one line?

I want to get the follow list:
['value1', 'value2', 'value3']
from the next string:
some_option=value1,value2,value3
Is it ugly to use the following code to get this?
some_string = 'some_option=value1,value2,value3'
print(some_string.split('=')[1].split(','))
I don't agree with the "ugly" statement, as that seems perfectly Pythonic to me, and efficient enough for the job at least. IMHO the question of how the code appears doesn't matter as much as whether it's easily understandable to others what the code is doing, and more importantly whether it actually gets the task accomplished - which it certainly does.
A slight change for optimization I would propose is to pass the number of splits to str.split, and then you can safely access the last result rather than the 2nd element:
some_string = 'some_option=value1,value2,value3'
print(some_string.split('=', 1)[-1].split(','))
"Ugly" is a matter of opinion, and can not be answered on stackoverflow.
The real issue with your code however, is that it has no error checking, so if the input string does not contain an = character, you will be indexing a non-existent list member.
If this code is designed for production application and not some personal tool, you should do something like this:
some_string = 'some_option=value1,value2,value3'
try:
print(some_string.split('=')[1].split(','))
except IndexError:
print('Invalid input')
Or, if you just want to skip the bad strings you can put pass in the except clause.
Without knowing more context, it looks fine to me. If you feel bad about the ugliness, one way to improve might be to put that inside a function, such as
def scrape_values(row):
return row.split('=')[1].split(',')
some_string = 'some_option=value1,value2,value3'
print(scrape_values(some_string))
If you give the function a meaningful name, then we can "abstract away" the ugliness

"Expected an indented block" What to do?

I'm new to programming and don't know what this means. Please tell me what to do to my code for my assessment. It doesn't highlight the problem when I run it and I don't know what to do. Please help me.
To be honest, reading a Python tutorial would probably do you better. In any case, however...
Python is an indentation-based language. This means anytime you enter a new "block" (code that belongs to a statement), you need to indent your code by one level. Here are two examples, one incorrect and one correct:
if 5 < 10:
print "5 is less than 10! Wow! Thanks, math!"
print "I'm so glad Python told me."
This is a syntax error, since the print statement belongs to the if statement, and is therefore a new block. It should be indented, but in this case it wasn't, so it's an error.
if 5 < 10:
print "5 is less than 10! Wow! Thanks, math!"
print "I'm so glad Python told me."
print "This is printed in any case, since it doesn't belong to the above block."
Here is the fixed verion. Notice the four spaces in the beginning of the second line? That's called "indentation". Any subsequent lines indented to the same level will be part of the block. Generally, you press TAB to indent in your text editor. The last line, however, is not indented and will therefore run regardless of whether the if statement evaluates to True or not.

'None' appears out of nowhere in my code

print("text")
print("text")
name=str(input("text"))
name=name.capitalize()
tutorial=str(input(print(name,"do you know the rules? (YES/NO)",sep=", ")))
tutorial=tutorial.upper()
I can't find the error in my code. Everytime I run it a "None" keeps coming out of nowhere. (replaced some parts of the code so it can be read more easily)
Name? >>>HAL 9000
Hal 9000, do you know the rules? (YES/NO)
None #This I want to erase
Your problem is in this line:
tutorial=str(input(print(name,"do you know the rules? (YES/NO)",sep=", ")))
You are getting that None because you have an unnecessary print inside your input. Your input is using the return of that print, which does not return anything, so by default is None. You are still seeing what is inside print because of the obvious functionality of print to output what you are sending inside the print method.
View this example that replicates your problem:
>>> input(print('bob'))
bob
None
''
>>>
To fix this problem, remove that print. Also, change the string in your input to use string format:
tutorial=str(input("{} do you know the rules? (YES/NO)".format(name)))
print doesn't return a value, so it's treated as returning None. Which means that you're effectively calling input(None) which prints out "None" before prompting you for input.

TypeError: 'str' object is not callable

I'm very new to Python and I was wondering if anyone could help me with this code I wrote:
print("What is your name:")
name = raw_input()
print "hi", name, "How are you:"
Feeling = raw_input()
if Feeling ("good"):
print ("Good")
Else
print ("Thats a shame")
It just comes up with error this when I run it:
TypeError: 'str' object is not callable
I have looked online but I couldn't find anything that would help because the answers were to complex.
Could someone please help me.
You are trying to use the string stored in Feeling as a function.
if Feeling ("good"):
With nothing but spaces between Feeling and the parenthesis around "good", Python sees that as a function call.
You probably wanted to test if it was equal to "good" instead:
if Feeling == "good":
print "Good"
In this line:
if Feeling ("good"):
You're trying to call Feeling as a function, with "good" as an argument. That's what parentheses mean in this syntax.
If you want to check whether Feeling is equal to "good", you use the == operator:
if Feeling == "good":
Meanwhile, as soon as you fix that, you're going to have another problem with the next line:
Else
In Python, capitalization counts; else has to be spelled in all lowercase. Also, block statements (like if and else) always need colons. And the statements inside a block statement have to be indented. So, you want this:
else:
print("Thats a shame")
You may want to find a smarter editor that helps you with some of this stuff, instead of using Notepad/TextEdit/etc. Any decent programmer's editor—including free ones like SciTE or emacs—will try to put the cursor at the right place for indentation, highlight when you've made a syntax error, and so on.
The problem is this line:
if Feeling ("good"):
Feeling is a string, the result of raw_input(). Feeling("good") looks like you want to call it as if it were a function. That's not possible, so it says "str object is not callable".
You probably meant
if Feeling == "good":
You're also missing a : after the else, you shouldn't capitalize else, and the line after should be indented.

Python unexpected indentaton error main()

I have no idea how to fix this. I've tried retyping the program.
I get an unexpected indentation error for the last main function.
resident = 81
nonresident = 162
def main():
# initialize counters and total tuition
resident_counter = 0
nonresident_counter = 0
total_tuition = 0
print("Name \tCode\tCredits\tTuition")
print
try:
# open the data file
infile = open('enroll.txt', 'r')
# read the first value from the file
student_name = infile.readline()
# continue reading from file until the end
while student_name != '':
# strip the new line character and print the student's name
student_name = student_name.rstrip('\n')
print(student_name, end='\t')
# read the code type, strip the new line, and print it
code = infile.readline()
code = code_type.rstrip('\n')
print(code_type, end='\t')
# read the number of credits, strip the new line, and print it
credits = infile.readline()
credits = int(credits)
print(format(credits, '3.0f'), end='\t')
# check the room type and compute the rental amount due
# increment the appropriate counter
if code_type == "R" or room_type == "r":
payment_due = credits * resident
resident_counter += 1
elif code_type == "N" or room_type == "n":
payment_due = credits * nonresident
nonresident_counter += 1
elif code_type != "R" or code_type != "r" or code_type != "N" or code_type != "n":
payment_due = 0
# accumulate the total room rent
tuition += payment_due
# print the appropriate detail line
if payment_due == 0:
print('invalid code')
else:
print('$', format(tuition, '8,.2f'))
# get the next studen't name
student_name = infile.readline()
# close the input file
infile.close()
# print the counters and payment total amount
print
print('total number of resident students: ', resident_counter)
print('total number of nonresident: ', nonresident_counter)
print
print('total students: ', end='')
print('$', format(tuition, ',.2f'))
# execute the main function
main()
You don't have an except clause to match the try.
Despite what everyone else is saying, if you have a try, you don't have to have an except: you must have an except or a finally.
That may seem nitpicky, but it's pretty plausible that the code you were copying was actually using finally (e.g., to make sure some cleanup code always gets run—given that it's doing C-/Java-style manual cleanup).
At any rate, adding an except clause is not the right answer. If you're actually looking to handle or ignore errors, then yes, add an except clause. If you're looking for somewhere to add cleanup code that gets run even on an error, add a finally clause instead. If you don't want either, just remove the try line.
you are mixing room type and code type in your if else statement. You are also missing your except statement. This should be your last two lines before calling main.
It should read:
except IOError:
print('an error occurred trying to open or read enroll.txt')
You are using the try statement. It means that you MUST have an except block
try:
some code
except:
pass
It is simplification, but will solve your problem.
The other answers have (correctly) pointed out that you need to have an except to go with your try: (or not use a try altogether). I'm going to try to explain how you could go about debugging similar issues in the future, since these can be very annoying to debug.
Your error message most likely looked something like this:
File "test.py", line 74
main()
^
IndentationError: unexpected unindent
At first glance, that doesn't seem too helpful, and it's definitely not very clear.
The fact that you "tried retyping the program" sounds like you saw IndentationError and thought, "this means my indents are messed up; maybe there's an extra space somewhere or a mixture of spaces and tabs or something." Those are definitely valid IndentationErrors, and retyping the program would fix them, if you didn't make the same typing error again. (On a side note, I believe that any text editor worth using will have the option to convert all of your tabs to 4 spaces to avoid a lot of indent headaches.)
However, looking at the error text, we see "unexpected unindent". To me this sounds kind of like gibberish, but what it means is that, when python was looking at your program, it ran into a line that it thought should be indented more than it was. (Unfortunately, this same kind of error can be called "unexpected unindent" or "expected an indented block", and it can even show up as a plain old SyntaxError: invalid syntax.)
So knowing what the error message means, we can look back through the code to see why python thought that main() was indented strangely- though we have to be careful because python isn't always right about where the problem actually is. Here would be something like my thought process:
There's a function definition right before main() is called, maybe that function wants main() to be inside it? No that isn't it, because python only really expects at least one line of code after a function definition.
What else "wants" code to be indented after it? if, elif, and while all do, but all of them have code after them as well.
The only other "indenter" is try:. At this point, you either know that try: needs to be followed by a except: or a finally: and you fix it, or you don't. If you don't know that, than you could still see that try: is followed by an indented block, and, given that it is a likely culprit for you error, decide that it's time to look up what try: does.
Well I hope that helps troubleshooting problems like this in the future, and check out abarnert's answer and my link for more on handling errors with try/except/else/finally statements.
As noted by LevLevitsky and david above, there's no except clause. The easiest way to solve this is adding a line like the following to your code before the call to main:
except: pass
The second comment I have to your code is more stylistic, but you could add the following, before your call to main and after the except clause:
if __name__ == '__main__':
main()
Besides the missing except or finally or the extra try... If you have a look at the edited code, you can see the strangely mixed color blocks in the indentation. It means that you are mixing tabs and spaces which can lead to problems like bad indentation. The reason is that the interpreter thinks differently about how the tabs should be interpreted (for example 8 vs. 4 column tab stops).
You must not mix tabs and spaces for the indentation. I personally would recommend to use only the spaces. Any decent editor is capable to expand TAB key to spaces and/or Untabify the existing mixture of tabs and spaces.

Categories