Python adding a string after range - python

a little stuck on this function.
So N = 5 it will print 0 1 2 3 4
N = 3 it will print 0 1 2
I was able to get this to run but on second step I need to add the results together. So it would be
N=3 0+1+2 = 3
N=5 0+1+2+3+4 = 10
Below is my code I am just unsure how to structure this to get the results I seek.
n = int(input("n = "))
if i in range(n):
x = str(i)
print(sum(x))
n = 5
Traceback (most recent call last):
File "<ipython-input-17-95a1e729596f>", line 4, in <module>
print(sum(x))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

You can't really use the built-in sum() function in a for-loop to add up the numbers in that range. You can either forget the loop altogether or add to a variable (s):
n = int(input("n = "))
s = 0
for i in range(n):
s += i
print(s)
So when I enter n = 5, the output is the sums:
0
1
3
6
10
As stated at the beginning of this post, I mentioned that you could do this without using a loop. So, here is how you would do that:
n = int(input("n = "))
print(sum(range(n))
which when n = 5 would just print the total sum of 10.
Oh and one last note is that you don't need to convert an integer (the i in the for-loop) to a string to be able to print it.

I'd keep it simple, avoid the loop, and use the resources Python gives you:
n = int(input("n = "))
print(*range(n), sep=' + ', end=' = ')
print(sum(range(n)))
USAGE
% python3 test.py
n = 5
0 + 1 + 2 + 3 + 4 = 10
%

I guess you can just do the following.
First, ask for the input, and translate the given number from string to integer.
n = int(input("N = "))
Then, print a sum of the range from 0 to n-1.
print(sum(range(n)))
Hope it is what you were asking!

Related

How to break a while loop when input is a particular string?

I need to stop adding up user inputs when one of them is the string "F".
So basically If my input is a int then : += result, if the same input variable is a string then I need to stop and add them together.
My code actually works and has the same inputs and outputs the exercise demands but I'm very unhappy with the way I resolve it.
This is my code:
import numbers
cat = int(input())
def norm(cat):
res = 0
for n in range(cat):
x = int(input())
res += x
print(res)
def lon():
res = 0
while 2 > 1:
try :
y = int(input())
if isinstance(y,int):
res +=y
except:
print(res)
break
if cat >= 0 :
norm(cat)
else:
lon()
It's actually breaking the while loop in a stupid way by checking if my variable is an int. (I need to make it stop by simply pressing F)
Is there any cleaner and shorter way to obtain the same outputs?
Example of the actual inputs-outputs I expect :
in: out:16 (1 + 3 + 5 + 7)
4
1
3
5
7
in: out:37 (1 + 3 + 5 + 7 + 21)
-1
1
3
5
7
21
F
You could have written it a bit shorter:
result = 0
while True:
line = input()
try:
result += int(line)
except ValueError:
break
print(result)
Notice:
import numbers isn't needed. (I didn't even know that existed!)
Instead of 2 > 1, you can use True.
You don't need to check isinstance(..., int) since int() enforces that.
This runs until any non-integer string is reached.
If you want to specifically check for "F" only, it's a bit easier:
result = 0
while True:
line = input()
if line == "F":
break
result += int(line)
print(result)
Note that without using try, you'll crash the program if you input a non-integer, non-"F" string.

fill empty array using loop in python

i'm new to python and i'm asked to make a basic calculator using 3 input int, int, str. the input and output should be like this:
INPUT
1 2 ADD
4 100 MUL
5 2 DIV
100 10 SUB
OUTPUT
3
400
2
90
Here's what i'm trying to do:
angk1, angk2, ope = input().split(" ")
angk1, angk2, ope = [int(angk1),int(angk2),str(ope)]
hasil = []
i = hasil
L = 0
while True:
for L in range(1, 500):
if ope=='ADD':
hasil[L] = (angk1+angk2)
elif ope=='MUL':
hasil[L] = (angk1*angk2)
elif ope=='DIV':
hasil[L] = (angk1/angk2)
elif ope=='SUB':
hasil[L] = (angk1-angk2)
L += 1
i.extend(hasil)
if input()=='STOP':
break
print i
print 'Done'
and the result is:
'123 123 ADD'
Traceback (most recent call last):
File "test.py", line 9, in <module>
hasil[L] = (angk1+angk2)
IndexError: list assignment index out of range
can anyone point my mistakes? any help appreciated.
I have cleaned your program up a little. I added a message print('Type number number OPERATOR to perform operation. Type STOP to end program.') at the beginning to guide the reader. Also, I took out the for loop (you had a for loop and a while loop, which were redundant. Also, you need to use append when adding to your list as you are starting with an empty list, so passing in an index will throw an error.
hasil = []
print('Type number number OPERATOR to perform operation. Type STOP to end program.')
while True:
inp = input()
if inp == 'STOP':
break
angk1, angk2, ope = inp.split(" ")
angk1, angk2, ope = [int(angk1),int(angk2),str(ope)]
if ope=='ADD':
hasil.append(angk1+angk2)
elif ope=='MUL':
hasil.append(angk1*angk2)
elif ope=='DIV':
hasil.append(angk1/angk2)
elif ope=='SUB':
hasil.append(angk1-angk2)
for i in hasil:
print(i)
print('Done')
Input:
1 2 ADD
4 100 MUL
5 2 DIV
100 10 SUB
Output:
3
400
2.5
90
Done
try building the list like:
if ope=='ADD':
x = (angk1+angk2)
hasil.append(x)
and you might want to print the value of L, it looks like it might not be what you're intending it to be based on the loop structure.

printing a number pattern in python without white space and new line at the end

The aim is to print a pattern half triangle depending upon the user input for example if the user input is 3 the pattern would be
1
1 2
1 2 3
but upon executing there is a space after the each element of the last column and a new line (\n) after the last row. i would like to remove that please help.
1 \n
1 2 \n
1 2 3 \n
likewise whereas the expected output is
1\n
1 2\n
1 2 3
here is the code i wrote
rows = int(input())
num = 1
for i in range (0, rows):
num = 1
for j in range(0, i + 1):
print(num,end=" ")
num = num + 1
print("")
Others have already shown the alternatives. Anyway, I believe that you are learning, and you want to understand that exact case. So, here is my comment.
YOU print the space. You cannot unprint it when already printed. There are more ways to solve that. If you want to preserve the spirit of your solution, you must not print the space after the last num. You can do one less turn of the inner loop, and print the last num separately, like this:
rows = int(input())
num = 1
for i in range (0, rows):
num = 1
for j in range(0, i):
print(num, end=' ')
num = num + 1
print(num)
In the example, the first num line can be removed. Also, you combine counted loop with your own counting (the num). It usually means it can be simplified. Like this:
rows = int(input('Type the number of rows: '))
for i in range (0, rows):
for j in range(1, i + 1):
print(j, end=' ')
print(i + 1)
Now, some experiment. Everything under the outer loop is actually printing a row of numbers. The sequence is generated by the range -- the generator that produces the sequence. When the sequence is wrapped by list(), you get a list of the numbers, and you can print its representation:
rows = int(input('Type the number of rows: '))
for i in range (1, rows + 1):
print(list(range(1, i + 1)))
It prints the result like...
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
Instead, you want to print the sequences of the same numbers joined by space. For that purpose, you can use join. However, you have to convert each of the elements to a string:
rows = int(input('Type the number of rows: '))
for i in range (1, rows + 1):
print(' '.join(str(e) for e in range(1, i + 1)))
And that is already similar to the solutions presented by others. ;)
Its too simple than the code you have made:
a = int(input("Enter a num: "))
for i in range(a+1):
print(" ".join(list(map(str,range(1,i+1)))),end="")
if i != a:print("")
Executing:
Enter a num: 3
1
1 2
1 2 3
>>>
I suggest you the following soltuion, building the whole result string first before printing it without new line character at the end:
my_input = int(input("Enter a num: "))
s = ""
for i in range(my_input):
s += " ".join([str(j) for j in range(1,i+2)])
s += "\n" if i != my_input-1 else ""
print(s, end="")
My version of your requirement,
rows = int(input('Enter a number - '))
num = 1
for i in range(0, rows):
num = 1
tmp = []
for j in range(0, i + 1):
tmp.append(str(num))
num = num + 1
if i + 1 == rows:
print(repr("{}".format(' '.join(tmp))))
else:
print(repr("{}\n".format(' '.join(tmp))))
p.s - Remove repr() if not required
Output
Enter a number - 3
'1\n'
'1 2\n'
'1 2 3'
Instead of printing a line piece by piece, or building a string by repetitively adding to it, the usual and efficient way in Python is to put all the values you want to print in a list, then to use join to join them.
Also, you don't need two imbricated loops: just append the latest number to your existing list on each loop, like this:
rows = int(input())
values = []
for i in range(1, rows + 1):
values.append(str(i))
print(' '.join(values))
Output:
3
1
1 2
1 2 3

Python: Reversing print order from a while loop

I am writing some code takes values, the values number and N as input and prints, the first N lines of a multiplication table as below:
3 * 4 = 12
2 * 4 = 8
1 * 4 = 4
What I'd like to do is reverse said output to look like this:
1 * 4 = 4
2 * 4 = 8
3 * 4 = 12
The code is here below. I've thought about using slicing such as [:-1] but I'm not sure how to implement it. Assistance would be appreciated. Thanks.
number = input("Enter the number for 'number ': ")
N = input("Enter the number for 'N': ")
if number .isdigit() and N.isdigit():
number = int(number )
N = int(N)
while int(N) > 0:
print('{} * {} = {}'.format(N,number ,N*number))
N = N - 1
else:
print ('Invalid input')
I would instead recommend using a for loop with the range method as such:
for i in range(1, N+1):
print('{} * {} = {}'.format(i,number ,i*number)
I think, you can let the program count upwards.
N = int(N)
i = 1
while int(N) >= i:
print('{} * {} = {}'.format(N,number ,N*number)) # TODO: adjust formula
i = i + 1
Reversing a list is [::-1] (you missed ':') and you are parsing twice the same number N, but in this case you can do
counter = 0
while counter != N:
print('{} * {} = {}'.format(N,number ,N*number))
counter = counter + 1
You could change your while loop like so:
int i = 0
while i < N:
print('{} * {} = {}'.format(i,number ,i*number))
i = i + 1
If you absolutely have to do it using while loops, perhaps something like the following will work.
m = 1
while m <= N:
#Do stuff with m
m += 1
Although I much suggest using a for loop instead.

Python == Function to Count All Integers Below Defined Variable, Inclusive [duplicate]

This question already has answers here:
Python Memory Error while iterating to a big range
(3 answers)
Closed 6 years ago.
Sorry I have to ask such a simple question, but I've been trying to do this for a while with no luck, despite searching around.
I'm trying to define a function that will get user input for X, and then add every integer from 0 to X, and display the output.
For example, if the user inputs 5, the result should be the sum of 1 + 2 + 3 + 4 + 5.
I can't figure out how to prompt the user for the variable, and then pass this variable into the argument of the function. Thanks for your help.
def InclusiveRange(end):
end = int(input("Enter Variable: ")
while start <= end:
start += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, start))
Just delete argument "end" from function header and use your function.
InclusiveRange()
or define code in other way:
def InclusiveRange(end):
while start <= end:
start += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, start))
end = int(input("Enter Variable: ")
InclusiveRange(end)
Here's an itertools version:
>>> from itertools import count, islice
>>> def sum_to_n(n):
... return sum(islice(count(), 0, n + 1))
>>>
>>> sum_to_n(int(input('input integer: ')))
input integer: 5
15
You should take the user input out of the function, and instead call the function once you have received the user input.
You also need to store the sum in a separate variable to start, otherwise you're only adding 1 each iteration. (I renamed it to index in this example as it reflects it's purpose more).
def InclusiveRange(end):
index = 0
sum = 0
while index <= end:
sum += start
index += 1
print("The total of the numbers, from 0 to %d, is: %d" % (end, sum))
end = int(input("Enter Variable: "))
InclusiveRange(end)
Demo
Instead of using a loop, use a range object, which you can easily send to sum(). Also, you're never actually using the passed end variable, immediately throwing it away and binding end to a new value. Pass it in from outside the function.
def inclusive_range(end):
num = sum(range(end+1))
print("The total of the numbers, from 0 to {}, is: {}".format(end, num))
inclusive_range(int(input("Enter Variable: ")))
You can also use a math formula to calculate the sum of all natural numbers from 1 to N.
def InclusiveRange(end):
''' Returns the sum of all natural numbers from 1 to end. '''
assert end >= 1
return end * (end + 1) / 2
end = int(input("Enter N: "))
print(InclusiveRange(end))

Categories