+ 3
[SOLVED] How to write for loop in one line ?
x="123" sum=0 for i in x: sum=sum+int(i) print("sum of digits is",sum) I want to write this for loop in one line how can I do that ? https://code.sololearn.com/cLXij8Zqajo7/?ref=app
26 Respostas
+ 11
here is a short tutorial i did some months ago: "turning a for loop to a comprehension"
https://code.sololearn.com/cqnGujvL7CXe/?ref=app
+ 6
dear all, wouldn't it be better to give the asker a chance to get his task done by himself befor we post solutions here? i mean we can give hints and guide him, so that he will grow in his skills?
BTW Frogged: the code you provided needs a closing parenthesis at the end of the line!
to Ratnapal Shende , you have done it as a regular for loop first. from there it is only a small step to a one-liner. the best way is to use a comprehension.
+ 4
mySum=sum([int(c) for c in "123"]
+ 4
Ratnapal Shende , it does not matter if your code is not running properly, just post it!
+ 4
+ 4
Frogged i will never gonna forget this pattern bro in my life...
Thank you so much..you are the best
+ 4
I also suggest this way:
[[sum:=0],[sum:=sum+int(c) for c in "123"],[print(sum)]]
for this programm:
sum=0
for c in "123":
sum=sum+int(c)
print(sum)
because it is more generall and can also used to doe everything within this for loop and also things before and after it....
+ 4
Use list comprehensions
https://code.sololearn.com/cGW7VrWGMjGU/?ref=app
+ 3
Lothar tried bro but I am stucked please help me
+ 3
OK bro agree with you Lothar
+ 3
Lothar yes and no and i hasitated to answer.
But sometimes there are ...well known secrets...how to do it.
In this case codemonkey had a very fine answer and I hope Ratnapal Shende will remember this pattern.
In other cases I will be with you.
+ 3
lol š¤£š
+ 3
Ratnapal Shende I don't think that Frogged is a bro.
+ 2
Ratnapal Shende , please do a try by yourself first. put your code in playground and link it here. if you get stuck come back .
Thanks!
+ 2
But I must say to maintain the proper redability and neatness of code you should not use one liners but it is totally up to yoh .
+ 2
Ohhh..
+ 1
Lothar Your code is only for adding strings which should be printed...
My code can do basically everything
[dosomething(),[dosth2(i) for i in lst],dosth3()]
+ 1
print(sum(map(int,list(x))))
you can use this line of code. you don't even need a for loop.
0
For(int i=0;i<200;i++)
{
Body of for loop
}
*First declare any variable..
*Then initialization by giving the start value..
*Condition where the program can access..
*Decrement or increament into the value...