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

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.

Related

Regarding the def and return function in python

I was writing a program to write the multiplication table of number given by the user.
Here's my code:
def mul_table(n):
for i in range(1,11):
print(n,"x",i,"=",(n * i))
i = i + 1
return(n)
x = int(input("Enter the number: "))
x1 = mul_table(x)
print(x1)
But in the output it shows the number entered by the user also in the end like this (I know have written the value after "return" but if I leave it empty then it shows None, so how can I get rid of this?):
Enter the number: 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
**5**
Can anyone tell me that how can the program return nothing (absolutely nothing, not even the "None" text or the number entered by the user) in PYTHON 3.9.1 ?
Your mul_table function handles the printing itself. It needs no return value, and you shouldn't print it even if it exists - you should just call the function:
def mul_table(n):
for i in range(1,11):
print(n,"x",i,"=",(n * i))
i = i + 1
# return statement removed here
x = int(input("Enter the number: "))
mul_table(x) # No need to capture the return value or print it
The problem is that mul_table method is returning n and you are printing it with print(x1). Remove this call to print if you don't need it.
There are several issues, here is a working version
def mul_table(n):
for i in range(1,11):
print(n,"x",i,"=",(n * i))
x = int(input("Enter the number: "))
mul_table(x)
You print inside the function, so you don't need to call mul_table in a print statement
You also don't need a return statement in the function (though it returns None if you omit the return statement or use a return statement without a return value)
i = i+1 inside the function is wrong, you are using a for statement where i gets values 1, 2, ..., 10 successively.

Python STDIN for multiple values

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.

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.

Python adding a string after range

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!

Python returning true when false when using greater than sign [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
okay so I am trying to see if a number is greater than 1 less than 0 or equal to nothing then to exit. here is what I have so far.
def main():
print("This program illustrates a chaotic function")
x = raw_input("Enter a number between 0 and 1: ")
if x == "" or x < 0 or x > 1:
print("bad person")
exit()
else:
x = eval(x)
for i in range(10):
x = 3.9 * x * (1-x)
print(x)
main()
raw_input()
my code keeps printing bad person when I type in 0.5 even though that is greater that 0 and less than 1. I feel like this is some stupid error but i dont know. Any help would be great. Thanks
val = None
while val is None or val < 0 or val > 1:
try:
val = float(raw_input("Enter a number between 0 and 1: \n"))
except ValueError:
print("You must enter a number between 0 and 1.")
for i in range(10):
val = 3.9 * val * (1 - val)
print(val)
This way you don't have to use exit(), it won't break the while loop until it gets a number between 0 and 1. It will also keep going incase the user enters a char or anything else.
Probably the cause of the error is that you cannot compare strings (as returned by raw_input) with numbers in a meaningful way. So you should convert the input to a number - in this case you want a float:
x = float(raw_input("Enter a number between 0 and 1: "))
and then you don't need that line anymore:
x = eval(x)

Categories