Good day fellow programmers!
This is the instructions I got for my python class and I am struggling so hard to make the input appear as I'd like.
flipside(s) takes a string s and returns a string whose first half is s's second half and the second half is the first. if the length is odd, the first half of the input string should have one fewer character than the second half. For example, the string carpet would have the output petcar. The input carpets would have the output petscar.
This is my current code:
def flipside():
print("This program will return second half as first half of what you write.")
s = input("Type in any word: ")
newWord = len(s)%2
print("DEBUG: ",newWord)
if newWord == 1:
print("DEBUG: ODD")
print (s[3:]+s[:4])
else:
print("DEBUG: EVEN")
print(s[4:]+s[:4])
I am really confused of what I should type inside the brackets to slice up the words properly. I've searched around using google to find solution for this function, and none work.
Could any experienced Python programmer explain to me what I've done wrong with my code? I'd like to learn.
I am using python 3.0
This is not a matter of Python programming, just of finding the division point. Whatever you find, your new string will be of the second form you give:
s[div_pt:] + s[:div_pt]
The "ODD" case you give repeats the 4th letter.
Integer division should solve your problem for you:
div_pt = len(s) // 2
Can you slip those into your program and see what you get? Try a couple of different examples, such as "carpet" and "ashtray".
Related
So i'm new to Python and i'm going through a Python course I purchased and they have a quiz. The last question was to print the last 6 letters of the string. The code is below:
welcome_message = "Hello and welcome to the land of Python"
print(f"The last 6 letters of the welcome message:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")
The output would then be:
The last 6 letters of the welcome message:
'Hello and welcome to the land of Python'
are: Python
This is from the solution. I am not understanding what's going on here: '{welcome_message[len(welcome_message)-6:]}'
I don't understand why the solution included the len() function.
Why can't I just do '{welcome_message[-6:]}'
?
You'll get the same output with this too.
In python -1 index is same as the last index and when its blank it means starting or ending depending on where you put it. for eg.
welcome_message[:]
will print the entire string.
As for your question you can use welcome_message[34:] which instead of counting yourself a better way of writing is welcome_message[len(welcome_message)-6:].
But an even better way of writing is the solution you pointed out, i.e,
welcome_message[-6:]
print(f"The last 6 letters of the welcome message:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")
Here is what is happening welcome_message is a variable which can have infinite letters/character/number/symbols/strings etc.. which the system does not know first hand...
So welcome_message[len...] first finds how many characters are there in the string, not words... I say characters because we supply len() function with the welcome_message variable which has just 1 string... so thus far i hope I explained what happened till
{welcome_message[len(welcome_message)]} and then its just plain old -6 arithmetic operation from the count that is returned by the len() fn
welcome_message = "Hello and welcome to the land of Python"
print(f"The last 6 letters of the welcome message:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")
Here welcome_message is storing a string which is "Hello and welcome to the land of Python".
while printing if we will add \n in a string it will output a newline in answer.
len(welcome_message)-6 = 39-6 = 33.
in string slicing s[i:] it will give output as a string which includes the character from i to end of the string.
Hence welcome_message[len(welcome_message)-6:] will output the characters from index of 33 to 39th index.
Remember that " " is also a character of the string.
I need to create a box with parameters that prints any input the user puts in. I figured that the box should be the length of the string, but I'm stuck with empty code, because I don't know where to start.
It should look like this:
I agree with Daniel Goldfarb comments. Don't look for help without trying.
If you still couldn't get how to do that, then only read my remaining comment.
Just print :
str = string entered
len(str) = string length
+-(len(str) * '-')-+
| str |
+-(len(str) * '-')-+
So hopefully you can learn, don't want to just write the code for you. Basically break it into steps. First you need to accept user input. If you don't know how to do that, try googling, "python accept user input from stdin" or here is one of the results from that search: https://www.pythonforbeginners.com/basics/getting-user-input-from-the-keyboard
Then, as you mentioned, you need the length of the string that was input. You can get that with the len function. Then do the math: It looks like you want "|" and two spaces on each side of the string, giving the length plus 6 ("| " on either side). This new length is what you should make the "+---+" strings. Use the print() function to print out each line. I really don't want to say much more than that because you should exercise your brain to figure it out. If you have a question on how to generate "+---+" of the appropriate length (appropriate number of "-" characters) you can use string concatenation and a loop, or just use the python string constructor (hint: google "construct python string of len repeat characters"). HTH.
One more thing, after looking at your code, in addition to my comment about printing the string itself within the box, I see some minor logic errors in your code (for example, why are you subtracting 2 from the width). THE POINT i want to me here is, if you ware going to break this into multiple small functions (a bit overkill here, but definitely a good idea if you are just learning as it teaches you an important skill) then YOU SHOULD TEST EACH FUNCTION individually to make sure it does what you think and expect it to do. I think you will see your logic errors that way.
Here is the solution, but I recommend to try it out by yourself, breakdown the problem into smaller pieces and start from there.
def format(word):
#It declares all the necessary variables
borders =[]
result = []
# First part of the result--> it gives the two spaces and the "wall"
result.append("| ")
# Second part of the result (the word)
for letter in word:
result.append(letter)
# Third part of the result--> Ends the format
result.append(" |")
#Transforms the list to a string
result = "".join(result)
borders.append("+")
borders.append("--"+"-"*len(word)+"--")
borders.append("+")
borders="".join(borders)
print(borders)
print(result)
print(borders)
sentence = input("Enter a word: ")
format(sentence)
I'm new to Python, and I've found this solution. Maybe is not the best solution, but it works!
test = input()
print("+-", end='')
for i in test:
print("-", end='')
print("-+")
print("| " + test + " |")
print("+-", end='')
for i in test:
print("-", end='')
print("-+")
I am a total newbie in programming so I was hoping anyone could help me. I am trying to write program in python that, given an integer n, returns me the corresponding term in the sylvester sequence. My code is the following:
x= input("Enter the dimension: ")
def sylvester_term(n):
""" Returns the maximum number of we will consider in a wps of dimension n
>>> sylvester_term(2)
7
>>> sylvester_term(3)
43
"""
if n == 0:
return 2
return sylvester_term(n-1)*(sylvester_term(n-1)-1)+1
Now, my questions are the following, when trying to run this in GitBash, I am asked to input the n but then the answer is not showing up, do you know what I could do to receive the answer back? I plan to continue the code a bit more, for calculating some other data I need, however, I am not sure if it is possible for me to, after coding a certain piece, to test the code and if so, how could I do it?
You will need to add:
print(sylvester_term((int(x)))
to the end of your program to print the answer.
You will need to cast to int because the Python Input() function stores a string in the variable. So if you input 5 it will return "5"
This does not handle exceptions, e.g if the user inputs a letter, so you should put it in a try and except statement.
Here's an example of how I'd handle it. You can use sys.argv to get the arguments passed via the command line. The first argument is always the path to the python interpreter, so you're interested in the second argument, you can get it like so:
sys.argv[1]
Once that is done, you can simply invoke your function like so
print(sylvester_term(int(sys.argv[1]))
As the title suggests, I want to get a string, split it into individual bits to input into something like ord('') and get a value for each individual character in that string. Still learning python so things like this get super confusing :P. Furthermore, the process for encryption for each of the codes will just be to shift the alphabet's dec number by a specified value and decrypt into the shifted value, plus state that value for each character. How would i go about doing this? any and all help would be greatly appreciated!
message=input("Enter message here: ", )
shift=int(input("Enter Shift....explained shift: ", )
for c in list(message):
a=ord(c)
print c
This is the very basic idea of what i was doing (was more code but similar), but obviously it didn't work :C, the indented--> just means that it was indented, just don't know how to do that in stack overflow.
UPDATE: IT WORKS (kinda) using the loop and tweaking it according to the comments i got a list of every single ascii dec value for each character in the string!, ill try and use #Hugh Bothwell's suggestion within the loop and hopefully get some work done.
mystring = "this is a test"
shift = 3
encoded = ''.join(chr(ord(ch) + shift) for ch in mystring)
You'll have to do a little more if you want your alphabet to wrap around, ie encode('y') == 'b', but this should give you the gist of it.
I'm new to Python and have been working through some tutorials to try to get to grips with different aspects of programming.
I'm stuck on an exercise that is most likely very simple however I am unable to find the solution.
How do I create a program that reads one line of input and prints out the same line two times?
For example if the input was Echo it would print:
Echo
Echo
Any help with this would be hugely appreciated. I think I'm making a simple logic error but don't yet have the skills in place to recognise what it is.
The other answers seem logical enough, but what if you wanted to print it let's say a 1000 times or a million times? Are you really going to be typing print(variable) a million types? Here is a faster way:
j=input("Enter anything.")
for i in range(2):
print(j)
Here, I can change the value of range to whatever I want, and J will be printed that many times.
What happens here, is that the variable i loops upwards (an increment) to the number 2, so to explain it to a beginner, i travels t=from number to number. Where I put print(j) for every number i loops through until it gets to 2, J will be printed.
It sounds like you've been doing the input and output in one go:
print(input())
That works for doing a single echo of the input, but makes it a bit harder to repeat the same thing twice. An easy workaround would be to save the inputted text to a variable, which you can print twice:
text = input()
print(text)
print(text)
If you needed to do the input and doubled output with a single statement, you could use string formatting to duplicate the text with a newline in the middle:
print("{0}\n{0}".format(input()))
way complex right?(:D)
inp = input("Input something would ya? ")
print(inp)
print(inp)