简体   繁体   中英

Python homework, midpoints and rounding strings

These are the steps given by my professor,:

  1. Assume user will enter string with at least 1 character
  2. Store the input as user_input
  3. Calculate length of user input
  4. Store this as 'string_length'
  5. Print message stating whether length is even or odd 6.print "length is" and the length of the string
  6. Assume user will input either 'h1', 'div' or 'article'
  7. Store this input as variable 'tag'

  8. Calculator half the length of the string_length, rounded down

  9. Store this value as 'midpoint'
  10. Calculate a new string that is the first half of 'user_input' using midpoint
  11. Store this as 'first_half'

  12. Calculate a new string that is the concatenation of 'tag' and 'first_half' in the following format first_half

  13. Store this value in a variable called tagged_input.

Attached is the code I've already run. Everything works fine up until I start with the "tag" variable being defined. So basically around step 9 and onward I have issues.

user_input=input ("Please enter something")
string_length=len(user_input)
even_message= string_length % 2

if even_message>0:
print ("The length is", string_length, "characters long and is 
odd.")

else:
print ("Your length is", string_length, "characters long and is 
even.")

tag= input("Input one of the following: h1, div or article.")

midpoint = (string_length/2)
first_half= (midpoint)
tagged_input= print ((tag) + (midpoint) + "/" + (tag))

Output should be this. (uploaded a screenshot to imgur)

https://imgur.com/a/ogiTQiH

this should work(replace the last 3 lines of your code with this):

midpoint = (string_length//2)
first_half = user_input[:midpoint]
tagged_input = f"<{tag}>{first_half}</{tag}>"

(1) the first line uses the // operator, that divides and rounds down

(2) the second line uses list/sequence slicing: Understanding slice notation

(3) the third line uses a fairly new and very useful feature of python called f-strings: https://realpython.com/python-f-strings/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM