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.
Related
I'm writing a program which should produce an output of something like this:
`Enter an integer (or Q to quit): 1
Enter an integer (or Q to quit): 2
Enter an integer (or Q to quit): 3
Enter an integer (or Q to quit): Q
(1 x 1) + (2 x 2) + (3 x 3) = 14`
So far, I've gotten the display of the equation right, but I can't seem to figure out how to actually get the total of the equation. Currently, the total displays 18 instead of the expected 14.
Here's my code so far:
`int_list = [] # initiate list
while True:
user_input = input("Enter an integer (or Q to quit): ") # get user input
if user_input == "Q": # break loop if user enters Q
break
integer = int(user_input) # convert user_input to an integer to add to list
int_list.append(integer) # add the integers entered to the list
for i in range(0, len(int_list)):
template = ("({0} x {1})".format(int_list[i], int_list[i]))
if i == len(int_list)-1:
trailing = " = "
else:
trailing = " + "
print(template, end="")
print(trailing, end="")
for i in range(0, len(int_list)):
x = (int_list[i]*int_list[i])
add = (x+x)
print(add)`
Any help would be greatly appreciated :))
Your problem exists in the here:
for i in range(0, len(int_list)):
x = (int_list[i]*int_list[i])
add = (x+x)
print(add)
Let us walk through what the code does to get a better understanding of what is going wrong.
With a list of [1, 2, 3] The for loop will iterate three times
On the first iteration, x will be assigned the value 1 because 1 * 1 is 1.
On the second iteration, x will be assigned the value 4 because 2 * 2 is 4. Notice that rather than the two values being added x's value being overwritten
On the third iteration, x will be assigned the value 9 because 3 * 3 is 9. Again the value is being overwritten.
After the loop, the variable add is created with the value x + x, or in our case 9 + 9 which is 18
This is why with the list [1, 2, 3] the value displayed is 18
Now that we have walked through the problem. We can see that the problem is overriding the value in the for loop then doubling the value before displaying it.
To fix these problems we can first remove the doubling giving the following code
for i in range(0, len(int_list)):
x = (int_list[i]*int_list[i])
print(x)
But the program still has the overriding problem so the value of a list [1, 2, 3] would be 9.
To fix this rather than overriding the value of x, let's create a new variable total that will have the result of the loop added to it every iteration rather than being overwritten.
total = 0
for i in range(0, len(int_list)):
total = total + (int_list[i]*int_list[i])
print(total)
Now let's walk through what the code does now.
With a list of [1, 2, 3] the for loop will iterate three times
On the first iteration, total will be assigned the value 1 because 0 + 1 * 1 is 1.
On the second iteration, total will be assigned the value 5 because 1 + 2 * 2 is 5. Notice how the previous value of the loop iteration is being added to the loop
On the third iteration, total will be assigned the value 14 because 5 + 3 * 3 is 14. Notice again how the previous value of the loop iteration is being added to the loop.
This gives us the correct result of 14.
One nice feature of python is the addition assignment which condentes A = A + B to A += B so it is possible to simply the following code to:
total = 0
for i in range(0, len(int_list)):
total += (int_list[i]*int_list[i])
print(total)
A reason this problem may have been so difficult is that the for loop is more complicated than it needs to be. It is possible that rather than iterating through a list of indices generated by a list of numbers then assessing the numbers from the list by their index. It is possible to iterate through the numbers directly.
With the that simplification your loop would look like this:
total = 0
for number in int_list:
total += number * number
print(total)
These changes would make your whole programme look like this:
int_list = [] # initiate list
while True:
user_input = input("Enter an integer (or Q to quit): ") # get user input
if user_input == "Q": # break loop if user enters Q
break
integer = int(user_input) # convert user_input to an integer to add to list
int_list.append(integer) # add the integers entered to the list
for i in range(0, len(int_list)):
template = ("({0} x {1})".format(int_list[i], int_list[i]))
if i == len(int_list)-1:
trailing = " = "
else:
trailing = " + "
print(template, end="")
print(trailing, end="")
total = 0 # start the total at zero as no values have been calculated yet
for number in int_list: # iterate through all values in the list
total += number * number # add to the total the number squared
print(total)
You duplicate only the last product (2 x 3 x 3 = 18).
Because you reassign x in your loop (x = (int_list[i]*int_list[i])) and than duplicate x with add = (x+x).
But you have to build the sum.
int_list = [] # initiate list
while True:
user_input = input("Enter an integer (or Q to quit): ") # get user input
if user_input == "Q": # break loop if user enters Q
break
integer = int(user_input) # convert user_input to an integer to add to list
int_list.append(integer) # add the integers entered to the list
for i in range(0, len(int_list)):
template = ("({0} x {1})".format(int_list[i], int_list[i]))
if i == len(int_list) - 1:
trailing = " = "
else:
trailing = " + "
print(template, end="")
print(trailing, end="")
x = 0
for i in range(0, len(int_list)):
x += (int_list[i] * int_list[i])
print(x)
You can try this
state= True
combi= []
while state:
user_input = input("Enter an integer (or Q to quit): ").lower()
if "q" in user_input:
state= False
else:
combi.append(int(user_input))
else:
final= sum([x+x for x in combi])
print(final)
Write a Python program to count the number of even and odd numbers from input.
count_even = 0
count_odd = 0
numbers = input()
for x in numbers:
for i in x:
if i % 2 == 0 :
count_even += 1
else:
count_odd += 1
print(count_even)
print(count_odd)
ERROR: Traceback (most recent call last):
File "main.py", line 6, in
if i % 2 == 0 :
TypeError: not all arguments converted during string formatting
First, I'm not sure why you are iterating twice over one list. Second, if you're expecting a list delinated by spaces, you need to split it into it's elements and then you need to convert each item to an integer that you can then iterate over.
count_even = 0
count_odd = 0
numbers = input()
print(numbers)
for x in numbers.split():
if int(x) % 2 == 0:
count_even += 1
else:
count_odd += 1
print(count_even)
print(count_odd)
I see a couple issues with the code. The first thing is, I don't see x and i being created or declared. The second thing is, when you do numbers = input(), the variable type of numbers is a string. You might want to change it to numbers = int(input())
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.
Hello I am having trouble inputting two numbers from stdin using the following code as I am not quite yet familiar with this feature, when I input numbers manually the code seems to work properly but I can't get sys.stdin.readline to properly work.
import sys
def k(upto):
def collatz(n):
if n < upto and lst[n] > 0:
return lst[n]
if n % 2 == 0:
val = collatz(n/2) + 1
else:
val = collatz((3*n + 1)/2) + 2
if n < upto:
lst[n] = val
return val
lst = [0]*upto
lst[1] = 1
lst[0] = 1
for i in range(mini,upto):
collatz(i)
return max(lst)
line=int(sys.stdin.readline())
maxi = max(line)
mini = min(line)
print k(maxi)
The code produces the following error: TypeError: 'int' object is not iterable. Any assistance would be appreciated.
EDIT ::: Should have mentioned only two numbers will be input, one per line.
After reading your comment, it looks like you want something like this
line = list()
for x in range(2):
line.append(int(sys.stdin.readline()))
That will read 2 lines from STDIN, convert each line to an int, and append each value to line.
The "one per line" is an important information :)
If you're reading one per line you're code is quite close - except you're reading only one line: your variable line is only one number - hence min and max can't work.
You could do something like
i1 = int(raw_input("Enter first number: "))
i2 = int(raw_input("Enter second number: "))
maxi = max(i1, i2)
mini = min(i1, i2)
...
note: If you switch to Python 3 (recommended) it's input() instead of raw_input()
old version:
What is the input? A list of integers, e.g. 2 3 5? This will be interpreted as a string "2 3 5". To convert this into integers you to have to do something like
line = [int(i) for i in sys.stdin.readline().split()]
This
- will split() the input into an array of strings ["2", "3", "5"] and then
- apply the int() conversion to each element of the array.
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!