For example I want to generate below output using for loop:
line1
line2
line3
line4
line5
line6
line7
CodePudding user response:
Here is how to do it with "f-strings" and the range()
class object in a for
loop:
for_loop_basic_demo.py:
#!/usr/bin/python3
END_NUM = 7
for i in range(1, END_NUM 1):
print(f"line{i}")
Run command:
./for_loop_basic_demo.py
Output:
line1
line2
line3
line4
line5
line6
line7
Going further: 3 ways to print
The 3 ways I'm aware of to print formatted strings in Python are:
- formatted string literals; AKA: "f-strings"
- the
str.format()
method, or - the C
printf()
-like%
operator
Here are demo prints with all 3 of those techniques to show each one for you:
#!/usr/bin/python3
END_NUM = 7
for i in range(1, END_NUM 1):
# 3 techniques to print:
# 1. newest technique: formatted string literals; AKA: "f-strings"
print(f"line{i}")
# 2. newer technique: `str.format()` method
print("line{}".format(i))
# 3. oldest, C-like "printf"-style `%` operator print method
# (sometimes is still the best method, however!)
print("line%i" % i)
print() # print just a newline char
Run cmd and output:
eRCaGuy_hello_world/python$ ./for_loop_basic_demo.py
line1
line1
line1
line2
line2
line2
line3
line3
line3
line4
line4
line4
line5
line5
line5
line6
line6
line6
line7
line7
line7
References:
- ***** This is an excellent read, and I highly recommend you read and study it!: Python String Formatting Best Practices
- Official Python documentation for all "Built-in Functions". Get used to referencing this: https://docs.python.org/3/library/functions.html
- The
range()
class in particular, which creates arange
object which allows the abovefor
loop iteration: https://docs.python.org/3/library/functions.html#func-range
- The
CodePudding user response:
You can use f strings.\
n = 7
for i in range(1, n 1):
print(f"line{i}")
CodePudding user response:
l=['line1','line2','line3','line4','line5','line6','line7']
for i in l:
print(i)