How to do a backspace in python - python-3.x

I'm trying to figure out how to print a one line string while using a for loop. If there are other ways that you know of, I would appreciate the help. Thank you. Also, try edit off my code!
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
for e in range(1,times+1):
print(e)
if e != times:
print("+")
else:
pass
Out:
Enter a number: 5
*
**
***
****
*****
Equation:
1
+
2
+
3
+
4
+
5
How do I make the equation in just one single line like this:
1+2+3+4+5

I don't think you can do a "backspace" after you've printed. At least erasing from the terminal isn't going to be done very easily. But you can build the string before you print it:
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
equation_string = ""
for e in range(1,times+1):
equation_string += str(e)
if e != times:
equation_string += "+"
else:
pass
print(equation_string)
Basically, what happens is you store the temporary equation in equation_str so it's built like this:
1
1+
1+2
1+2+
...
And then you print equation_str once it's completely built. The output of the modified program is this
Enter a number: 5
5
*
**
***
****
*****
Total stars:
15
Equation:
1+2+3+4+5
Feel free to post a comment if anything is unclear.

Instead of your original for loop to print each number, try this:
output = '+'.join([str(i) for i in range(1, times + 1)])
print(output)
Explanation:
[str(i) for i in range(1, times + 1)] is a list comprehension that returns a list of all your numbers, converted to strings so that we can print them.
'+'.join(...) joins each element of your list, with a + in between each element.
Alternatively:
If you want a simple modification to your original code, you can simply suppress the newline from each print statement with the keyword paramater end, and set this to an empty string:
print(e, end='')
(Note that I am addressed the implied question, not the 'how do I do a backspace' question)

Too long for a comment, so I will post here.
The formatting options of python can come into good use, if you have a sequence you wish to format and print.
Consider the following...
>>> num = 5 # number of numbers to generate
>>> n = num-1 # one less used in generating format string
>>> times = [i for i in range(1,num+1)] # generate your numbers
>>> ("{}+"*n + "{}=").format(*times) # format your outputs
'1+2+3+4+5='
So although this doesn't answer your question, you can see that list comprehensions can be brought into play to generate your list of values, which can then be used in the format generation. The format string can also be produced with a l.c. but it gets pretty messy when you want to incorporate string elements like the + and = as shown in the above example.

I think you are looking for the end parameter for the print function - i.e. print(e, end='') which prints each value of e as it arrives followed by no space or newline.

Related

Beginner coder. Trying to convert string to integer in Python 3.X [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 months ago.
I am a at the very beginning of learning to code in python and am following a tutorial. I attempted to convert this string into an integer to get it to simply add 5 and 6. Here is what I have
No matter what I do, I get 5+6 = 56. Here is what I have:
first_num = (input('Please enter a number '))
second_num = (input('Please enter another number '))
print int((first_num) + int(second_num))
I tried using a comma instead of a plus sign, as a few places suggested. I also tried using int in front of the input line to convert the inputs themselves from strings to integer.
I expect it to add 5 + 6 = 11. I keep getting 56.
I'm not positive what version of Python I'm using, but I know I'm using VS Code and it is Python 3.X. i just don't know what the X is. Here is a screenshot
edit: I have resolved this question. I was not saving the file before I ran it. Therefore every time I tried to change something it was just running the saved, incorrect file. Thanks to those that tried to help me.
In Python when you add two strings together you concatenate the values.
For an easier example:
string_one = "hello"
string_two = " "
string_three = "there"
final = string_one + string_two + string_3
print(final) # hello there
To add them together mathematically, you need to ensure the values are ints, floats, decimals...
one = 1
two = 2
final = one + two
print(final, type(final)) # 3 int
So for your code:
first_num = int(input('Please enter a number'))
second_num = int(input('Please enter another number'))
final = first_num + second_num
print(final) # will give you the numbers added
However, you are casting to ints based on user input, so I would ensure you are also catching the errors that occur when a user enters a value that cannot be cast to an int, like hi. For example:
try:
first_num = int(input('Please enter a number'))
second_num = int(input('Please enter another number'))
print(first_num + second_num) # will give you the numbers added, if ints
except ValueError as ex:
# if any input val is not an int, this will hit
print("Error, not an int", ex)
Try this
first_num = int(input('Please enter a number '))
second_num = int(input('Please enter another number '))
sum=first_num+second_num
print (sum)

Horizotal print of a complex string block

Once again I'm asking for you advice. I'm trying to print a complex string block, it should look like this:
32 1 9999 523
+ 8 - 3801 + 9999 - 49
---- ------ ------ -----
40 -3800 19998 474
I wrote the function arrange_printer() for the characters arrangement in the correct format that could be reutilized for printing the list. This is how my code looks by now:
import operator
import sys
def arithmetic_arranger(problems, boolean: bool):
arranged_problems = []
if len(problems) <= 5:
for num in range(len(problems)):
arranged_problems += arrange_printer(problems[num], boolean)
else:
sys.exit("Error: Too many problems")
return print(*arranged_problems, end=' ')
def arrange_printer(oper: str, boolean: bool):
oper = oper.split()
ops = {"+": operator.add, "-": operator.sub}
a = int(oper[0])
b = int(oper[2])
if len(oper[0]) > len(oper[2]):
size = len(oper[0])
elif len(oper[0]) < len(oper[2]):
size = len(oper[2])
else:
size = len(oper[0])
line = '------'
ope = ' %*i\n%s %*i\n%s' % (size,a,oper[1],size,b,'------'[0:size+2])
try:
res = ops[oper[1]](a,b)
except:
sys.exit("Error: Operator must be '+' or '-'.")
if boolean == True:
ope = '%s\n%*i' % (ope,size+2, res)
return ope
arithmetic_arranger(['20 + 300', '1563 - 465 '], True)
#arrange_printer(' 20 + 334 ', True)
Sadly, I'm getting this format:
2 0
+ 3 0 0
- - - - -
3 2 0 1 5 6 3
- 4 6 5
- - - - - -
1 0 9 8
If you try printing the return of arrange_printer() as in the last commented line the format is the desired.
Any suggestion for improving my code or adopt good coding practices are well received, I'm starting to get a feel for programming in Python.
Thank you by your help!
The first problem I see is that you use += to add an item to the arranged_problems list. Strings are iterable. somelist += someiterable iterates over the someiterable, and appends each element to somelist. To append, use somelist.append()
Now once you fix this, it still won't work like you expect it to, because print() works by printing what you give it at the location of the cursor. Once you're on a new line, you can't go back to a previous line, because your cursor is already on the new line. Anything you print after that will go to the new line at the location of the cursor, so you need to arrange multiple problems such that their first lines all print first, then their second lines, and so on. Just fixing append(), you'd get this output:
20
+ 300
-----
320 1563
- 465
------
1098
You get a string with \n denoting the start of the new line from each call to arrange_printer(). You can split this output into lines, and then process each row separately.
For example:
def arithmetic_arranger(problems, boolean:bool):
arranged_problems = []
if len(problems) > 5:
print("Too many problems")
return
for problem in problems:
# Arrange and split into individual lines
lines = arrange_printer(problem, boolean).split('\n')
# Append the list of lines to our main list
arranged_problems.append(lines)
# Now, arranged_problems contains one list for each problem.
# Each list contains individual lines we want to print
# Use zip() to iterate over all the lists inside arranged_problems simultaneously
for problems_lines in zip(*arranged_problems):
# problems_lines is e.g.
# (' 20', ' 1563')
# ('+ 300', '- 465') etc
# Unpack this tuple and print it, separated by spaces.
print(*problems_lines, sep=" ")
Which gives the output:
20 1563
+ 300 - 465
----- ------
320 1098
If you expect each problem to have a different number of lines, then you can use the itertools.zip_longest() function instead of zip()
To collect all my other comments in one place:
return print(...) is pretty useless. print() doesn't return anything. return print(...) will always cause your function to return None.
Instead of iterating over range(len(problems)) and accessing problems[num], just do for problem in problems and then use problem instead of problems[num]
Debugging is an important skill, and the sooner into your programming career you learn it, the better off you will be.
Stepping through your program with a debugger allows you to see how each statement affects your program and is an invaluable debugging tool

Difference resulting from position of print in loops

First question here.
I am picking up Python and have a question that may be quite basic.
I am trying to create this pattern with a nested loop:
x
x
x
xxx
With the code:
numbers = [1,1,1,3]
for count_x in numbers:
output = ""
for count in range(count_x):
output +=x
print(output)
My question is - why does my output change when I move the position of print(output).
The code above works but when I align print(output) with the for count_x in numbers:, I only get "xxx", when I align print(output) to output +=x, I get the following:
x
x
x
x
xx
xxx
which is very odd because there are only 4 items in the list and it shows me 6 lines of output.
Could someone please help? Really puzzled. Thank yall very much.
There's a difference between these two bits of code (fixing the x/"x" problem along the way - your code won't actually work as is unless you have a variable x):
# First:
numbers = [1,1,1,3]
for count_x in numbers:
output = ""
for count in range(count_x):
output += "x"
print(output)
# Second:
numbers = [1,1,1,3]
for count_x in numbers:
output = ""
for count in range(count_x):
output += "x"
print(output)
In the second, the print is done inside the loop that creates the string, meaning you print it out multiple times while building it. That's where your final three lines come from: *, ** and ***. This doesn't matter for all the previous lines since there's no functional difference. Printing a one character string at the end or after adding each of the one characters has the same effect.
In the first, you only print the string after fully constructing it.
You can see this effect by using a slightly modified version that outputs different things for each outer loop:
numbers = [1,1,1,3]
x = 1
for count_x in numbers:
output = ""
for count in range(count_x):
output += str(x)
print(output)
x += 1
This shows that the final three lines are part of a single string construction (comments added):
1 \
2 >- | Each is one outer/inner loop.
3 /
4 \ | A single outer loop, printing
44 >- | string under construction for
444 / | each inner loop.
In any case, there are better ways to do what you want, such as:
numbers = [1,1,1,3]
for count_x in numbers:
print('x' * count_x)
You could probably also do it on one line with a list comprehension but that's probably overkill.

for some input in python3 in increasing order of list not come right

my code is:
n=int(input())
list_1 = []
for i in range(n):
list_1.append(input())
list_2=[]
#print(list_1)
while list_1:
minimum = list_1[0]
for x in list_1:
if x < minimum:
minimum = x
list_2.append(minimum)
list_1.remove(minimum)
print (' '.join(map(str, list_2)))
all output come correct but incorrect come in some input like
4
10
3
7
6
please help
Your list 'list_1' is a list of strings, and for strings minimums work in a different manner. For example, '10' < '3' is True.
Change the line:
list_1.append(input())
To:
list_1.append(int(input()))
The first thing you should do when posting questions here is properly explain your problem, and what the code does.
Now for your question, Mono found the issue in your code, but you should know that you do not need all this to sort a list of numbers. It already exists in the language. Use the sort() function on the list, like this:
print("This script will ask you for numbers and print them back to you in order.")
print("Enter how many numbers you will input: ", end="")
n=int(input())
list_1 = []
print("Please type each number.")
for i in range(n):
print(" Number", i, ": ", end='')
list_1.append(int(input()))
list_1.sort()
print("These are your numbers, in order:")
print (' '.join(map(str, list_1)))
The output is:
This script will ask you for numbers and print them back to you in order.
Enter how many numbers you will input: 4
Please type each number.
Number 0 : 10
Number 1 : 2
Number 2 : 8
Number 3 : 3
These are your numbers, in order:
2 3 8 10

How can I insert spaces at certain locations in a string (Python 2.7)?

I've found many related questions, and a couple that have at least helped me get this far. My goal is to have a function that receives a string and an arbitrary number of integers. I want the function to return that string with spaces inserted at the points given in the arguments. I will use this function with many different strings that will have varying numbers of inserts and insert locations.
This is an example of what I'd like to produce:
Input a string like 'ATGCATGCATGCATGC' and indexes (e.g. 4, 7). The output should be 'ATGCA TGC ATGCATGC'.
This is the function that has given me the closest results so far:
def breakRNA(seqRNA, *breakPoint):
n = 0
for i in seqRNA:
n += 1
for i in breakPoint:
if i == n:
seqRNA = seqRNA[n:] + ' ' + seqRNA[:n]
return seqRNA
The return string, however, is transposed out of order. Example:
>>> test = breakRNA('AAAAAAAAAAAAAAAAAAAAAAAAAAATTTTTGGGGGGGGCCCCCCCCCC', 5, 8, 14)
>>> test
>>> 'TTTTTGGGGGGGGCCCCCCCCCC AAAAA AAAAAAAA AAAAAAAAAAAAAA'
I am a day-1 beginner so any advice is appreciated. Thank you.
String are indexed like list in Python.
For example consider the following:
test_string = "azertyuiop"
print test_string[0] #will return 'a'
print test_string[0:2] #will return 'az'
So getting back to your problem:
def insert_space(string, integer):
return string[0:integer] + ' ' + string[integer:]
Hope this is what you are looking for
def breakRNA(seqRNA, *breakPoint):
seqRNAList = []
noOfBreakPoints = len(breakPoint)
for breakPt in range(noOfBreakPoints):
for index in breakPoint:
seqRNAList.append(seqRNA[:index])
seqRNA = seqRNA[index:]
break
return seqRNAList
test = breakRNA('AAAAAAAAAAAAAAAAAAAAAAAAAAATTTTTGGGGGGGGCCCCCCCCCC', 5, 8, 14)
print test
This will return you alist then you can create a string out of it using join function.
simbol = input('Enter a character:\n')
triangle_n = int(input('Enter triangle height:\n'))
print('')
for i in range (triangle_n ):
for j in range(i+1):
print(simbol [0],end=' ')
print()
string_name = string_name[starting index:ending index] + ' ' + string_name[starting index:ending index]
example:
product_rating = '4.56888 rating 256156 reviews'
product_rating = product_rating[0:3] + ' ' + product_rating[3:]
output
'4.5 6888 rating 256156 reviews'
If ending index is not mentioned its default value will be till the end of string.
Note indexing will start from 0 and 0:3 means it will take 0 to 2.

Resources