Why is the else statement is not allowed to have a then or other conditions?
Is it because it is the final condition within the else-if conditions it represents?
I am struggling to understand this concept since I'm a beginner who just learned about variables.
I'm asking this because I received an error with my else statement in the code:
message = 0
condition = 30
if condition <=10
message = “try harder”
elseif
condition <=20 then
message = "Almost learning"
else
condition = <=30 **—This is the line where I get the error message**
message = "Now you’re getting it"
end
print(message)
Would appreciate someone breaking down in laymen terms, why else is not allowed to have < or > or then or other conditions.
else condition = <= 30
(which is the way your code was originally formatted) would be a very unusual feature in a language.
The whole point of else on its own is to execute if none of the other conditions were true. So a condition on the else is absolutely useless.
The Programming in Lua book if statement shows the normal usage:
if op == "+" then
r = a + b
elseif op == "-" then
r = a - b
elseif op == "*" then
r = a*b
elseif op == "/" then
r = a/b
else
error("invalid operation")
end
However, your actual code (when formatted correctly) ends up looking like:
else
condition = <=30
which is correct in terms of the else but unfortunately makes the next line a statement. And this statement is very much incorrect syntax.
Now it may be that you meant to assign 30 to condition but, based on your other lines (that sort of match this as a condition), I suspect not. So it's probably best just to remove that line totally.
I have to count two words 'cat' and 'dog' from a string.
If the counts are equal, I would like to return True else false.
For example, for input "dogdoginincatcat" my method should return True.
Here is my code,
def cat_dog(str):
count=0
count1=0
for i in range(len(str)):
if str[i:i+3] == 'cat':
count=count+1
if str[i:i+3] == 'dog':
count1=count+1
if count == count1:
return True
else:
return False
cat_dog('catdog')
just one line to do this using count on a string:
z= "dogdoginincatcat"
print(z.count("cat")==z.count("dog"))
First, DON'T use str (the string class) as a variable name. While Python won't cry at that very moment, you'll regret it later.
Second, it doesn't look like the count and count1 are indented as inside blocks of the 'if' statements, so your code is seen as:
for i in range(len(str))
if something:
pass
count = count + 1
if something_else:
pass
count1 = count1 + 1
Other than that, your code seems to work
import scala.collection.mutable.MutableList
var x = false
while (!x) {
val list = MutableList[Any]()
val input = scala.io.StdIn.readLine("input pls:\n")
list += input
if (input == "end"){ x = true ; println("Bye!"); sys.exit}
if (input =="show") {println(list)}
}
So whenever I run this program and then enter "show" to print the list it only prints out "show" in the list but why not the other input I have done before? What do I have to change in order to store all the input into my list (append) till i type "show" or "end?
All you need to do is move initialization of list variable up:
val list = MutableList[Any]()
while (!x) {
// ...
}
The way you have it now, a new list is created in every loop iteration and thus previous content is lost.
Scala 2.11.7 on Ubuntu 15.04 / OpenJDK8
I added a line feed "\n" removal function called .stripLineEnd thinking this was needed for the ifs to match, but apparently that is unnecessary and will work fine with or without.
From Documentation:
def stripLineEnd: String
Strip trailing line end character
from this string if it has one.
A line end character is one of
LF - line feed (0x0A hex)
FF - form feed (0x0C hex)
If a line feed
character LF is preceded by a carriage return CR (0x0D hex), the CR
character is also stripped (Windows convention).
And, as #Mifeet said, the code was initializing the list on every loop and need to move the initialization to before the loop.
import scala.collection.mutable.MutableList
var x = false
val list = MutableList[Any]()
while (!x) {
val input = scala.io.StdIn.readLine("input pls:\n").stripLineEnd
list += input
if (input == "end"){ x = true ; println("Bye!"); sys.exit}
if (input =="show") {println(list)}
}
for(i=getchar();; i=getchar())
if(i=='x')
break;
else putchar(i);
Answer is : mi
Can someone explain this piece of code ?(MCQ Question)
This question can be solved by eliminating incorrect answer. This fragments prints character and exits loop if the character is an x. So the program would not output an x.
Any output string that doesn't contain x is possible. In your MCQ, possibly mi is the only option with x and all other options contain x somewhere in the string making them incorrect answer.
If input is "mix....", output would be "mi". Below is your loop unrolled.
getchar() -> m -> else -> print m /* First getchar */
getchar() -> i -> else -> print i /* Second getchar */
getchar() -> x -> if -> break /* Second getchar */
for(i=getchar();; i=getchar())
if(i=='x')
break;
else putchar(i);
your Code will keep on running till it encounter 'x' so whatever input you give, it will read character by character as you have used getchar() function..
If character is 'x' then break the loop.
else print character.
like, If the input is
sparx
output will be
spar
The for loop
for(i=getchar();; i=getchar())
and syntax and structure of the for loop is
for ( variable initialization; condition; variable update )
as i = getchar() will read char 'i' it is ok. next there is no condition and final in updating you are again reading a character so it a infinite loop.
Loop will terminate only when it will encounter 'x' as the statement
if(i=='x')
break;
Otherwise it will keep on printing the character.
else putchar(i);
Here is the Demo.
Hope it helps!!
I am beginner for real programming and have the ff problem
I want to read many instances stored in a file/csv/txt/excel
like the folloing
find<S>ing<G>s<p>
Then when I read this file it goes through each character and start from the six position and continue until the 11 position-the max size of a single row is 12
-,-,-,-,-,f,i,n,d,i,n,0
-,-,-,-,f,i,n,d,i,n,g,0
-,-,-,f,i,n,d,i,n,g,s,0
-,-,f,i,n,d,i,n,g,s,-,S//there is an S value next to the letter d
-,f,i,n,d,i,n,g,s,-,-,0
f,i,n,d,i,n,g,s,-,-,-,0
i,n,d,i,n,g,s,-,-,-,-,G // there is a G value here at th end of g
n,d,i,n,g,s,-,-,-,-,-,P */// there is a P value here at th end of s
Here is the code that I tried in python. but can be possible in c++, java, dotNet.
import sys
import os
f = open('/home/mm/exprimentdata/sample3.csv')// can be txt file
string = f.read()
a = []
b = []
i = 0
while (i < len(string)):
if (string[i] != '\n '):
n = string[i]
if (string[i] == ""):
print ' = '
if (string[i] = upper | numeric)
print rep(char).rjust(12),delimiter=','
a.append(n)
i = (i+1)
print (len(a))
print a
my question is how can I compare each string and assign a single char at the rightmost part (position 12 like above G,P,S)
how can I push one step back after aligning the first row?
how can i fix the length
please anyone see fragment and adjust to solve the above case
I don't understand your question.
But some advice:
Firstly, you should be closing the file after you open it.
f = open('/home/mm/exprimentdata/sample3.csv')// can be txt file
string = f.read()
**f.close()**
Secondly, your indentation is problematic. Whitespace matters in Python. (Maybe your real code is indented properly and it's just a StackOverflow thing.)
Thirdly, instead of using a while loop and incrementing, you should be writing:
for i range(len(string)):
# loop code
Fourthly, this line will never evaluate to True:
if (string[i] == ""):
string[i] will always be some character (or cause an out of bounds error).
I advise you read a Python tutorial before you try and write this program.