I'm just following the basic's of python and have been using IDLE as I find it handy to experiment scripts in real-time.
While I can run this script with no issues as a file I just cannot include the last print statement in IDLE!. I have tried an indentation, 4 spaces, no indentation's. Please explain what I'm doing wrong.
while True:
print ('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('value')
SyntaxError: invalid syntax
You can type one statement at a time. The while loop considered one with the loop itself, and since the loop is a code block everything in it is okay.
The print at the end however is a new command. You have to run the while loop first and type the print after in the interpreter.
You can't paste more than one statement at a time into IDLE. The problem has nothing to do with indentation. The while loop constitutes one compound statement and the final print another.
The following also has issues when you try to paste at once into IDLE:
print('A')
print('B')
The fact that this has a problem shows even more clearly that the issue ins't one of indentation.
You have an undentation error in line 10, then you need just to add an espace
while True:
print ('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('value')
As others have kindly pointed out python IDLE only allows one block of code to be executed at a time. In this instance the while loop is a 'block'. The last print statement is outside this block thus it cannot be executed.
Related
I'm writing a script to start all of my services like Admin and Managed Server using Python. When i tried executing it says "SyntaxError: Invalid Syntax(try). Please find the code below
import time
sleep=time.sleep
configFile =
"/u02/weblogic/user_projects/domains/base_domain/userConfig.dat"
pwFile = "/u02/weblogic/user_projects/domains/base_domain/userKey.dat"
while True:
try:
connect(userConfigFile=configFile,
userKeyFile=pwFile,
url='t3://my.Adminserver.com:7001')
break
except:
sleep(60)
nmConnect(userConfigFile=configFile,
userKeyFile=pwFile,
domainName='base_domain')
nmStart('ManageServer1')
exit()
The try/except block should have 4 spaces. Functions, classes, if statements, while loops, for loops and try/except block all get 4 spaces.
try:
connect(userConfigFile=configFile,userKeyFile=pwFile,url='t3://localhost:7001')
break
except:
The rest of your code which you posted has a few other things perhaps I would change.I wouldn't set up a sleep variable like that I personally would just call time.sleep(). Also don't forget while loops gets 4 spaces of indentation and so try/except blocks. I'm also not sure about the last 5 lines of code if they are part of the except clause but if they are space them in 8 times (the reason is because we need to get past the while loop + put the code in the except clause so 8 spaces). I would edit your code snippet in your question with the correct indentation and perhaps comment out what it is suppose to do and such.
import time
configFile = "/u02/weblogic/user_projects/domains/base_domain/userConfig.dat"
pwFile = "/u02/weblogic/user_projects/domains/base_domain/userKey.dat"
while True:
try:
connect(userConfigFile=configFile,
userKeyFile=pwFile,
url='t3://my.Adminserver.com:7001')
break
except:
sleep(60)
nmConnect(userConfigFile=configFile,
userKeyFile=pwFile,
domainName='base_domain')
nmStart('ManageServer1')
exit()
A SyntaxError is at, or before, the ^ symbol. So the error is going to be before the try: itself -- maybe a missing parenthesis on a previous line, maybe try is not indented correctly -- we cannot tell because you have elided all the previous code, but that's where you should look.
Using the exec() python command, is it possible to run indented blocks of code (Like if/else statements or try/except). For example:
name = input("Enter name: ")
if name == "Bob":
print("Hi bob")
else:
print("Hi user")
At the moment I am using this to run the code:
code_list = []
while True:
code = input("Enter code or type end: ")
if code == "end":
break
else:
code_list.append(code)
for code_piece in code_list:
exec(code_piece)
Also I know that this isn't very "Pythonic" or "Good practise" to let the user input their own code but it will be useful in other parts of my code.
The problem here isn't the indentation. The problem is that you're trying to exec the lines of a compound statement one by one. Python can't make sense of a compound statement without the whole thing.
exec the whole input as a single unit:
exec('\n'.join(code_list))
From exec() documentation:
This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed ...
Thus, you can do things like
exec("a=2\nb=3")
exec("if a==2:\n\tprint(a)\nelse:\tprint(b)")
You just need to follow the right syntax and indentation.
Another way of formatting code within an exec() function is to use triple quotes, which makes it easy to see what the code looks like.
code = """ # Opening quotes
for i in range(0, 10): # Code line 1
print(i) # Code line 2
""" # Closing quotes
exec(code)
This would maybe not work if you're asking the user to input the code, but it's a trick that may come in handy.
So I know how to print one character at a time and the basic code I have for that is:
import time
import sys
def delay_print(s):
for c in s:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.2)
delay_print("hello world")
But I'm making a game and I'm using delay_print for all of my code and need a way to run it within user inputs without getting this result (there is no error but I don't really want a random "None" there).
GetUp=input (delay_print("\nGET UP? Y/N: "))
And when run it displays:
GET UP? Y/N: NoneN
Which isn't exactly what I want.
So what I need is for someone to tell me how to use delay_print without the "None" appearing. Other than that it runs correctly.
Just brake it into two lines and leave input() without a prompt:
delay_print("\nGET UP? Y/N: ")
GetUp = input()
That way, your print will behave the way you want it and the input will read the user input unobstructed.
Do not complicate your life when you don't have to ;)
If you insist on doing it in a single line you have to modify the definition of delay_print by adding a return '' statement. That way, instead of the default None it will return and empty string instead.
Note however, that GetUp=input(delay_print("\nGET UP? Y/N: ")) is not a very clean coding style. In my opinion that is.
You can return "" from delay_print, so input(delay_print("whatever")) will print slowly, then print an empty input prompt at the end of the line, which seems to be what you want.
The current behavior happens because delay_print returns None, and that is printed by input as a prompt.
See built-in function input:
If the prompt argument is present, it is written to standard output without a trailing newline.
You gave an argument (delay_print("\nGET UP? Y/N: ")) to it (as prompt). So, the interpreter first evaluates the argument. At this time, the program does the write, flush and sleep. Then it returns None (implied when running to the end of a function). That was then provided as the prompt of input().
Your code works like this one:
temp = delay_print("\nGET UP? Y/N: ")
# assert temp is None
GetUp = input(temp)
# Same as input(None)
So, that is the mistake.
The correct should be:
delay_print("\nGET UP? Y/N: ")
GetUp = input()
The None appeared because delay_print was returning no values.
import time
import sys
def delay_print(s):
for c in s:
if c:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.50)
return ''
#delay_print("hello world")
GetUp=input(delay_print("\nGET UP? Y/N: "))
I'm currently in the process of trying to add a while loop to my code that is shown below. The theory behind what I'm attempting to do is as follows:
As you can see at the very bottom of my code, I confirm the user's reservation and ask if he/she would like to create another. If the user enters 'yes", I would like the program to re-run. If no, then the program should terminate. I'm aware the best way to accomplish this is using a while loop, but I'm having a little difficulty executing this as my textbook is a little confusing on the subject.
I know it's supposed to look something like this (or something along the lines of it):
while True:
expression
break
Though I can't seem to get it to compile. Any suggestions? Below is my code:
user_continue = str(raw_input("Your reservation was submitted successfully. Would you like to do another?"))
if user_continue != 'yes':
print('Thank you for flying with Ramirez Airlines!')
Here's a simple example that shows how to use a while loop:
import time
while True:
print time.ctime()
print 'Doing stuff...'
response = raw_input('Would you like to do another? ')
if response != 'yes':
break
print 'Terminating'
Note that the code inside the while loop must be indented, unlike the code in your first code block. Indentation is very important in Python. Please always ensure that code in your questions (and answers) here is properly indented.
FWIW, the raw_input() input function returns a string, so str(raw_input()) is unnecessary clutter.
The end of your code should look something like:
user_continue = raw_input("Your reservation was submitted successfully. Would you like to do another?")
if user_continue != 'yes':
break
print('Thank you for flying with Ramirez Airlines!')
...
Your print statements are a bit funny. Since you're using Python 2.7 you don't need to do
print ('The total amount for your seats is: $'),user_people * 5180
you can just do
print 'The total amount for your seats is: $', user_people * 5180
or if you wish to use Python 3 style, put everything you're printing inside the parentheses, like this:
print ('The total amount for your seats is: $', user_people * 5180)
However, the output will look a bit messy since there will be a space between the $ and the amount. Please read the python docs to learn how to fix that.
...
Also, you have import time inside your loop. Don't do that. Generally, import statements should be at the top of your script before any other executable code.
Version: Python 3.3.2 (default, Sep 11 2013, 20:16:42)
Hey,
I'm doing some tests with python, fiddling a bit with the shell, but I get a strange error.
>>> a = 5
>>> if a > 0:
... print("a is a positive number.")
... if a < 0:
File "<stdin>", line 3
if a < 0:
^
SyntaxError: invalid syntax
I don't know why this error appears. I know I can use elif or else, but I just want to test.
Help?
This is valid Python syntax when it is located in a module, but in the interactive interpreter you need to separate blocks of code with a blank line.
The handy rule of thumb here is that you can't start a new block with if, def, class, for, while, with, or try unless you have the >>> prompt.
Are you pressing backspace to enter the second if? The shell doesn't like that. It's expecting another line in the logic block, or to be able to execute the block (by pressing enter one more time). The shell can only execute one block at a time, i.e. finish the first if first, then you can enter the second if. You can use elif because it's still considered part of the same logic block.
The REPL is still working on the previous code block. Enter an empty line on its own to terminate it first.
You need a blank line after your print statement, the Python interpreter thinks you're continuing a block until you do that, so you get an indentation error on your second if statement. This is not "invalid", the interactive interpreter is designed to work that way.