3

Suppose I have the list

primary = {"b","a","e"}

I want to get the following output with a For-loop (or While-loop)

"b"
"a"
"e"

My code is:

For[i = 0, i < 3, Part[primary, i], i++]

but there was no Output.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257

2 Answers2

8

Some things:

  1. For-loops are for effect; they always return Null, which doesn't print.
  2. Your For-loop is mal-formed.
  3. Mathematica arrays are 1-based, not 0-based.
  4. To get printed output you need to use Print or some other function that produces an output cell.

Taking the above into consideration, the minimal correction to your code is:

For[i = 1, i <= 3, i++, Print[Part[primary, i]]]

But here is a much better way to do the same thing.

Scan[Print, primary]

This writes the each character in own output cell.

multi_cell

Update

Another very simple solution you might consider is

Column[primary]

This writes each character on its own line is a single output cell.

one_cell

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
2

You might try the code as in the following transcript:

Mathematica 10.2.0 for Microsoft Windows (32-bit)
Copyright 1988-2015 Wolfram Research, Inc.

In[1]:= primary = {"b", "a", "e"};

In[2]:= Map[ Print @ InputForm @ # &, primary];
"b"
"a"
"e"

In[3]:=

which seems to be what you want.

The InputForm is a print format which shows the double quotes delimiting the strings. The Print @ InputForm @ # & is an idiomatic way of defining an anonymous function which prints an exmpression using the print format. The Map[] applies the function to all the elements of the list. As usual in Mathematica there are several variant ways to do something like what you wanted to do. One variant would be to use Scan[] instead of Map[] which has the advantage that the trailing ; would not be needed. Here is another variation using Do[]

In[3]:= Do[ Print @ InputForm @ s, {s , primary}]
"b"
"a"
"e"

In[4]:=
Somos
  • 4,897
  • 1
  • 9
  • 15