Very new to the world of programming and just starting to learn, working through Flatiron School prework and have been doing ok but unable to understand "if" and "else" statements for some reason. The problem is similiar to Chris Pine 'deaf grandma' problem but without saying "BYE!" three times.
~The method should take in a string argument containing a phrase and check to see if the phrase is written in all uppercase: if it isn't, then grandma can't hear you. She should then respond with (return) HUH?! SPEAK UP, SONNY!.
~However, if you shout at her (i.e. call the method with a string argument containing a phrase that is all uppercase, then she can hear you (or at least she thinks that she can) and should respond with (return) NO, NOT SINCE 1938!
I have so far:
def speak_to_grandma
puts "Hi Nana, how are you?".upcase
if false
puts "HUH?! SPEAK UP, SONNY!"
else
puts "NO, NOT SINCE 1938!"
end
end
but am getting wrong number of arguments...how am I supposed to add argument while using the if/else statements? This is probably a very easy and basic question but can't seem to get my head around this (overthinking probably).
Any help and clarity would be greatly appreciated.
input_phrase = "Hi Nana, how are you?"
def speak_to_grandma(phrase)
# Check if string equals same phrase all upper case letters, which means string is all uppercase
if phrase == phrase.upcase
# return this string if condition is true
puts "NO, NOT SINCE 1938!"
else
# return this string if condition is false
puts "HUH?! SPEAK UP, SONNY!"
end
end
# execute function passing input_phrase variable as argument
speak_to_grandma(input_phrase)
how am I supposed to add argument while using the if/else statements?
This is probably a very easy and basic question but can't seem to get
my head around this (overthinking probably).
Your mistake was that function was not accepting any arguments, here it accepts "phrase" variable as argument and processes it:
def speak_to_grandma(phrase)
You had
if false
but did not check what exactly is false.. To rewrite my version with "false" :
input_phrase = "Hi Nana, how are you?"
def speak_to_grandma(phrase)
# Check if it is false that string is all upper case
if (phrase == phrase.upcase) == false
# return this string if condition is false
puts "HUH?! SPEAK UP, SONNY!"
else
# return this string if condition is true
puts "NO, NOT SINCE 1938!"
end
end
speak_to_grandma(input_phrase)
Here I am evaluating
if (phrase == phrase.upcase) == false
Basically means "if expression that phrase equals phrase all uppercase is false"
Related
I want the while loop to run as long as the name is not "1234". And if the name is only spaces, I want to print "name can not be only spaces" and ask for a name again. Else I want it to just ask for a name again.
name=input("")
while (name!="1234"):
if(name.isspace):
print ("name can not be only spaces")
name=input("")
else:
name=input("")
The problem I have is that it prints "name can not only be spaces" for whatever string I give it. Even if the string does not have spaces it prints the if statement. What is going on?
You might just be missing the parentheses of the isspace function.
So turn isspace into isspace() and you should be fine.
As Mat has already mentioned, the problem you're facing is simply because name.ispace does not return a boolean like you need in your program.
Also, I think you could simplify your code a bit -
name=input("")
while (name!="1234"):
if(name.isspace()):
print ("name can not be only spaces")
name=input("")
In many other programming languages, there is a function which takes as a parameter a regular expression and returns an array of string values. This is true of Javascript and Ruby. The .match in crystal, however, does 1) not seem to accept the global flag and 2) it does not return an array but rather a struct of type Regex::MatchData. (https://crystal-lang.org/api/0.25.1/Regex/MatchData.html)
As an example the following code:
str = "Happy days"
re = /[a-z]+/i
matches = str.match(re)
puts matches
returns Regex::MatchData("Happy")
I am unsure how to convert this result into a string or why this is not the default as it is in the inspiration language (Ruby). I understand this question probably results from my inexperience dealing with structs and compiled languages but I would appreciate an answer in hopes that it might also help someone else coming from a JS/Ruby background.
What if I want to convert to a string merely the first match?
puts "Happy days"[/[a-z]+/i]?
puts "Happy days".match(/[a-z]+/i).try &.[0]
It will try to match a string against /[a-z]+/i regex and if there is a match, Group 0, i.e. the whole match, will be output. Note that the ? after [...] will make it fail gracefully if there is no match found. If you just use puts "??!!"[/[a-z]+/i], an exception will be thrown.
See this online demo.
If you want the functionality similar to String#scan that returns all matches found in the input, you may use (shortened version only left as per #Amadan's remark):
matches = str.scan(re).map(&.string)
Output of the code above:
["Happy days", "Happy days"]
Note that:
String::scan will return an array of Regex::MatchData for each match.
You can call .string on the match to return the actual matched text.
Actually the posted example returns a #<MatchData "Happy"> in Ruby, which also has no "global" flag – thats what String#scan(Regex) is for as mentioned by others.
If you want only a single match without going through Regex::MatchData, you can use String#[](Regex):
str = "Happy days"
p str[/[a-z]+/i] # => "Happy"
I am trying to evaluate below expression in Robot framework
Run Keyword If '${buttondisplayed}' == 'PASS' and '${ReturnedInfo}' ==
' PASS', Some Keyword,
else if, '${buttondisplayed}' ==
'PASS' and '${ReturnedInfo}' == 'FAIL', Some Keyword ,
else if, '${buttondisplayed}' == 'FAIL' and '${ReturnedInfo}' == 'PASS',
Some Keyword,
else, Some Keyword
Where the value of both ${buttondisplayed} and ${ReturnedInfo} = FAIL.
Based on above condition, else part mentioned, in the end, should be executed however in Log output I am getting the following result
Documentation:
Runs the given keyword with the given arguments, if the condition is true.
Start / End / Elapsed: 20170806 11:15:14.448 / 20170806 11:15:14.448 / 00:00:00.000
So basically none of the conditions is executed here.
Could anyone please indicate what is wrong here in this expression?
There are at least four problems with the code you've posted:
there's only one space after the first "if"
"else if" is lowercase. It must be all uppercase (ELSE IF)
you have commas in your code. robot syntax doesn't support commas as field separators
your code seems to span multiple lines but you aren't using the robot line continuation characters ...
Run Keyword If '${buttondisplayed}'=='PASS' and '${ReturnedInfo}'=='PASS' Some Keyword
... ELSE IF '${buttondisplayed}'=='PASS' and '${ReturnedInfo}'=='FAIL' Some Keyword
... ELSE IF '${buttondisplayed}'=='FAIL' and '${ReturnedInfo}'=='PASS' Some Keyword
... ELSE Some Keyword
#input = "rrgb"
def is_letters?
#input.chars.all? {|letter| letter == /[a..zA..Z]/}
end
def right_letters?
#input.chars.all? {|letter| letter =~ (/[rgbyrp]/)}
end
So #right_letters? will return true because it will return an arrays of trues : [true, true, true, true]. 0s are truthy and so it will return an array of trues?
#is_letters? will return an array of falses right? I can't use == there if I want the line to mean "the letter is either a lower case letter or uppercase letter".
Is there a better way to code "this letter is one of these letters :r,g,b,y,r,p
This is really a question about Ruby, and all? doesn't work like you think it does - it just returns false if the block ever returns a falsey value, and true otherwise.
To your question, yes. What you've missed is that regex operates on a whole string, you don't have to do one character at a time. So:
#input = "rrgb"
def is_letters?
! #input.match /[^a-z]/i
end
def right_letters?
#input.match /[rgbyrp]/
end
Note as well that I demonstrate above that the syntax you're trying to use for a character class range (ie. a..z) is wrong, the regex syntax is a-z.
By matrix style, I mean having n variables, each with some number of inputs, and having to handle all possible values. The simplest case of this is multiple boolean values and having to handle every combination of true/false. This is easy if the returned values follow certain patterns, but otherwise it seems quite difficult.
(If there is a better name than 'matrix style', please comment and tell me so I can update the title.)
The ugly way to handle this is an if else chain.
IF self.A = 'N' THEN
IF self.B = 'N' THEN
...
ELSE
...
END IF;
ELSE
IF self.B = 'N' THEN
...
ELSE
...
END IF;
END IF;
Good luck keeping track of that mess, especially with more than 4 variables.
A slightly more readable way of doing this is to do all the checks together.
IF self.A = 'N' AND ... self.Y = 'N' AND self.Z = 'N' THEN
returnValue := 'Bob';
END IF;
If self.A = 'N' AND ... self.Y = 'N' AND self.Z = 'Y' THEN
returnValue := 'Birthday Party';
END IF;
...
If self.A = 'Y' AND ... self.Y = 'N' AND self.Z = 'N' THEN
returnValue := 'What did I ever do to deserve this?';
END IF;
...
If self.A = 'Y' AND ... self.Y = 'Y' AND self.Z = 'Y' THEN
returnValue := 'Thank God I am done!';
END IF;
You can make that a little better if you do a CASE statement instead of a bunch of if/elses, but that is still very hard to maintain. Imagine accidentally putting a Y instead of an N some place and having to go find it. Considering the chance for errors grows exponentially with each new variable added (as you at least double the amount of code you need to write), there is a good chance for errors in any significant sized problem like this.
You can potentially do some interesting text replacement to try to reduce errors. I recently did this with 5 variables. I started with...
NNNNN
NNNNY
...
YYYYN
YYYYY
Then I ran some find and replace over them using Notepad++ to try to reduce the chance of mistyping a N or Y. But the end product still looks nasty to maintain. So I'm wondering if there are any better ways to handle this (mostly in terms of maintainability, though any efficiency boost without loosing maintainability are also welcome suggestions). While I'm looking specifically for PL/SQL solutions, any solutions in other languages are still welcome because they might be able to be translated to PL/SQL.
Edit: In case anyone is trying to solve this problem and wants to use my current solution, here is the find and replace.
Find: ([Y,N]) repeated as many times as you have variables.
Replace: \t\t\tWHEN self.valueName = '\1' THEN\r\n\t\t\t\treturnValue := '' where the self.valueName = '\1' is repeated once for each variable you have, with the \1 incremented each time. You'll also need to set the correct number of \t's so that it matches however much indented it should be. This works in Notepad++, regex mode.
Why do you have that problem? I assume that this is a variable of a type consisting out of variables from A-Z. So how do you populate this in the first place? Can't you simplify right there?
But if there is no alternative you can first check if there is only 'Y' and 'N' in the single fields and convert to 1 and 0 and make numbers out of it and check against the numbers. E.g. NNNNY becomes one and NNNYN becomes 2 etc. Then it is IF r=1 then .. elsif r=2 ..
A probably even better alternative is to generate the code. You can form a string that has the "create or replace functionX as ..." and do an execute immediate on it.
Try to concatenate to one value (self.A || self.B || .. || self.Z) and then use case on values like 'NNNNN', 'NNNNY', 'NNNYN, etc.
EDIT:
I made assumtions that:
you have large set of one-char variables that...
...you want to translate to single return value...
...covering all-or-many possibile sets.
What you gain is a view of all combinations, one per line, one key under other, in each single-char column having same self.variable. If number of variables is really big, to avoid options like YNNYYYNYNNYNYYYNNY you can improve readability to put space every 3-rd or 5-th or n-th char:
when 'NNN NNN NNN' then '1st choice'
when 'NNN NNN NNY' then '2nd choice'
when 'NNN NNN NYN' then '3rd choice'
... ... ...
As #hol in answer below suggested generating code is a very good choice in that case.
But you, as developer, should know if m-th choice is YYY YNY YY or YYY NYY YY, no other way to be sure whether you get correct results than to check/test code.