Python Forum
For loop syntax and math on len()
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For loop syntax and math on len()
#1
I am curious to know if you are able to divide the len of a string to get a numeric value. I am trying to do this within a for loop. I have two outcomes to the code i would like to write.
1. prints symbols over the users name.
2. allows for a space between the symbols, while sticking to the length of the users name.

i was sable to use len for the symbols without a space.
name="KEYS"
symbol="."
for i in range(1, len(name)+1, 1):
        print (symbol, end="")
print("\n"+str(name))
Output is
....
KEYS

but with space between the symbols i would need half the spaces or characters.
I tried this but it was definitely wrong.

    for e in range(1, len(name)/2, 1):
        print (symbol, end=" ")
    print("\n"+(str(name)))
trying to get an output of or something like
. .
KEYS
Reply
#2
The problem is that you are using a proportional font. The width of "m" is wider than the width of '.'. If you switch to a monospace font (Courier, for example) then it will work. Otherwise very hard to get the dots to line up with the characters
Reply
#3
Your attempt was close, but the division renders a float and you want an integer. So using floor division is a better idea. Changing yours to this makes it work okay.

name="KEYS"
symbol="."
for e in range(1, len(name)//2 + 1, 1):
    print (symbol, end=" ")
print("\n"+(str(name)))
You don't need to put in an explicit step of 1, since that is the default.

But I would probably take out the loop and do something like:
print(f"{symbol} " * (len(name)//2 + 1))
print(name)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  math.log versus math.log10 stevendaprano 10 2,400 May-23-2022, 08:59 PM
Last Post: jefsummers
  Why getting ValueError : Math domain error in trig. function, math.asin() ? jahuja73 3 3,764 Feb-24-2021, 05:09 PM
Last Post: bowlofred
  Error on nested loop : Invalid syntax dvazquezgu 3 3,232 Nov-25-2020, 10:04 AM
Last Post: palladium
  "SyntaxError: invalid syntax" running code in Doing Math With Python b saucerdesigner 2 2,725 Nov-03-2020, 04:23 PM
Last Post: saucerdesigner
  pass after a loop is a syntax error??? Skaperen 5 5,856 Jan-16-2017, 03:01 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020