Run while loop one extra time after condition is met - python

I am making an area calculator to help me understand the basics of Python, but I want to do some type of validation on it - if a length is less than zero, then ask again.
I've managed to do this with the 'validation' code inside the function for the shape (e.g. inside the 'square' function) but when I put the validation code in a separate function - 'negativeLength,' it doesn't work. This is my code in the separate function:
def negativeLength(whichOne):
while whichOne < 1:
whichOne = int(input('Please enter a valid length!'))
When I run this by calling 'negativeLength(Length)' it will ask me for the length again (as it should) but when I enter the positive length, the condition is met and so the actual loop does not run.
I have also tried (after following Emulate a do-while loop in Python?)
def negativeLength(whichOne):
while True:
whichOne = int(input('Please enter a valid length!'))
if whichOne < 1:
break
... but that doesn't work either.
I've put the parameter as 'whichOne' because the circle's 'length' is called Radius, so I'd call it as negativeLength(Radius) instead of negativeLength(Length) for a square.
So is there any way to make the while loop finish after the 'whichOne = int(input...)'?
Edit: I'm using Python 3.3.3

The code you've written works, as far as it goes. However, it won't actually do anything useful, because whichOne is never returned to the caller of the function. Note that
def f(x):
x = 2
x = 1
f(x)
print(x)
will print 1, not 2. You want to do something like this:
def negative_length(x):
while x < 0:
x = int(input('That was negative. Please input a non-negative length:'))
return x
x = input('Enter a length:')
x = negative_length(x)

I'm going to assume you're using Python 3. If not, you need to use raw_input() rather than input().
The code that I usually use for this would look like:
def negativeLength():
user_input = raw_input('Please enter a length greater than 1: ')
if int(user_input) > 1:
return user_input
input_chk = False
while not input_chk:
user_input = raw_input('Entry not valid. Please enter a valid length: ')
if int(user_input) > 1:
input_chk = True
return user_input
Which should do what you want.

Related

Python How to break loop with 0

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

How to display an integer many times

I'd like to create a function that add 2 to an integer as much as we want. It would look like that:
>>> n = 3
>>> add_two(n)
Would you like to add a two to n ? Yes
The new n is 5
Would you like to add a two to n ? Yes
the new n is 7
Would you like to add a two to n ? No
Can anyone help me please ? I don't how I can print the sentence without recalling the function.
The idea is to use a while loop within your function that continues to add two each time you tell it to. Otherwise, it exits.
Given that knowledge, I'd suggest trying it yourself first but I'll provide a solution below that you can compare yours against.
That solution could be as simple as:
while input("Would you like to add a two to n ?") == "Yes":
n += 2
print(f"the new n is {n}")
But, since I rarely miss an opportunity to improve on code, I'll provide a more sophisticated solution as well, with the following differences:
It prints the starting number before anything else;
It allows an arbitrary number to be added, defaulting to two if none provided;
The output text is slightly more human-friendly;
It requires a yes or no answer (actually anything starting with upper or lower-case y or n will do, everything else is ignored and the question is re-asked).
def add_two(number, delta = 2):
print(f"The initial number is {number}")
# Loop forever, relying on break to finish adding.
while True:
# Ensure responses are yes or no only (first letter, any case).
response = ""
while response not in ["y", "n"]:
response = input(f"Would you like to add {delta} to the number? ")[:1].lower()
# Finish up if 'no' selected.
if response == "n":
break
# Otherwise, add value, print it, and continue.
number += delta
print(f"The new number is {number}")
# Incredibly basic/deficient test harness :-)
add_two(2)
You can use looping in your add_two() function. So, your function can print the sentence without recalling the function.
The above answer describes in detail what to do and why, if you're looking for very simple beginner-type code that covers your requirements, try this:
n = 3
while True:
inp = input("Would you like to add 2 to n? Enter 'yes'/'no'. To exit, type 'end' ")
if inp == "yes":
n = n + 2
elif inp == "no":
None
elif inp == "end": # if the user wants to exit the loop
break
else:
print("Error in input") # simple input error handling
print("The new n is: ", n)
You can wrap it in a function. The function breaks once the yes condition is not met
def addd(n):
while n:
inp = input('would like to add 2 to n:' )
if inp.lower() == 'yes':
n = n + 2
print(f'The new n is {n}')
else:
return
addd(10)

Python - Function to check if user input matches a condition

I'm writing a script that is asking for user to input a number between 1-10, the script will then call the function Size and will return true if the number is greater or equal to 5 and false if not. However, I seem to have run into a bit of a wall, I get an error asking me to define x, this is my code currently.
def Size(x):
if x >= 5:
print("True")
else:
print("False")
x = int(input("Please enter a number greater than 5"))
Size(x)
You declared user input x in the Size function. X should be an outside size function
def Size(x):
if x >= 5:
print("True")
else:
print("False")
x = int(input("Please enter a number greater than 5"))
Size(x)
Or if you want to take user input in Size function then initialize x in Size function and pass just Size function then follow the second answer
You were close, you need to correct 3 things in your code.
Ask user for input before doing checks in your function.
Remove variable passed in your user defined function.
You need to change name of your function for safer side to make it more meaningful, so I changed it to funcSize.
#!/usr/bin/python3
def funcSize():
x = int(input("Please enter a number greater than 5: "))
if x >= 5:
print("True")
else:
print("False")
funcSize()
Define x outside the function. Rest of the code is correct.
def Size(x):
if x >= 5:
print("True")
else:
print("False")
x = int(input("Please enter a number greater than 5"))
Size(x)
The error occured because I didn't fix my indentation after the false statement.

Python: Issue with Elif Break

I'm trying to make a simple program that will take all of your lottery numbers, and compare them (using set intersect) with the winning numbers that you input.
I've gotten the groundwork laid where you enter your numbers, it gets submitted to a sublist, which will then be converted into five separate sets, which will be used to compare. However, when you run the script, the while loop will not break when the length of the list is 5 (this is the goal).
Can someone explain what I'm doing wrong? Or maybe even a better way of working this whole program. I'm relatively new to the world of Python, I'm just diving in, and trying to make this program work.
# Start Program
def set_convert(list):
conversion = set(list)
return conversion
def comparison(winning_numbers, my_numbers):
pass
def main():
print('Welcome to the Lottery Checker v1.0!')
winning_numbers = [int(x) for x in input('Enter the winning numbers(Sep w/ Spaces): ').split()]
winning_set = set_convert(winning_numbers)
my_numbers = []
while True:
numbers = [int(x) for x in input('Enter your numbers(Sep w/ Spaces Max: 5): ').split()]
if len(numbers) == 6:
my_numbers.append(numbers)
print('Added! Want to add more?')
elif len(my_numbers) == 5:
break
else:
pass
else:
pass
print('Here are your numbers: {}. Good luck! :-)'.format(my_numbers))
main()
Replace
elif len(my_numbers) == 5:
with
elif len(numbers) == 5:
Also, it is advisable that you don't use the keyword list as an argument for the function set_convert. Rather, define it as:
def set_convert(mylist):
conversion = set(mylist)
return conversion
And finally, you don't need to pass in my_numbers and winning_numbers into the function comparison as arguments since they are available in the outer scope.

How do I make my script take only numeric inputs without screwing it up

I've been banging my head against the wall with this task and I can't seem to figure it out for the life of me.
I want to write a script that would prompt a user to input a number and store that number in a list every time after they input the number. When the user would just press enter and not input anything, the script would then print out the highest number in the list.
This is what I wrote so far:
x = 0
mylist = []
while x != '':
x = input("enter a number:")
mylist.append(x)
if x == '':
print(max(mylist))
There are two problems with this code that I can see:
The user can input a string (I tried fixing that by saying x = int(input(...), but that only lead to a new error:
ValueError: invalid literal for int() with base 10: ''
print(max(mylist)) only prints out the number with the largest initial integer. For instance, if the user inputs 51 and 112, it would print out 51.
Thank you for taking your time in helping me out.
Use a different variable to test the While. Check isnumeric() for the input, and if it is numeric, convert it as you append it to your array:
keepMoving = True
mylist = []
while keepMoving:
x = input("enter a number:")
if x.isnumeric():
mylist.append(int(x))
else:
keepMoving = False
print(max(mylist))
I suggest you use a try statement to check if the input is an integer. The following is an implementation which attempts to convert the user input into an integer, and append that to the list. In the result of a ValueError (a non-int input), it will print the largest integer in the list. Using raw_input instead of input is also a good practice here, to prevent python from trying and failing to convert the input on its own.
x=0
mylist=[]
while x!='':
x = raw_input("enter a number:")
try:
x = int(x)
mylist.append(x)
except ValueError:
if x == '':
print(max(mylist))
This prevents the user from adding non-integers to the list, and is a better way to handle unexpected user input. As an added bonus, this method also makes it easy to add more conditions in the future.

Categories

Resources