Why this WHILE loop does not end? [Python] [duplicate] - python

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
im trying to create a multiple values calculator in Python, using While, For/In sentences with lists
numbers = []
out = 0
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
if out2 == 1:
out == 1
#In theory if out == 1 the while loop should end and go to:
for add in numbers:
add = numbers
print(add)
I tried using While Not sentence, but i get an obvius mistake. I suppose this is a pretty dumb error of comprehention i have, but i can't really get what am i doing wrong. I'll be very glad if u help me with this.

First of all, variable assignment should be done with = not ==. Your problem is that in the second input() (where you let user choose will he/she stay or exit), you need to convert the input to int from string first, OR check by the string representation of the number (fail-safe):
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
if out2 == '1':
out = 1
However, best way to break out a loop is to use break:
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
if out2 == '1':
break

Apart from the errors pointed out in the other 2 answers, you are getting input from the user as a str and not converting it to an int.
So it never hits the if condition and therefore your program doesn't end.
Please try this
numbers = []
out = 0
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
print(type(out2))
if int(out2) == 1: # Convert the out2 to an int here
print(f" Inside if condition")
out = 1 # Use an assignment operator here

Related

Need Help Dealing with inputs [duplicate]

This question already has answers here:
How to append multiple values to a list in Python
(5 answers)
Closed 7 months ago.
Begginer Question, So i have this problem where i receive a lot of inputs in different lines like:
Inputs:
1
2
0
2
1
And i want to sum them or store them in any kind of list to Sum them latter, how can i do this?
I mean, i could store a variable for each one of them like:
a1 = int(input())
a2 = int(input())
ax = int(input())
....
and then
result = a1+a2+ax...
print(result)
but that's not pratical. Someone can explain me on how to store and sum them in a list?
i think that i could do something like this too
x = int(input())
and use
x += x
Just use python lists:
inputlist = []
for i in range(5):
inputlist.append(int(input))
result = sum(inputlist)
Note, I just put a 5 there to ask for 5 values. Ask however many inputs you want.
you could use a while loop, or a for loop for it. If you are provided the number of inputs in advance in a variable x, you can start with a for loop.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
answer = 0
for i in range(x):
answer += int(input())
print("Answer is", answer)
If you do not know the amount of inputs in advance, you can implement a while loop that will take input until a non-integer input is given.
answer = 0
while True:
x = input()
try:
x = int(x) # Tries to convert the input to int
except ValueError: # If an error occurs, ie, the input is not an integer.
break # Breaks the loop and prints the answer
# If all goes fine
answer += x
print("Answer is", answer)
And obviously, we also have a classic alternate to all this, which is to use python list, these can store numbers and we can process them later when printing the answer. Although, I would have to say if the number of input is large, then the most efficient manner is to use either of the above solution due to their memory footprint.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
inputs = []
for i in range(x):
inputs.append(int(input()))
print("Answer is", sum(inputs))
I'm also a beginner, but here's a solution I came up with:
new_list = []
for entry in range(10):
new_list.append(int(input()))
print(sum(new_list))

A way to get python to receive input and sum it? [duplicate]

This question already has answers here:
Loop that adds user inputted numbers and breaks when user types "end"
(4 answers)
How to sum numbers from input?
(2 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
sorry for the stupid question, but I can't get out of this thing in any way, I'm a beginner.
I need to write a code that asks the user to write a series of int one at the time using a while function. When the user has inserted all the numbers, to stop the series he'll write a specific string. When it's done, I need the code to print the sum and the average of all the numbers inserted.
The user can't insert them all in one time, he needs to enter one at the time.
I tried something like this: but there's no way it'll work. Implementing items in a list and then operate on the list is possible, but I had no idea on how to do that more easily than summing every element each time.
(my initial code:)
count = 0
total = 0
while():
new_number = input('> ')
if new_number == 'Done' :
break
count = count + 1
total = total + number
print(total)
print(total / count)
Don't mind about data being a string or an int, as long as it's just an error that IDLE would tell me. I just would like to know what's logically wrong in my code.
Thank you in advance.
You were really close, I made a couple of changes - firstly I changed while(): to while True:, so that the loop runs until break is hit. Secondly I altered total = total + number to total = total + int(new_number) - corrected variable name and convert string returned by input() to an int. Your logic is fine.
Corrected Code:
count = 0
total = 0
while True:
new_number = input('> ')
if new_number == 'Done' :
break
count = count + 1
total = total + int(new_number)
print(total)
print(total / count)
Using a list is actually not that hard. Here's how:
Firstly make the corrections from CDJB's answer.
Create an empty list. Add each new_number to the list. Use sum() and len() to get the total and count.
nums = []
while True:
new_number = input('> ')
if new_number == 'Done':
break
nums.append(int(new_number))
total = sum(nums)
count = len(nums)
print(total)
print(total / count

Finding the next entity in a list python

I am relatively new to python and I have searched the web for an answer but I can't find one.
The program below asks the user for a number of inputs, and then asks them to input a list of integers of length equal to that of the number of inputs.
Then the program iterates through the list, and if the number is less than the ToyValue, and is less than the next item in the list the variable ToyValue increments by one.
NoOfToys=0
ToyValue=0
NumOfTimes=int(input("Please enter No of inputs"))
NumberList=input("Please enter Input")
NumberList=NumberList.split(" ")
print(NumberList)
for i in NumberList:
if int(i)>ToyValue:
ToyValue=int(i)
elif int(i)<ToyValue:
if int(i)<int(i[i+1]):
NoOfToys=NoOfVallys+1
ToyValue=int(i[i+1])
else:
pass
print(NoOfVallys)
Here is an example of some data and the expected output.
#Inputs
8
4 6 8 2 8 4 7 2
#Output
2
I believe I am having trouble with the line i[i+1], as I cannot get the next item in the list
I have looked at the command next() yet I don't think that it helps me in this situation.
Any help is appreciated!
You're getting mixed up between the items in the list and index values into the items. What you need to do is iterate over a range so that you're dealing solidly with index values:
NoOfToys = 0
ToyValue = 0
NumOfTimes = int(input("Please enter No of inputs"))
NumberList = input("Please enter Input")
NumberList = NumberList.split(" ")
print(NumberList)
for i in range(0, len(NumberList)):
value = int(NumberList[i])
if value > ToyValue:
ToyValue = value
elif value < ToyValue:
if (i + 1) < len(NumberList) and value < int(NumberList[i + 1]):
NoOfToys = NoOfVallys + 1
ToyValue = int(NumberList[i + 1])
else:
pass
print(NoOfVallys)
You have to be careful at the end of the list, when there is no "next item". Note the extra check on the second "if" that allows for this.
A few other observations:
You aren't using the NumOfTimes input
Your logic is not right regarding NoOfVallys and NoOfToys as NoOfVallys is never set to anything and NoOfToys is never used
For proper Python coding style, you should be using identifiers that start with lowercase letters
The "else: pass" part of your code is unnecessary

Need help shortening program (python beginner)

In response to the following task, "Create an algorithm/program that would allow a user to enter a 7 digit number and would then calculate the modulus 11 check digit. It should then show the complete 8-digit number to the user", my solution is:
number7= input("Enter a 7 digit number")
listnum= list(number7)
newnum=list(number7)
listnum[0]=int(listnum[0])*8
listnum[1]=int(listnum[1])*7
listnum[2]=int(listnum[2])*6
listnum[3]=int(listnum[3])*5
listnum[4]=int(listnum[4])*4
listnum[5]=int(listnum[5])*3
listnum[6]=int(listnum[6])*2
addednum= int(listnum[0])+int(listnum[1])+int(listnum[2])+int(listnum[3])+int(listnum[4])+int(listnum[5])+int(listnum[6])
modnum= addednum % 11
if modnum== 10:
checkdigit=X
else:
checkdigit=11-modnum
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
print(strnewnum)
(most likely not the most efficent way of doing it)
Basically, it is this: https://www.loc.gov/issn/check.html
Any help in shortening the program would be much appreciated. Thanks.
It might be worth it to do some kind of user input error checking as well.
if len(number7) != 7:
print ' error '
else:
//continue
Using a while loop for that top chunk might be a good starting point for you. Then you can sum the list and take the modulus in the same step. Not sure if you can make the rest more concise.
number7= input("Enter a 7 digit number: ")
listnum= list(number7)
newnum=list(number7)
count = 0
while count < 7:
listnum[0+count] = int(listnum[0+count])*(8-count)
count += 1
modnum= sum(listnum) % 11
if modnum== 10:
checkdigit=X
else:
checkdigit=11-modnum
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
print('New number:', strnewnum)
EDIT:
If you want it to print out in ISSN format, change your code after your if-else statement to this:
newnum.append(str(checkdigit))
strnewnum = ''.join(newnum)
strnewnum = '-'.join([strnewnum[:4], strnewnum[4:]])
print('ISSN:', strnewnum)
You can convert the list to contain only int elements right after the input
number7 = int(input())
Then you can perform those operations in a loop.
for i in range(len(listnum)):
listnum[i] *= (8-i)
also the sum function does the trick of performing the addition of every element in the list (if possible)
EDIT:
addedNum = sum(listNum)

making calculator in python, is this approach sensible?

I trying to learn to write in Python and am attempting to making a calculator. For this I am using an input to choose which type of calculation and then inputs for the numbers to be calculated.
print ("1. add ; 2. subtract ; 3. multiply ; 4. divide " )
print ("wat is your choise")
choise = input()
if choise == 1 :
num_1_1 = input()
num_2_1 = input()
anwsr_add = (num_1_1 + num_2_1)
print (anwsr_add)
and repetition for the rest of the options.
This however returns that anwsr_add can't be printed because it is not defined. It leads me to believe the second inputs are not valid, giving nothing equal to anwsr_add.
Is there a extra code for these input functions within an if stream or am I completely of track with this approach?
This depends on what version of python you are using.
If you are using python 3, then input() is returns a type of 'str', which leads to your error. To test this theory, try print(type(choice)) and see what type it returns. If it returns str, then there is your culprit. If not, get back to us so we can continue to debug. I've posted my approach to your problem below in python 3 just so you have a reference in case I am unable to reply. Please feel free to ignore it if you would like to write it all on your own.
choice = int(input('Enter 1 to add, 2 to subtract, 3 to multiply, 4 to divide\n'))
if 1 <= choice <= 4:
num1 = int(input('What is the first number? '))
num2 = int(input('What is the second number? '))
if choice == 1:
answer = num1 + num2
elif choice == 2:
answer = num1 - num2
elif choice == 3:
answer = num1 * num2
elif choice == 4:
# In python 3, the answer here would be a float.
# In python2, it would be a truncated integer.
answer = num1 / num2
else:
print('This is not a valid operation, goodbye')
print('Your answer is: ', answer)
The main issue I found is you are comparing a char data type to an int data type. When you ask for input from the user, it is stored as a character string by default. Character strings cannot be compared to integers, which is what you are trying to do with your if block. If you wrap the input in an int() call it will convert the char to an int data type, and can then be properly compared with your == 1 statement. Additionally, within your if statement you call input() twice, and it will also give you a character string. This means if you input 1 and 1, you will get 11 out (like a + b = ab). To fix this, also wrap those input() statements with int() calls. I fixed these problems in the code below:
choice = int(input())
if choice == 1:
num_1_1 = int(input())
num_2_1 = int(input())
anwsr_add = (num_1_1 + num_2_1)
print(anwsr_add)
Hey Dalek I've copied your code and got this result:
1. add ; 2. subtract ; 3. multiply ; 4. divide
What's your choise?
1
Traceback (most recent call last):
File "C:\Users\timur\AppData\Local\Programs\Python\Python36-32\Game.py", line 10, in <module>
print (anwsr_add)
NameError: name 'anwsr_add' is not defined
The NameError occurs because the programm trys to call anwsr_add while it executes the code below if choise == ...
You can use this code. It works. The reason why your code doesn't works is that you call anwr_add not in the if choise == ... method:
choise = input("1. add ; 2. subtract ; 3. multiply ; 4. divide. What's your choise?")
if str(choise) == '1':
print('First_num:')
num_1_1 = input()
print('Second_num:')
num_2_1 = input()
anwsr_add = (int(num_1_1) + int(num_2_1))
print (anwsr_add)

Categories

Resources