Understanding Global Names and Python2 and 3 - python

As a newbie to Python, I'm kind of learning some of the differences between Python2 and 3. In working through the Python course, it seems that there are some things that need to be changed in the code to make it work in 3. Here's the code;
def clinic():
print "In this space goes the greeting"
print "Choose left or right"
answer = raw_input("Type left or right and hit 'Enter'.")
if answer == "LEFT" or answer == "Left" or answer == "left":
print "Here is test answer if you chose Left."
elif answer == "RIGHT" or answer == "Right" or answer == "right":
print "Here is the test answer if you chose Right!"
else:
print "You didn't make a valid choice, please try again."
clinic()
clinic()
To make this work in Python 3, the print syntax needs to be changed (add parens), but another issue that comes up is the error "NameError: global name 'raw_input' is not defined". I've seen this issue come up often in my learning. It doesn't seem to come up when I run it in Python2, but in 3 it seems to need it declared as a global. However, when I add "global raw_input" to the function, it doesn't seem to work (in other cases, it worked everytime I did it.) Can someone tell me what I'm doing wrong? Also, I've heard that declaring globals is a bad habit to get into when not necessary, so what's the best way to handle them?

raw_input() has been renamed in Python 3, use input() instead (and the old Python 2 input() was removed). See PEP 3111.
See What's new in Python 3.0 for an exhaustive overview. There is also the Dive into Python 3 overview.

Amending Martijn's answer, here's a general trick you can do for these kind of small incompatibilities:
try:
input_func = raw_input
except NameError:
raw_input = input
Afterwards you can just use raw_input in your script with both Py2 and Py3. Similar things might be required for the unicode, and byte types.
Since you indicated you're interested in migration from >=Py2.7 to a Py3, you should know that Python 2.7 was mostly a Python 2.6 with lots of Py3 stuff backported.
So, while the print function technically still is a statement in Py2.7, and a function in Py3, the Py2.7 print does accept tuples. And that makes some of the Py3 syntax work in Py2.7. In short, you can just use parantheses:
print("Here is the test answer if you chose Right!")
To print an empty line, the best method working in both versions would be
print("")
To print without adding a newline by default I'm resorting back to write(), e.g.:
import sys
sys.stdout.write("no newline here")
sys.stdout.write(" -- line continued here, and ends now.\n")
On the other hand, for lots of Py3 stuff, you can actually enable the full Py3 syntax in Py2.7 by importing things from the future:
from __future__ import print_function
Then you don't need to switch between write() and print().
In real applications it all depends on if and how you have to interact with other people's code (packages, other developers in your team, code publishing requirements) and what's your roadmap for Python version changes.

Related

Random indentation errors? [duplicate]

This question already has answers here:
I'm getting an IndentationError. How do I fix it?
(6 answers)
Closed 4 years ago.
Here's my code:
def options():
selection=int(input("#>"))
if selection == 1:
#Connect
elif selection == 2:
#Modules
print("Modules")
elif selection == 3:
#Checking Internet
checkInternetConnection()
elif selection == 99:
#Exit
shutdown()
else:
print "Unknown Option Selected!"
sleep(100)
sys.clear()
start()
Every time I run i get this error:
File "main.py", line 41
elif selection == 2:
^
IndentationError: expected an indented block
I am probably being a noob here but please may someone help?! Thanks
There has to be a statement after your if block
Note: Comments don't count.
You can use pass statement instead.
eg.
if statement:
pass
While that indebted # Connect looks like a perfectly good if body to you, and to other human readers, to Python it‘s as if you had nothing there at all. And an empty if body is illegal.
There are two common ways to handle this, and you’ll want to get into the habit of doing one or the other without thinking, whenever you need to stick in a placeholder for code to be written later, or temporarily disable some code for debugging.
The first is to write this:
pass # TODO: Connect
The second is to write this:
"Connect"
The latter may look kind of weird (even if you’re used to docstrings), but it is a perfectly valid expression, and therefore a perfectly valid statement.
While you could just write pass # Connect, the problem with that is that pass and a comment is something you could reasonably have in your final code, so you have no way to tell whether this was a placeholder you meant to come back to before deploying anything.
By contrast, your linter/IDE/commit-hooks/CI/whatever can easily be configured to recognize either TODO comments, or expression statements that have no effect, and therefore warn you to double-check that this code really is ready to deploy.
Comments are not placeholders for if statements so use pass.
...
if selection == 1:
#Connect
pass
...
Where you have #connect, put some functional code under that if instead or with it. Its reading that the elif is ' under ' the if.

Python 2.7.13 - print command issue

I am absolutely new to python programming. i have written the below piece of code:
'''Lets us just learn python'''
print ("Hey God Help Me !!!")
name = raw_input("Enter Name:")
print name
While i run the code it asks for the input as intended however it doesn't print anything and looks like going in a infinite loop. i have used the same code in codeacademy system and it works. can someone help me understand what may be the issue?
i have tried using other functions and it works. Even tried manually entering the value in the code and that too works. However when ever i try to take a input from the user, this doesn't seem to work.
Well, after you changed your problem description to one, that I recommended initially:
print ("Hey God Help Me !!!")
name = raw_input("Enter Name:")
print name
then you need to assure you're using python 2.7 for 2 options of print statement -
print name and print(name) - to work.
Just in case you're using python 3x, please modify print name to print(name)
Hello fri3nd!
Welcome to party, I envy you! Not that I feel I've reached any plateau but that's the nature of the IT sector... You stay compliant to the current standard or your behind you... Anyhow firstly..
You say your on python 2.7? Youll quickly learn that firstly I assure you is that in 2.7 and 3.0+ you have different method of having to write your actual code... and the first ever code will have a printt lets take that for example...
Python 2.7
print 'HEY TH3R3'
Python3.0+
print('SEE THE DIFFERENCE?')
So when your running the code you provided... your mixing and matching which ... just cant be done,... So what your code would turnout to be properly
Python3.0+
name = input("gHey its... not god lol... whats your name? \n:")
greeting = "Oh! hi {}".format(name)
print(greeting)
I wont toch the 2.7 syntax but aside from the fact that we need to get you some quality tutorials lol... whats more important here is thatyou get the :logic of the language build... So much awesomeness awaits you. You ever need some help drop me a message but you have to put in that effort son lol.. but Ill give you a pass and place most of the blame oh bad source for the beging of the trip but yeah... google is your friend

Python 3.x multi line comment throws syntax error

I'm working on a Python project and as of now, my code has over 400+ lines. At one point, I had to write a multi-line comment about a small bug which needs a work around, and the interpreter decided to throw a syntax error.
According to the interpreter, the syntax error is occuring at elif.
I re-checked my indentation, converted tabs to spaces etc. Nothing seems to work.
if some_condition_1 == True:
do_something()
"""
Sub stage (b):
Refer documentation [1.7A] for ...
....
....
....
"""
elif condition_1 == True:
if condition_2 == False:
list.append(item)
However, if I remove the multi-line comment, the code executes fine.
Any idea what's going wrong? Please note that the code sample I've show above, is at very top of the file, and there's no chance for anything to go wrong elsewhere.
This is an indentation error. Your "multi-line comment" (really multi-line string) must be indented under the if block just like anything else.
""" These kinds of things """ are not really comments in Python. You're just creating a string and then throwing the value away (not storing it anywhere). Since Python doesn't have true multi-line comments, many people use them this way. However, since they are not true comments (they aren't ignored by the interpreter), they must obey all normal syntax rules, including indentation rules.
(Do note that when I say "creating a string" I'm speaking loosely. CPython, at least, has an optimization not to create an object here.)

Codecademy, Python code won't work

I have started programming in Python at Codecademy. So far I think that I've learn some basic programming skill and I'm really existed to try something more difficult.
On a project I've been working I keep getting this error
My code looks like this:
print "Welcome to the English to Pig Latin translator!"
original = raw_input("What's your name?")
def function():
if len(original) > 0:
print original
else:
print "empty"
The task is to see if the string is empty cause I will be using this piece of code later on.
When I press the 'Save & Submit Code' it prompts with my question and I type my answer in to the editor, and then nothing happens.
The message I get is: "The original variable ("Nicolai") had more than 0 characters but did not get printed."
Can anybody tell me what I'm doing wrong here?
It doesn't look like you're ever calling the function, only defining it. Try inserting:
function()
at the end. (also please name it more descriptively than "function")
Looking at the exercise, it doesn't want you to create a function. Simply remove the def function(): (and don't forget to un-indent your code!)
In fact, learning functions is after the PygLatin course :D

time.localtime() question beginner python

I'm having a syntax error on the second line of this code, I'm trying to make a counter with the winsound beep.
I think the problem is with the format() part, but i get a highlighted =, equals sign when i try to run the program. syntax error
def print_time(secs):
print('{0}:{1:02}'.format(secs//60,secs%60),end=' ')
print("left to wait...")
This is my second week programming, very basic understanding of comp sci or of languages.
This looks like a wonderful site to learn from.
If the part of the code I wrote looks fine, i can post the rest of it up as well to help find the problem.
It sounds like you're reading documentation for Python 3.x, but running Python 2.x. Try this instead:
def print_time(secs):
print '{0}:{1:02}'.format(secs//60,secs%60),
print "left to wait..."
Also, divmod().
def print_time(secs):
print '{0}:{1:02}'.format(secs//60,secs%60),
print "left to wait..."
The above code should work fine.
Python 3+ treats 'print' as a function and hence introduces end=' ' to suppress newline. But, in earlier versions of python it was done by appending ,(comma) to the print statement. See this link for what's new in Python 3+.
Apparently, your Python environment is 2.x and hence you are seeing the error.

Categories

Resources