'SyntaxError: invalid syntax' in python 3 IDLE - python-3.x

Why is this a syntax error? And how do I fix it?
class Queue:
#Queue is basicliy a List:
def __init__(self):
self.queue = []
#add to the top of the list (the left side)
def Enqueue(self, num):
if isinstance(num, int):
self.queue.append(num)
#remove from the top of the list and return it to user
def Dequeue(self):
return self.queue.pop(0)
#this function gets inputs from user, and adds them to queue,
#until it gets 0.
def addToQueue(queue, num):
num = input()
while num != 0:
queue.Enqueue(num)
num = input()

The interactive mode (with the >>> prompt) only accepts one statement at a time. You've entered two to be processed at once.
After you've entered the class definition, be sure to add an extra blank line so that the interactive prompt knows you're done. Once you're prompted with a >>>, you'll know it is ready for the function definition.
The rest of your code looks fine. Happy computing :-)

Related

Is there a way in Python to simulate keyboard input to a function that asks for input?

I have a function in my code that asks the user for input:
def function_1():
...
x = input('Please provide input')
...
return something
I want to be able to run my code, and when the program eventually reaches function_1 and asks the user for input, automatically provide it with some specified input. When unittesting, I can use the mock library to simulate keyboard input as below
#mock.patch('builtins.input', side_effects=[1,2,3])
function_1()
function_1()
function_1()
This calls the function three times and provides the inputs {1, 2, 3}. I'm wondering if there is a way to do the same thing outside of unittesting.
I'm aware that I can rewrite the code, or use pipe in terminal. But I'm more curious about whether this can be solved in the manner described above.
One way is to overwrite sys.stdin:
import sys
from io import StringIO
oldstdin = sys.stdin
sys.stdin = StringIO("1\n2\n3\n")
assert input() == "1"
assert input() == "2"
assert input() == "3"
sys.stdin = oldstdin
The great thing about Python is that you can override just about any function, even built-ins.
def override():
from itertools import count
counter = count()
return lambda *args, **kwargs: next(counter)
input = override()
def x():
return input("Testing123")
print(x()) # 1
print(x()) # 2
print(x()) # 3
Though, this has to be done before your functions are called.

How to make x variable change each time and read its value from txt file

I am working on my undergraduate project and this is my first time using Python to control a parrot bebop 2 drone. I have a variable x(an int) and I want to read its value from a file. In the mean time I want the program to read this file continuously; what I mean is that my text file input will be changed each time and I want the Python code to catch this change and change the value x.
For example:
if x is assigned 1 from the text file --> then the drone takes off.
in the mean time after x is assigned the value 1, I want it to be assigned 2 automatically and do the second command, for example: move to the left (but without disconnecting the drone "the first command")
here is my code, but I had a lot of problems with it, it checks the value, but no commands work after it knows the value of x:
bebop = Bebop()
print("connecting")
success = bebop.connect(10)
print(success)
f = open('EEGresults.txt')
lines = f.readlines()
list_of_elements = []
for line in lines:
list_of_elements += map(int, line.split())
f.close()
print (list_of_elements)
x = list_of_elements[1]
bebop.smart_sleep(5)
if x == 1:
print ("Yay! This number is = 1")
bebop.safe_takeoff(3)
else:
if x == 2:
print ("Yay! This number is = 2")
bebop.move_relative(0,0,0,1.6)
I expect that the code will read the value of x from text file directly and continuously and at the same time it will run the commands depending what the value of x that it receives.
I donĀ“t know how to use Bebop but I whould use something like this...
First I would create an object to store the data from your file. So you need something like an onValueChanged callback. You have to define this object on your own:
class NotifierVariable():
def __init__(self):
self.__value = 0
self.__Listener = list()
#NotifierVariable.setter
def set(self, value):
if(value != self.__value):
self.__value = value
for callback in self.__Listener:
callback(self.__value)
#property
def get(self):
return self.__value
def addListener(self, callback):
self.__Listener.append(callback)
You can use it in the following way:
class NotifierVariable():
def __init__(self):
self.__value = 0
self.__Listener = list()
def set(self, value):
if(value != self.__value):
self.__value = value
for callback in self.__Listener:
callback(self.__value)
def get(self):
return self.__value
def addListener(self, callback):
self.__Listener.append(callback)
def Func(value):
print(value)
if __name__ == '__main__':
x = NotifierVariable()
x.addListener(Func)
x.set(10)
Now you have to read the file periodicly:
while(True):
with open('EEGresults.txt') as File:
lines = File.readlines()
list_of_elements = []
for line in lines:
list_of_elements += map(int, line.split())
print (list_of_elements)
x.set(list_of_elements[1])
time.sleep(10)
You use the callback to send the command to your drone. The file is periodicly read out every 10 seconds (you can change it) and update your x variable. A callback is triggered if the value got changed and then you can send a command, based on the input, to your drone.

Defining a main_menu function to be called from other methods within a class in Python

I have a class with several methods to assign attributes from user input, and three methods that will add, delete, or update a nested dictionary with the input.
I would like to add a main_menu function so that the user can access the add, delete, and update methods and then choose to either continue adding/deleting/updating the dictionary, or go back to the main menu.
When I tried to make a main_menu function, I receive NameError: name 'command' is not defined. The program will loop through as expected if the main_menu is not a function, but once I tried to turn it into a function, I get the error. I've tried different levels of indentation, but I'm new to Python and don't know what else to try.
class MyClass:
def __init__(self):
self.x = 0
self.y = 0
self.z = 0
def get_x(self):
#code to get x from user input
def get_y(self):
#code to get y from user
def get_z(self):
#code to get z from user
def add_info(self):
store_info = {}
id = 0
while command = '1':
new_info = {}
new_id = len(store_info) + 1
store_info[new_id] = new_info
x = h.get_x()
new_info['x'] = x
y = h.get_y()
new_info['y'] = y
z = h.get_z()
new_info['z'] = z
print('Your info has been updated.\n', store_info)
choice = input('To add more info, type 1. To return to the main menu, type 2')
if choice == '1':
continue
elif choice == '2':
main_menu()
else:
print('The End')
break
def delete_info(self):
#code to delete, with an option at the end to return to main_menu
def update_info(self):
#code to update, with option for main_menu
def main_menu():
main_menu_option = """Type 1 to add.
Type 2 to delete.
Type 3 to update.
Type any other key to quit.\n"""
h = MyClass()
command = input(main_menu_option)
if command == '1':
h.add_info()
elif command == '2':
h.delete_info()
elif command == '3':
h.update_info()
else:
print('Good bye.')
main_menu()
When I run the program, I get the main menu and type 1, but then receive the NameError for command.
Before I tried to make the main_menu a function, I could access the add method to add info to the nested dictionary.
In Python methods/functions only have access to variable in their scope or parent scopes. For example:
command = 1 # A
def foo():
print(command)
def bar():
command = 2 # B
print(command)
foo()
bar()
print(command)
prints out 1 and then 2 and then 1. This works because when we call foo, python looks at the local variables and realises there is no command variable there so it looks at the scope above and sees the command variable at label A. Then when we call bar() we add a variable called command (label B) to the local variables of bar and then print that, notice that python doesn't look at the global variables here so it prints 2 without changing the initial command variable (label A) as we can see when we finally print(command) at the end of the script.
It is because of this that your program is failing, your add_info method is trying to access a variable called command however none exists in its local variable or its global scope. The fix for this would be to add command to the add_info local variables by passing it as an argument to the method from main_menu.
# in main_menu
if command == '1':
h.add_info(command)
# in add_info
def add_info(self, command):
...

TypeError: object() takes no parameters 3

I'm a beginner and while trying for a program error: TypeError: object() takes no parameters is frequently occurring.
next_output = True
def start() :
class Gate(object):
""" class representing a gate. It can be any gate. """
def __init__(bit, *args):
""" initialise the class """
bit.input = args
bit.output = None
def logic(bit):
""" the intelligence to be performed """
raise NotImplementedError
def output(bit):
""" the output of the gate """
bit.logic()
return bit.output
a = int(input("Enter the first input: "))
b = int(input("Enter the second input: "))
class AndGate(Gate):
""" class representing AND gate """
def logic(bit):
bit.output = bit.input[0] and bit.input[0]
return bit.output
class NotGate(Gate):
""" class representing NOT gate """
def logic(bit):
bit.output = not bit.input[0]
return bit.output
class NandGate(AndGate,NotGate):
def logic(bit):
bit.flag = AndGate.logic(bit)
Gate.__init__(bit,bit.flag)
bit.output = NotGate.logic(bit)
return bit.output
n = NandGate(a,b).logic()
print(int(n))
while next_output :
start()
while running error occurs in line
n = NandGate(a,b).logic()
It's a strong convention to have the first parameter in member functions be called self, as that one refers to the object it's being called on, and not some other object. That is,
def logic(self):
clarifies that it's working on itSELF.
A NandGate should probably HaveA, rather than IsA And/NotGate.
class NandGate(Gate):
def logic(self):
anded = AndGate(self.input).logic() # calculate the and'd values
notted = NotGate(anded).logic() # not them
return notted
Not only is this clearer than having an object be both, it's tidier reuse of code and less hoops to jump through with specific __init__s being called.
Based on what you've shown, it's not entirely necessary for a gate to have a .output field. It could just calculate the result from its .logic() and return that, storing only its input.
def output(bit):
""" the output of the gate """
return bit.logic()
The AndGate's logic is busted--it checks the [0] twice. It should check self.input[0] and self.input[1].
It's hard to tell if the tabbing just got butchered by Stack Overflow or not, but it's unclear where Gates's init, logic, and output functions got placed.
It's definitely bad form to put active logic in between definitions:
class Gate():
def __init__():
# definitions
class NotGate(Gate):
# more definitions
# functional flow of program
a = int(input("Enter the first input: "))
b = int(input("Enter the second input: "))
n = NandGate(a,b).logic()
print(int(n))
It's entirely possible that with point 5 and 6, the error is just coming from a being declared as a part of Gate, and NOT global variables as part of your runtime program.

Simple Guessing Game not working

This is supposed to be a guessing game. If the user submits a number that is higher than the pre-set value (which is 10), it will say go lower. And if the user submits a lower number, it will say go higher. The problem I'm facing is that it only tells me to go higher with every integer or even string I type in. Any clue what the problem might be?
Also, the reason I turned 10 into a string is because it gives me an error if it's an integer.
from tkinter import *
# Simple guessing game
window = Tk()
def number():
if typed == key:
print("This is the correct key")
elif typed > key:
print("Go lower!")
else:
print("Go higher!")
e = Entry(window)
e.pack()
key = str(10)
typed = e.get()
b = Button(window, text="Submit", command=number)
b.pack()
window.mainloop()
You need to update the value on each submit and check or else it will stay constant. The reason why it did not work is because you assigned typed to e.get() on program start, which is an empty string. You need to update it on every click, or put typed inside the function.
You also need to make key an integer, and convert the entry value into an integer, or else you're lexicographically comparing strings. Also, you can add a try/except to handle if the user does not enter an integer, as shown below.
I would personally pass the entry's value into the function and on click use a lambda to process the check:
from tkinter import *
# Simple guessing game
window = Tk()
def number(num): # Passing in string instead of using typed
try:
intNum = int(num) # Here we convert num to integer for comparison
if intNum == key:
print("This is the correct key")
elif intNum > key:
print("Go lower!")
else:
print("Go higher!")
except ValueError: # If user doesn't enter a convertable integer, then print "Not an integer!"
print("Not an integer!")
e = Entry(window)
e.pack()
key = 10 # Key is an integer here!
b = Button(window, text="Submit", command=lambda: number(e.get())) # Here's a lambda where we pass in e.get() to check
b.pack()
window.mainloop()
So now it will pass the value in, then compare instead of using typed. lambda: number(num) just allows the passing of an argument in the command argument. Here's a link to docs regarding lambdas. Without lambdas, here's a hastebin demonstrating without function arguments.

Resources