I am trying to get a loop that allows the user to pick "yes" or "no" and if not the program says invalid input and repeats. I just get invalid input every time and it won't give me a "yes" or "no"
def main():
choice = raw_input("Would you like to open a file? (yes or no) ")
while true:
if choice is 'no':
print("Goodbye")
break
elif choice != "yes" or choice != "no":
print("invalid input")
break
elif choice is 'yes':
file = get_file()
image = make_image(file)
show_image(image)
def get_file():
file = pickAFile()
return file
def make_image(file):
image = makePicture(file)
return image
def show_image(image):
show(image)
main()
Related
So I am working on a project where we are making a small compiler program but before I can move on to the other parts I am having troubles with getting the lexical analyzer to output anything after '\BEGIN' afterwards I debugged it and it seems the value is stuck in a loop where the condition is saying the next character is always a newline. Is it because I haven't added the pattern matching yet to the defined tokens?
Here is the code
import java.util
//import com.sun.javafx.fxml.expression.Expression.Parser.Token
/*Lexical analyzer will be responsible for the following:
- finds the lexemes
- Checks each given character determining the tokens
* */
class MyLexicalAnalyzer extends LexicalAnalyzer {
//Array full of the keywords
//val SpecialCharacters = List(']', '#', '*', '+', '\\', '[', '(',')', "![", '=')
val TEXT = "[a-z] | _ | 0-9 | [A-Z]:"
private var sourceLine: String = null
private val lexeme: Array[Char] = new Array[Char](999)
private var nextChar: Char = 0
private var lexLength: Int = 0
private var position: Int = 0
private val lexems: util.List[String] = new util.ArrayList[String]
def start(line: String): Unit = {
initializeLexems()
sourceLine = line
position = 0
getChar()
getNextToken()
}
// A helper method to determine if the current character is a space.
private def isSpace(c: Char) = c == ' '
//Defined and intialized tokens
def initializeLexems(): Any = {
lexems.add("\\BEGIN")
lexems.add("\\END")
lexems.add("\\PARAB")
lexems.add("\\DEF[")
lexems.add("\\USE[")
lexems.add("\\PARAE")
lexems.add("\\TITLE[")
lexems.add("]")
lexems.add("[")
lexems.add("\\")
lexems.add("(")
lexems.add(")")
lexems.add("![")
lexems.add("=")
lexems.add("+")
lexems.add("#")
}
//val pattern = new regex("''").r
def getNextToken() ={
lexLength = 0
// Ignore spaces and add the first character to the token
getNonBlank()
addChar()
getChar()
// Continue gathering characters for the token
while ( {
(nextChar != '\n') && (nextChar != ' ')
}) {
addChar()
getChar()
}
// Convert the gathered character array token into a String
val newToken: String = new String(lexeme)
if (lookup(newToken.substring(0, lexLength)))
MyCompiler.setCurrentToken(newToken.substring(0,lexLength))
}
// A helper method to get the next non-blank character.
private def getNonBlank(): Unit = {
while ( {
isSpace(nextChar)
}) getChar()
}
/*
Method of function that adds the current character to the token
after checking to make sure that length of the token isn't too
long, a lexical error in this case.
*/
def addChar(){
if (lexLength <= 998) {
lexeme({
lexLength += 1; lexLength - 1
}) = nextChar
lexeme(lexLength) = 0
}
else
System.out.println("LEXICAL ERROR - The found lexeme is too long!")
if (!isSpace(nextChar))
while ( {
!isSpace(nextChar)
})
getChar()
lexLength = 0
getNonBlank()
addChar()
}
//Reading from the file its obtaining the tokens
def getChar() {
if (position < sourceLine.length)
nextChar = sourceLine.charAt ( {
position += 1;
position - 1
})
else nextChar = '\n'
def lookup(candidateToken: String): Boolean ={
if (!(lexems.contains(candidateToken))) {
System.out.println("LEXICAL ERROR - '" + candidateToken + "' is not recognized.")
return false
}
return true
}
}
else nextChar = '\n'<- this is where the condition goes after rendering the first character '\BEGIN' then just keeps outputting in the debug console as listed below.
This is what the debug console it outputting after '\BEGIN' is read through
Can anyone please let me know why that is? This happens after I keep stepping into it many times as well.
Here is the driver class that uses the lexical analyzer
import scala.io.Source
object MyCompiler {
//check the arguments
//check file extensions
//initialization
//get first token
//call start state
var currentToken : String = ""
def main(args: Array[String]): Unit = {
val filename = args(0)
//check if an input file provided
if(args.length == 0) {
//usage error
println("USAGE ERROR: Must provide an input file. ")
System.exit(0)
}
if(!checkFileExtension(args(0))) {
println("USAGE ERROR: Extension name is invalid make sure its .gtx ")
System.exit(0)
}
val Scanner = new MyLexicalAnalyzer
val Parser = new MySyntaxAnalyzer
//getCurrentToken(Scanner.getNextToken())
//Parser.gittex()
for (line <- Source.fromFile(filename).getLines()){
Scanner.start(line)
println()
}
//.......
//If it gets here, it is compiled
//post processing
}
//checks the file extension if valid and ends with .gtx
def checkFileExtension(filename : String) : Boolean = filename.endsWith(".gtx")
def getCurrentToken() : String = this.currentToken
def setCurrentToken(t : String ) : Unit = this.currentToken = t
}
The code is operating as it is supposed to. The first line contains only the string \BEGIN so the lexical analyser is treating the end of the first line as an '\n' as shown in this method:
def getChar() {
if (position < sourceLine.length)
nextChar = sourceLine.charAt ( {
position += 1;
position - 1
})
else nextChar = '\n'
However, the comment directly above that method does not describe what the method actually does. This could be a hint as to where your confusion lies. If the comment says it should read from the file, but it is not reading from the file, maybe that's what you've forgotten to implement.
I'm working on integrating an IDTech swiper into my app and I've gotten pretty far along, added the library, registered notifications, unregistered them, and now I'm working on a function that connects the reader. I can't seem to figure out what I'm doing wrong here when I'm attempting to switch cases based on a return value.. could someone please help me?
func displayUmRet(operation: String, returnValue: UmRet) {
var string = ""
do {
switch returnValue {
case UMRET_SUCCESS: string = ""
case UMRET_NO_READER: string="No reader attached"
case UMRET_SDK_BUSY: string="Communication with reader in progress"
case UMRET_MONO_AUDIO: string="Mono audio enabled"
case UMRET_ALREADY_CONNECTED: string="Already connected"
case UMRET_LOW_VOLUME: string="Low volume"
case UMRET_NOT_CONNECTED: string="Not connected"
case UMRET_NOT_APPLICABLE: string="Not applicable to reader type"
case UMRET_INVALID_ARG: string="Invalid argument"
case UMRET_UF_INVALID_STR: string="Invalid firmware update string"
case UMRET_UF_NO_FILE: string="Firmware file not found"
case UMRET_UF_INVALID_FILE: string="Invalid firmware file"
default: string="<unknown code>"
}
} while (0)
// var retStatus = UMRET_SUCCESS==ret
//self.textResponse.text = "\(operation), \(retStatus), \(string)"
self.hexResponse.text = "";
}
You need to put a . before your cases:
enum UmRet {
case UMRET_SUCCESS, UMRET_FAILURE
}
var string = " "
let returnValue = UmRet.UMRET_SUCCESS
switch returnValue {
case .UMRET_SUCCESS: string = "y"
case .UMRET_FAILURE: string = "n"
}
Also, 0 isn't the same as false in Swift, so:
do {
...
} while (0)
Shouldn't work either.
And you don't need semicolons at the end of a line, so this:
self.hexResponse.text = "";
can be this:
self.hexResponse.text = ""
And finally, if your switch statement has every case for every case in your enum, you don't need a default case. (that's why mine didn't have one in the example)
By the way, ~= is just the operator for the pattern-matching function, which is what Swift does in a switch statement. It works kind of like the == function, for instance, Int ~= Int is the same as Int == Int. But it's a bit more versatile: for instance Range ~= Int, eg 0...3 ~= 2 returns whether or not the Int is in the range. (So true in this case) For enums, it matches cases to cases. In my example, it'll match UMRET_SUCCESS, and string will be set to y.
i'm creating trying to create a project, but i'm running into an error.
This is my code (not all of it, it's pretty lengthy, but the problem i'm running into):
class Rest(object):
def __init__(self, name, order=[], total=0):
self.name = name
self.order = []
self.total = 0
def end_order(self):
print("Here is your complete order: {0}".format(self.order))
print("Here is your total: {0}".format(self.total))
def order_menu(self):
loop = 1
while (loop == 1):
question_1 = raw_input("What would you like? Push S to Submit, Push C to Cancel")
if (question_1 == "1"):
self.total += 4.99
print("You added a cheeseburger, $4.99)
elif (question_1 == "S"):
end_order()
Okay, so under order_menu(self), under the elif statement, it gives me an error:
"Global name 'end_order()' is not defined".
There's a probably something silly i'm not doing, but I can't figure out what..
I believe the self keyword is required in Python when calling a class method. Try:
self.end_order()
The below code snippet is for deleting a node in linked list. My class contains two members namely data and next a pointer to hold other objects of that class type. When, I run my program, I don't get any error. If I try to delete the first item in the linked list, it enters the First for loop and displays the message "The data is found". But if I print my list, I am seeing the element in the list. I think this is because of assigning objects back, but I am not able to find where I have done that mistake. Any help is greatly appreciated.
def deleteNode(self, a_data):
flag = 0
if (self.data == a_data):
print("The data is found")
self = self.next
flag = 1
else:
while(self.next != None):
if (self.next.data == a_data):
self.next = self.next.next
flag = 1
break
else:
self = self.next
if(flag):
print("Data Deleted")
else:
print("Data not available")
Thanks
self = self.next in your code has no effect on the outside world: it just assigns to a local variable.
It looks like you are trying to delete a node from within Node class itself. You could use a function instead that accepts a list head and returns a (possibly new) list head with the corresponding item deleted:
def delete_node(head, data):
"""Delete the first node in the `head` list that has `data`."""
prev, node = None, head
while node is not None: # until the last node (`None` means empty list)
if node.data == data: # found node that has data
if prev is None: # we are at the very beginning of the list
assert head is node
head = node.next # remove the first node
else:
assert prev.next is node
prev.next = node.next # remove internal node
break
prev, node = node, node.next
return head
Friends,
I modified my function. I think the error may be because not assigning back the value to the original one, so I made my function to return value. Comments and other methods and any other reason for above than mine are cordially welcome.
def deleteNode(self, a_data):
flag = 0
if (self.data == a_data):
print("The data is found")
self = self.next
flag = 1
else:
while(self.next != None):
if (self.next.data == a_data):
self.next = self.next.next
flag = 1
break
else:
self = self.next
if(flag):
print("Data Deleted")
else:
print("Data not available")
return self
Thanks
S
I am currently using Random function in Autohotkey to generate random and save into variable rand but if user presses R.
my question is below this code
R::
Random, rand, 1, 3
Msgbox, %rand%
if (rand = "1")
{
;SAM()
}
else if (rand = "2")
{
;AAJ()
}
else if (rand = "3")
{
;HEAD()
}
else
{
;Msgbox, else
}
I also want to add code where if user presses 1 it will, may if I can add OR expression in if statement such as
if (rand = "1" || keyboardinput = "1" )
{
;SAM()
}
Why not use the same approach u used with your code for generating random numbers.
1::
if( rand == 1)
{
tooltip, hello
}
return
You are also missing a return at the end of the first part of your code, unless you want the script to start executing things it shouldn't.