Python syntax error with If/Else statement [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
hey I need help with a stupid syntax error using the if and else statement.
GNU nano 2.2.6
#!/usr/bin/python
print 'ACTIVATED'
import RPi.GPIO as GPIO ## Import GPIO library
GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
GPIO.setup(40, GPIO.IN) ## Setup GPIO Pin 40 to OUT
GPIO.input(40) ## Turn on GPIO pin 40
for x in xrange(10):
if: GPIO.input(40)
print ('CHEESE')
else:
GPIO.cleanup()
heres the error:
File "./gid.py", line 12
if: GPIO.input(40)
^

Your if needs to have a conditional
if: GPIO.input(40) # wrong placing of semicolon with missing conditional
it has to be
if GPIO.input(40): # correct usage
as GPIO.input(40) returns a boolean
(Apart from that your print indent has mismatched)

Perhaps you mean if GPIO.input(40):. The colon goes after the entire if condition.

There are two things wrong:
if: GPIO.input(40) should be if GPIO.input(40):
You need to define something to happen inside the if statement. For example:
if GPIO.input(40):
print('CHEESE')

Related

(Python) Why is my while loop not working? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 months ago.
Improve this question
I have been working on an operating system inside of Python and I am starting off with the system booting code. I have a while loop that executes when the variable "Booting" = 1. Inside the while loop is a script that prints "Booting" then replaces that with "Booting.", then it gets replaced with "Booting.." and so on until it reaches "Booting....." which should make it reset to "Booting" and reset the cycle. Instead, it just stops at "Booting....." and doesn't continue to reset the cycle.
Here is the code:
import time
import sys
Booting = 1
while Booting == 1:
print("Booting")
sys.stdout.write("\033[F")
time.sleep(0.2)
print("Booting.")
sys.stdout.write("\033[F")
time.sleep(0.2)
print("Booting..")
sys.stdout.write("\033[F")
time.sleep(0.2)
print("Booting...")
sys.stdout.write("\033[F")
time.sleep(0.2)
print("Booting....")
sys.stdout.write("\033[F")
time.sleep(0.2)
print("Booting.....")
sys.stdout.write("\033[F")
time.sleep(0.2)
it does not erase the rest of the line, so you need to replace any existing variables you want to overwrite with spaces
try
...
print("booting ")
...
print("booting. ")
...
etc
(there are many ways to clear the line this is just one (#code provides another good alternative in the comments)

Uncaught Error: NameError: name 'true' is not defined [duplicate]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
The community reviewed whether to reopen this question 2 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I want to use Boolean ( true / false ) in my python source file, but after running the application, I receive the following error:
NameError: name 'true' is not defined
The error lies on while true:, when I am trying to make the Raspberry Pi run a HTML script when it receives input on port 17:
import RPi.GPIO as GPIO
import time
import os
inputSignal = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(inputSignal,GPIO.IN)
while true:
if (GPIO.input(inputSignal)):
os.system("html /home/pi/index.html")
else:
print("No Input")
Python’s boolean constants are capitalized: True and False with upper case T and F respectively.
The lower-case variants are just valid free names for variables, so you could use them for whatever you want, e.g. true = False (not recommended ;P).
You haven't defined a variable true. Maybe you meant the built-in boolean value True?
while True:
# but seems like inifite loop

Beginner python3 question about elif statement syntax and the use of print_function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Trying to build a simple script for returning disk, cpu usage and network connectivity checks. I keep getting errors in my elif statement syntax. I've tried revising this for 3 days and finally am not getting errors in the str format line 36 but now i get an invalid syntax error on line 37 (line containing only "else:". I read that in earlier python versions you had to import print_function, which is why it is listed, though I believe you shouldn't need to do this in Python3. Any suggestions or insight into why this error is occurring would be very much appreciated.
#!/usr/bin/env python3
import shutil
import psutil
import print_function
from network import *
def dsk_free(disk):
df = shutil.disk_usage(disk)
fre = df.free / df.total * 100
dsk_out = 'Disk usage = {}%'.format(fre)
return (dsk_out)
def cpu_ok():
cpuse = psutil.cpu_percent(1)
cpu_out = 'Cpu usage = {}%'.format(cpuse)
return (cpu_out)
def check_disk_usage(disk):
du = shutil.disk_usage(disk)
free = du.free / du.total * 100
return free > 20
def check_cpu_usage():
usage = psutil.cpu_percent(1)
return usage < 75
x = dsk_free
y = cpu_ok
if not check_disk_usage("/") or not check_cpu_usage():
print("ERROR! Shut down immediately!")
elif check_connectivity() and check_localhost():
print("Everything is awesome! Disk Usage is {}% and Cpu usage is {}%".format(dsk_free(),cpu_ok())
else:
print("Network connection failure!")
if not check_disk_usage("/") or not check_cpu_usage():
print("ERROR! Shut down immediately!")
elif check_connectivity() and check_localhost():
print("Everything is awesome! Disk Usage is {}% and Cpu usage is {}%".format(dsk_free(),cpu_ok())
else:
print("Network connection failure!")
in your second elif statement, where you have your print statement, you are missing the finishing ), add one more ) at the end and you should be good to go

class and functions in python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm new to Python and I'm trying classes and objects, I have this script:
#!/usr/bin/env python
class test:
def __init__(self, username):
self.username = username
def name_again(self):
for i in range(0-4):
print ("username is %s" %self.username)
ahmed = test('ahmbor')
ahmed.name_again()
I'm expecting this script to print "username is ahmbor" 5 times
When I run this script, I have nothing
Please help find what's wrong with this
You are telling range() to loop over 0-4 (subtract four from zero), which is -4. Because the default is to start at 0 and count up, that is an empty range:
>>> range(0-4)
range(0, -4)
>>> len(range(0-4))
0
Use a comma instead, and use 5 to loop 5 times, not 4. The endpoint is not included:
>>> len(range(0, 4))
4
>>> len(range(0, 5))
5

Invalid syntax on if else statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm writing a simple text-based game and I've run into an error here.
def lamp():
print "You pick up the lamp and examine it."
print "It looks like an ordinary gas lamp."
print "What do you do?"
lamp_action = raw_input("> ")
if "rub" in lamp_action:
rub()
elif "break" or "smash" in lamp_action:
print "The lamp shatters into pieces."
dead("The room disappears and you are lost in the void.")
else:
lamp()
If I comment out the elif part, Python gives an invalid syntax error on else. If I leave the elif part in, the program will run without an error, but even typing something random like "aaaaaa" will follow the elif action.
I also doesn't work if I replace the else section with something like this:
else:
print "That's not a good idea."
lamp()
or like this:
else:
dead("That's not a good idea.")
Where dead is:
def dead(why):
print "%s Game over." % why
exit(0)
What did I miss?
"break" or "smash" in lamp_action is interpreted by Python as testing "break", then testing "smash" in lamp_action. Since "break" is a nonempty string, it is always interpreted as "true", so the elif is always taken.
The correct form is
elif lamp_action in ('break', 'smash'):
i.e. testing if the action is in a list of possibilities.

Categories