I am fairly new programmer, currently I have been assigned a project to create a looping calculator that even after you use one of the calculator functions it will keep going until you make a selection provided. My problem with my calculator currently is that there is an incessant termination whenever I try to test my function on Pydev. I already fixed the first problem where Pydev read one of my variables (choice) as unused so I used the "ctrl + 1" trick and that got rid of the unused variable warning. Any tips on how I might be able to run this program and have it continually loop?
def main():
loop=1
choice=0 # #UnusedVariable
while loop == 1:
print("Welcome to Calculator Function!")
print("Your options are:")
print(" ")
print("1/) Addition")
print("2/) Subtraction")
print("3/) Multiplication")
print("4/) Division")
print("5/) Quit CalculatorFunction.py")
print(" ")
choice = int(raw_input("Choose your option: ").strip())
if choice == 1:
add1 = input("Add what: ")
add2 = input("To what: ")
print add1, "+", add2, "=", add1+add2
elif choice == 2:
sub2 = input("Subtract what: ")
sub1 = input("From what: ")
print sub1, "-", sub2, "=", sub1-sub2
elif choice == 3:
mult1 = input("Multiply what: ")
mult2 = input("To what: ")
print mult1, "*", mult2, "=", mult1*mult2
elif choice == 4:
div2= input("Divide what: ")
div1= input("From what: ")
print div1, "/", div2, "=", div1/div2
elif choice == 5:
loop = 0
print"Thank you for using CalculatorFunction.py have a good day!"
else:
print"No selection made, please try again."
if __name__ == '__main__':
main()
Your if - else block is outside the while loop, that is why it doesn't work. Here's the properly indented code:
def main():
loop=1
choice=0 # #UnusedVariable
while loop == 1:
print("Welcome to Calculator Function!")
print("Your options are:")
print(" ")
print("1/) Addition")
print("2/) Subtraction")
print("3/) Multiplication")
print("4/) Division")
print("5/) Quit CalculatorFunction.py")
print(" ")
choice = int(raw_input("Choose your option: ").strip())
if choice == 1:
add1 = input("Add what: ")
add2 = input("To what: ")
print add1, "+", add2, "=", add1+add2
elif choice == 2:
sub2 = input("Subtract what: ")
sub1 = input("From what: ")
print sub1, "-", sub2, "=", sub1-sub2
elif choice == 3:
mult1 = input("Multiply what: ")
mult2 = input("To what: ")
print mult1, "*", mult2, "=", mult1*mult2
elif choice == 4:
div2= input("Divide what: ")
div1= input("From what: ")
print div1, "/", div2, "=", div1/div2
elif choice == 5:
loop = 0
print"Thank you for using CalculatorFunction.py have a good day!"
else:
print"No selection made, please try again."
if __name__ == '__main__':
main()
This worked well on pydev.
Thanks to your tips on "indentation" and a couple of other things I finally figured out the program works thank you all for your input. What I did to fix my immediate termination was fix the indentation. Then to make it so the program continually loops if a selection isn't made I added the continue, in essence the only way to terminate the program is to select the option quit which is listed as "5".
def main()
loop=1
choice=0 # #UnusedVariable
while loop == 1:
print(" ")
print("Welcome to Calculator Function!")
print("Your options are:")
print(" ")
print("1) Addition")
print("2) Subtraction")
print("3) Multiplication")
print("4) Division")
print("5) Quit CalculatorFunction.py")
print(" ")
choice = int(raw_input("Choose your option: ").strip())
if choice == 1:
add1 = int(raw_input("Add what: "))
add2 = int(raw_input("To what: "))
print add1, "+", add2, "=", add1+add2
elif choice == 2:
sub2 = int(raw_input("Subtract what: "))
sub1 = int(raw_input("From what: "))
print sub1, "-", sub2, "=", sub1-sub2
elif choice == 3:
mult1 = int(raw_input("Multiply what: "))
mult2 = int(raw_input("To what: "))
print mult1, "*", mult2, "=", mult1*mult2
elif choice == 4:
div2= int(raw_input("Divide what: "))
div1= int(raw_input("From what: "))
print div1, "/", div2, "=", div1/div2
elif choice == 5:
loop = 0 #Ends the program
print"Thank you for using CalculatorFunction.py have a good day!"
else:
print"No selection made, please try again."
continue #loops the program
if name == 'main':
main()
Related
I'm using the following awk command to replace strings in a swift source file:
awk '
BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
{ print }
' "$old" "$new" "$file" > ./temp
Trying not to edit commented out values. At a minimum, need to ignore lines that start with "//" but it seems possible to ignore inline comments (e.g. when the line is only partially commented like "MATCH // <- Ok" or "foo // MATCH <- Not Ok").
Something like...
s=index($0,old) && !($0 =~ "^//") { ... }
Sample Input:
old="\"Some \(value) with %# special \n characters\""
new="\"some_key\".localized"
file {contents}...
/// - Returns: "Some \(value) with %# special \n characters"
static let someValue = "Some \(value) with %# special \n characters" // <-- This should change
static let otherValue = "This line does NOT change" // "Some \(value) with %# special \n characters"
Expected Output:
/// - Returns: "Some \(value) with %# special \n characters"
static let someValue = "some_key".localized // <-- This should change
static let otherValue = "This line does NOT change" // "Some \(value) with %# special \n characters"
EDIT
Although #RavinderSingh13's answer did not match expected output, it was close and I used it to modify my command like so:
BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
s=index($0,old) { if (!(match($0,/.*\/\//))) $0 = substr($0,1,s-1) new substr($0,s+len) }
{ print }' "$old" "$new" "$file"
This meets the original requirement, but ignores ANY line that has two slashes. This is problematic, because it doesn't support in line comments (e.g. the above command would not edit any of the sample input; unless the "// <-- This should change" comment is removed. If no one replies, I'll use this as the answer, but I'll wait a day or so in case someone posts a version of the command that meets all the requirements. Will accept that answer.
It would be something like this...
s=index($0,old) { if (!(match($0,/.*\/\//)) || (match($0,/"$old".*\/\//))) $0 = substr($0,1,s-1) new substr($0,s+len) }
Considering that you want skip all lines which start from // and also you want to print contents which comes before // for in between inline comments. Fair warning not tested since NO samples given.
awk '
BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
/^\/\//{ next }
match($0,/.*\/\//){ $0 = substr($0,RSTART,RLENGTH-2) }
s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
{ print }
' "$old" "$new" "$file" > ./temp
Above will neglect lines which are starting with // if you want to print them then do following.
awk '
BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
/^\/\//{ print; next }
match($0,/.*\/\//){ $0 = substr($0,RSTART,RLENGTH-2) }
s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
{ print }
' "$old" "$new" "$file" > ./temp
Only look for "old" in the part of each line before the start of any comment, e.g.:
awk '
BEGIN { old=ARGV[1]; new=ARGV[2]; ARGV[1]=ARGV[2]=""; len=length(old) }
{ preCmt = $0; sub("//.*","", preCmt) }
s=index(preCmt,old) { $0 = substr($0,1,s-1) new substr($0,s+len) }
{ print }
' "$old" "$new" file
/// - Returns: "Some \(value) with %# special \n characters"
static let someValue = "some_key".localized // <-- This should change
static let otherValue = "This line does NOT change" // "Some \(value) with %# special \n characters
In the official swift document it says
"The print(_:separator:terminator:) function is a global function that prints one or more values to an appropriate output."
var welcomeMessage = "Hello"
var friendlyWelcom = "Hello!"
print(friendlyWelcom, separator: ",", terminator: "", welcomeMessage, separator: ",", terminator: "") // Why this is not working
Question As the comments inside the code - why do print(friendlyWelcom, welcomeMessage) and print(friendlyWelcom, separator: ",", terminator: "" work but print(friendlyWelcom, separator: ",", terminator: "", welcomeMessage, separator: ",", terminator: "") generates a compiler error?
You cannot simply add named parameters as you wish. Instead you should pass the variables to print in comma seperated as the first argument. They then get joined with the separator in between and the terminator at the end:
print(friendlyWelcom, welcomeMessage, separator: " - ", terminator: "?")
Outputs
Hello! - Hello?
You can add as many variables there as you wish:
print(friendlyWelcom, welcomeMessage, 123, "somethingElse", "etc", separator: " - ", terminator: "!!!!")
Hello! - Hello - 123 - somethingElse - etc!!!!
This works,
print map { $_." x" => $_ } 1..5;
print map { ("$_ x" => $_) } 1..5;
print map { ("$_ x") => $_ } 1..5;
but this throws syntax error,
print map { "$_ x" => $_ } 1..5;
Is this documented bug, undocumented bug, or I can't see why this should not compile?
Why perl thinks this should be map EXPR, LIST instead of map BLOCK LIST
From perlref
Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a + or a return in front so that Perl realizes the opening brace isn't starting a BLOCK. The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle.
To make your intentions clearer and to help the parser,
Say +{...} to unambiguously specify a hash reference
#list_of_hashrefs = map +{ "$_ x" => $_ }, 1..5;
Say {; ...} to unambiguously specify a code block
%mappings = map {; "$_ x" => $_ } 1..5;
Why perl thinks this should be map EXPR, LIST instead of map BLOCK LIST?
The relevant section of code is in toke.c, Perl's lexer (the below is from Perl 5.22.0):
/* This hack serves to disambiguate a pair of curlies
* as being a block or an anon hash. Normally, expectation
* determines that, but in cases where we're not in a
* position to expect anything in particular (like inside
* eval"") we have to resolve the ambiguity. This code
* covers the case where the first term in the curlies is a
* quoted string. Most other cases need to be explicitly
* disambiguated by prepending a "+" before the opening
* curly in order to force resolution as an anon hash.
*
* XXX should probably propagate the outer expectation
* into eval"" to rely less on this hack, but that could
* potentially break current behavior of eval"".
* GSAR 97-07-21
*/
t = s;
if (*s == '\'' || *s == '"' || *s == '`') {
/* common case: get past first string, handling escapes */
for (t++; t < PL_bufend && *t != *s;)
if (*t++ == '\\')
t++;
t++;
}
else if (*s == 'q') {
if (++t < PL_bufend
&& (!isWORDCHAR(*t)
|| ((*t == 'q' || *t == 'x') && ++t < PL_bufend
&& !isWORDCHAR(*t))))
{
/* skip q//-like construct */
const char *tmps;
char open, close, term;
I32 brackets = 1;
while (t < PL_bufend && isSPACE(*t))
t++;
/* check for q => */
if (t+1 < PL_bufend && t[0] == '=' && t[1] == '>') {
OPERATOR(HASHBRACK);
}
term = *t;
open = term;
if (term && (tmps = strchr("([{< )]}> )]}>",term)))
term = tmps[5];
close = term;
if (open == close)
for (t++; t < PL_bufend; t++) {
if (*t == '\\' && t+1 < PL_bufend && open != '\\')
t++;
else if (*t == open)
break;
}
else {
for (t++; t < PL_bufend; t++) {
if (*t == '\\' && t+1 < PL_bufend)
t++;
else if (*t == close && --brackets <= 0)
break;
else if (*t == open)
brackets++;
}
}
t++;
}
else
/* skip plain q word */
while (t < PL_bufend && isWORDCHAR_lazy_if(t,UTF))
t += UTF8SKIP(t);
}
else if (isWORDCHAR_lazy_if(t,UTF)) {
t += UTF8SKIP(t);
while (t < PL_bufend && isWORDCHAR_lazy_if(t,UTF))
t += UTF8SKIP(t);
}
while (t < PL_bufend && isSPACE(*t))
t++;
/* if comma follows first term, call it an anon hash */
/* XXX it could be a comma expression with loop modifiers */
if (t < PL_bufend && ((*t == ',' && (*s == 'q' || !isLOWER(*s)))
|| (*t == '=' && t[1] == '>')))
OPERATOR(HASHBRACK);
if (PL_expect == XREF)
{
block_expectation:
/* If there is an opening brace or 'sub:', treat it
as a term to make ${{...}}{k} and &{sub:attr...}
dwim. Otherwise, treat it as a statement, so
map {no strict; ...} works.
*/
s = skipspace(s);
if (*s == '{') {
PL_expect = XTERM;
break;
}
if (strnEQ(s, "sub", 3)) {
d = s + 3;
d = skipspace(d);
if (*d == ':') {
PL_expect = XTERM;
break;
}
}
PL_expect = XSTATE;
}
else {
PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
PL_expect = XSTATE;
}
Explanation
If the first term after the opening curly is a string (delimited by ', ", or `) or a bareword beginning with a capital letter, and the following term is , or =>, the curly is treated as the beginning of an anonymous hash (that's what OPERATOR(HASHBRACK); means).
The other cases are a little harder for me to understand. I ran the following program through gdb:
{ (x => 1) }
and ended up in the final else block:
else {
PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
PL_expect = XSTATE;
}
Suffice it to say, the execution path is clearly different; it ends up being parsed as a block.
I'm writing a description of R syntax, and I'd like to include some statements that include syntax errors, e.g.
if (n >= 2)
{
# if TRUE
}
else
{
# if FALSE
}
(This is a syntax error at top level because the if is complete before the else is read.) I'm trying to put this into a knitr document, but
even with error=TRUE it fails, because that option only affects run-time errors, not syntax errors. Is there some reasonable way to get this to display what would be shown if I entered it at the console? I.e.
I'd like it to display something like
if (n >= 2)
{
# if TRUE
}
else
Error: unexpected 'else' in "else"
{
# if FALSE
}
Here's a function that does part of what I want: it reproduces the output from a syntax error, but it doesn't do all the markup that knitr would do, so the formatting is wrong.
parse_with_error <- function(text) {
reportError <- function(e) {
msg <- conditionMessage(e)
line <- as.numeric(sub("^text:([[:digit:]]*):.*", "\\1", msg))
col <- as.numeric(sub("^text:[[:digit:]]*:([[:digit:]]*):.*", "\\1", msg))
cat(text[1:line], sep="\n")
if (col > 1)
cat(paste(rep(" ", col-1), collapse=""))
cat("^\n")
err <- sub("^text:[[:digit:]]*:[[:digit:]]*: ([^[:cntrl:]]*)\n.*", "\\1", msg)
parseData <- getParseData(sf)
lastToken <- parseData[nrow(parseData), "text"]
cat(paste0("Error: ", err, ' in "', lastToken, '"'), "\n")
}
text <- unlist(strsplit(text, "\n"))
sf <- srcfile("text")
tryCatch(parse(text = text, keep.source = TRUE, srcfile=sf),
error = reportError)
}
This shows how it would be used:
parse_with_error(
"if (TRUE) {
# do TRUE
}
else {
# do FALSE
}")
You can use a separate R session to evaluate the code, e.g.
```{r, engine='Rscript', error=TRUE}
if (TRUE)
{
# if TRUE
}
else
{
# if FALSE
}
```
How can I run for until a condition is met? Instead of using scala.util.control.Breaks.break, is it possible to test for a condition within for?
for(line <- source.getLines) {
if (line.equals("")) scala.util.control.Breaks.break
Console print "Message> "
dataWriter.write(line, InstanceHandle_t.HANDLE_NIL)
}
} catch {
case e: IOException =>{
Try takeWhile
for(line <- source.getLines.takeWhile(!_.isEmpty)) {
Console print "Message> "
dataWriter.write(line, InstanceHandle_t.HANDLE_NIL)
}
or
source.getLines.takeWhile(!_.isEmpty).foreach {
line =>
Console print "Message> "
dataWriter.write(line, InstanceHandle_t.HANDLE_NIL)
}