I'm attempting to get not more than 10 user inputs. The user can choose to stop giving input by inputing an empty string
container_size = []
for i in range(10):
while True:
container_size.append(float(input('What is the size of your container?: ')))
if input('What is the size of your container?: ') == '':
break
if i <= 1:
refund = 0.10
else:
refund = 0.25
print(refund)
I keep getting an error when trying to break if no input is given. What can I do? I am also getting more than 10 inputs.
You call for input() twice: once for add to container, and second time in the if. So for every iteration, you are asking for 2 inputs. Therefore you have a total of 20 inputs instead of ten. Put it in a variable, and ask if the variable is empty/add variable to container.
your break statement currently refer to the if statement and not the while, because it interacts with closest statement which is the if. You can overcome this by using flag and check it at the end of the while statement.
container_size = []
refund = []
i = 0
for i in range(10):
try:
container_size.append(float(input('What is the size of your container?: ')))
except ValueError:
break
for x in container_size:
if x <= 1:
refund.append(0.10)
else:
refund.append(0.25)
print(sum(refund))
I corrected the code already. Thank you.
Related
I don't understand why is not working on my code
def random_calculation(num):
return((num*77 + (90+2-9+3)))
while random_calculation:
num = int(input("Pleace enter number: "))
if num == "0":
break
else:
print(random_calculation(num))
Can you guide me what is wrong here, i really dont understand
You have several errors in your code:
You cannot do while random_calculation like this. You need to call the function, but since inside the loop you are already checking for a break condition, use while True instead.
Also, you are converting the input to int, but then comparing agains the string "0" instead of the int 0
Here's the corrected code:
def random_calculation(num):
# 90+2-9+3 is a bit strange, but not incorrect.
return((num*77 + (90+2-9+3)))
while True:
num = int(input("Please enter number: "))
if num == 0:
break
# you don't need an else, since the conditional would
# break if triggered, so you can save an indentation level
print(random_calculation(num))
so,when you start the loop it ask you what number you want to enter and then the code checks if the number is == to 0. IF the number is equal to 0: break the loop. IF the number is equal to any other number it prints the "random_calculation" function
I'm new to programming and I'm stuck with an exercise, I hope someone can help.
The problem is the following:
1)Write a function that repeatedly asks the user to insert a number and computes the sum of those numbers
2)When the user inserts 0, exit and print the value of the sum.
Now this is the code i managed to write, but if my variable keeps increasing the input will never b 0 and the program will run forever...
def mysum():
n=1
while n>0:
n=n+int(input('Insert a value: '))
print(n)
Now when I call the function it keeps addings the sum of the numbers the users wrote, but how can I going on with the 2nd point of the exercise?
thank you
You're close! Loop forever (while True) and break when the user gives a 0
def mysum():
n = 0
while True:
new = input('Insert a value: ')
# validate the new input can be made a number
try:
new = float(new)
except ValueError:
print('invalid input, try again')
continue
if not new: # or new == 0
break
n += new
print(n)
I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).
My question is, why does it end loop when it return value on line 5, return(int(val))?
Thank you for your attention.
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.
If you allow me, here are some modifications to your original code:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!
So here is how the program is supposed to work. The user would input something like this and the output would give them the answer.
Input:
1
2
2
1
Done
Output:
1.5
So far I was able to come up with the input question and got it to loop until you put Done.
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
else:
nums.append(int(num))
I don't know how to make the program perform the calculation to print out the average. I am very new to programming in python and I would appreciate any help I can get on fixing this program. Thanks in advance!
Break while loop when 'Done' is the input, else save the number as float. This throws an error if you try to enter 'finish'. Finally calculate and print the Average.
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done": # This has to be tested inside the while loop
break
# Only append after testing for 'Done'
nums.append(float(num)) # Ensure valid input by convert it into the desired type.
print('average: %s' % (sum(nums) / len(nums)))
It is a good practice to give the user useful error messages, when some input is not as the program needs it. It can save the user lots of trouble. If you just want to tell the user what the problem was when an invalid input is given, you can do it with a try statement as below:
nums = [] # Empty list.
while True:
num = input("Enter number, or Done to end:")
if num == "Done":
break
try:
nums.append(float(num))
except Exception:
print('Please enter a number. Input "%s" will be ignored.' % num)
print('average: %s' % (sum(nums) / len(nums)))
I am getting input from users via raw_input (using a for loop).
What code can I use to ensure that if a user presses only Enter it keeps the default values (i.e. raw_input returns an empty string '' when no value has been entered)?
So for the default values are in the form of variables:
age_years = 2
cash_earned_last_year = 1000
growth = 0.02
If i understand you correctly you need to iterate over values inserted by user and replace with an empty string if the user type only Enter key.
def values_input():
return raw_input("Please enter value or 'quit' to finish: ")
values = []
for code in iter(values_input, "quit"):
if len(code) == 0:
values +=['']
else:
values += [code]
print values
You can use an if to check if the user pressed only enter. As jonrsharpe
said, only Enter would set your input equal to empty string, that is, ''.
if user_answer_1 == '':
age_years = 2
cash_earned_last_year = 1000
growth = 0.02
If user is supposed to either press enter, or give numerous inputs, then you can use break to skip the rest of the questions if his first answer was Enter.
while True:
user_age_answer = input('\nAge?')
if user_age_answer == '':
age_years = 2
cash_earned_last_year = 1000
growth = 0.02
# Skips the rest of the questions.
break
# Here go the rest of the questions.
user_cash_answer = input('Cash?')
# And then you do what you want with the answers.
age_years = user_age_answer
# This break is used to exit loop.
break