I am still newish to programming and I'm just developing simple programs to automate routine office work.
I have the most barebones code written but whenever I try to add a while loop it breaks the code and causes the program to close after I enter a value for Y. The print text after entering the Y value never appears. I have my code listed below.
Everything works fine until I try to throw it into a while loop, then it stops working. Is there something I am missing here?
Removing the while loop and having everything work again
import os
import subprocess
import time
import pyautogui
x=15
y=10
while x != 333:
print("test")
print("15 - 10 is",x-y)
print("Okay now tell me what X should be")
x = input("Enter a numerical value for X: ")
print("Excellent! Now let's do Y")
y = input("Enter a numerical value for Y: ")
print("Okay now let's compare X and Y")
#don't forget to indent!
if x > y:
print("X is greater than Y!")
elif y > x:
print("Y is greater than X!")
else:
print("X is equal to Y!")
print(x, y)
time.sleep(2)
input("Press Enter to continue...")
input returns a string, so when the loop comes back around and tries to print x-y, it crashes because you can't substract strings.
Related
The loop starts with two variables, let's call them X and Y, both at 0. The user is prompted to enter a number to add to X, then a number to add to Y. The loop repeats itself, letting the user continue to add to both variables, until the user wants it to stop -- I guess they could enter 'add' as one of the inputs?
I also need it to ask for the input again if the user inputs anything other than a digit, but only if it's also not 'add'. If it's 'add', the loop ends, and both totals are displayed. If the input is a float or int, the loop proceeds. Otherwise, it prompts the input again. And this is for each of the two inputs.
I can do either of these things separately, but I'm having trouble incorporating both requirements into the same loop structure.
So far, my code basically looks like this:
while (x != 'add') and (y != 'add'):
# ask input for x
if x != 'add':
#ask input for y
if (x != 'add') and (y != 'add'):
# operations that add inputs to running variables
else:
pass
else:
pass
# print both variable totals here
My first issue is that the user is supposed to be entering digits, while the code is also checking for a string. How would I resolve that? My second issue is that I'm not sure how to reprompt each input if the input is not either a digit or 'add'.
Welcome to SO!
You've generally got the right idea, here's how you might translate that into code.
x_total = 0
y_total = 0
while True:
first_input = input('Enter the next value of x: ')
if first_input == 'add':
break
x_total += float(first_input)
second_input = input('Enter the next value of y: ')
if second_input == 'add':
break
y_total += float(second_input)
print('x = ', x_total)
print('y = ', y_total)
Note that in Python we can convert a string number_string = '1239' into a float by calling the type float as number = float(number_string ). The same applies to int for integers. The documentation contains useful recipes and usage examples and is typically where I start when I'm unsure what I need.
Since you mentioned that you're new to Python, I'll mention that more than other languages, strong idioms exist in Python. The Zen of Python is a sort of introduction to this idea. It's frequently useful to ask 'is this Pythonic?' when you first begin, as there are probably established ways to do whatever you're doing which will be clearer, less error-prone, and may run faster.
This slide deck is a good look at some Pythonisms, it's tailored to Python 2.x so some syntax is different, but the ideas are just as relevant in 3.x.
A more Pythonic, (though possibly less understandable way to new Python users) of fulfilling your original request is to use any unexpected value or escape character to quit the adding process.
x_total = 0
y_total = 0
while True:
try:
first_input = input('Enter the next value of x: ')
x_total += float(first_input)
second_input = input('Enter the next value of y: ')
y_total += float(second_input)
except (ValueError, EOFError):
break
except KeyboardInterrupt:
print()
break
print('x =', x_total)
print('y =', y_total)
Now users of your program can type any non-float value to exit, or even use the key interrupts (ctrl + Z or ctrl + C for example). I ran it in PowerShell to give you some usage examples:
With exit, a common idiom:
Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y: exit
x = 4.0
y = 2.0
Your original case, with add:
Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y: add
x = 4.0
y = 2.0
With ctrl + Z:
Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y: ^Z
x = 4.0
y = 2.0
With ctrl + C:
Enter the next value of x: 1
Enter the next value of y: 2
Enter the next value of x: 3
Enter the next value of y:
x = 4.0
y = 2.0
You can apply an "endless" loop, and break it with a string input,e.g "add" or any other, or pressing Enter:
while True:
try:
x=float(input("give x or enter to stop: "))
X+=x
y=float(input("give y or enter to stop: "))
Y+=y
except ValueError:
print(X,Y)
break
I know you asked to output the results after the loop but I decided to do it before Python breaks the loop. This is the code:
print("If you want to end the program input 'add'.")
x_value = 0
y_value = 0
while True:
x_input = str(input("Value of X:"))
if x_input != 'add':
y_input = str(input("Value of Y:"))
if (x_input != 'add') and (y_input != 'add'):
x_value += int(x_input)
y_value += int(y_input)
elif y_input == "add":
x_value += int(x_input)
print("Value of X:", str(x_value))
print("Value of Y:", str(y_value))
break
elif x_input == "add":
print("Value of X:", str(x_value))
print("Value of Y:", str(y_value))
break
Hope it helps :)
This question already has answers here:
Python: 'break' outside loop
(5 answers)
Closed 6 years ago.
When running the program, the user is asked to input a number. If the number is 1, quit the program. If the number is not 1, print the number.
I wonder how to realize this.
I am using python 3.5.
My code is like this. I always get an error: 'break' outside loop
How can I fix this?
x = input('Please input a number: ')
if x == '1':
print('quit')
break
else:
continue
print(x)
You get the error break outside loop because the keyword break is used to break out of a loop. You are using it outside of a loop so you get the error. To exit the application you should not use break. Instead you should use:
sys.exit(0)
So now your code should look like this:
x = input('Please input a number: ')
if x == '1':
print('quit')
sys.exit(0)
else:
print(x)
You do not need the continue in the else statement either. You can just simply leave the else statement empty and the program will continue on or you can put print(x) inside of the else statement like I did with your code.
That's not how you quit an application. Try sys.exit(error) where error is the error number.
break allows you to escape loops, like this:
while True:
line = 'test'
if line = 'test':
break
print "now I'm not in the loop"
You don't have a loop in your code, so you'll need to add a while statement. Set the condition to True to have it always run. You also don't need the else continue statement since that would skip the print(x). X is automatically being cast to an integer, so cast it to a string.
while True:
x = input('Please input a number: ')
if str(x) == "1":
print('quit')
break
print(x)
i'm just writing a simple program that should give me a random integer between 1 and 10 if i input the value of 'r'in code. here's what i have:
import sys, random
from random import *
def randomly():
return (randint(1, 10))
while True:
x = input("input string ")
x = str(x)
print (x)
if x == 'r':
print ("your generated number is", randomly())
else:
break
i know there's just something small i'm overlooking. but i can't figure out what. the randomly function works. and if i replace the 'r' conditional with an integer (i used 1) convert x with int(x) and then input 1 the program works fine. like so:
import sys, random
from random import *
def randomly():
return (randint(1, 10))
while True:
x = input("input number ")
x = int(x)
print (x)
if x == 1:
print ("your generated number is", randomly())
else:
break
for some reason the if conditional won't respond to my string. i tried x.lower() and it still won't work, while it's true that just using the method i described before with the integer would work fine. it frustrates me that my code won't work the way i want it to. for what it's worth i checked len(x) and it says 2 when i input a single character(r). i'm fairly novice to python but i have the knowledge i need, at least, to write a program like this. any help would be greatly appreciated.
i'm using visual studio 2015
python environment: python 3.2
this is my first question here. i searched to the best of my capabilities and couldn't find an answer. i apologize in advance if there is anything wrong with my question.
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.
I'm running the following code from the command line (python filename.py) and it wont terminate. I've tried the code outside of a procedure and have tried the procedure in an online interpreter, so I don't think it's the the algorithm. What am I doing wrong?
n = raw_input("Enter a number: ")
def print_multiplication_table(n):
x = 1
while x <= n:
y = 1
while y <= n:
z = x * y
print x, " * ", y, " = ", z
y += 1
x += 1
print_multiplication_table(n)
You should convert the number received from raw_input into an integer. Right now it's being compared as a string.
An easy (but probably bad) way to do this:
n = int(raw_input("Enter a number: "))
There is a problem with the raw_input command. I have a similar code myself (guess we're both following the Udacity course). I tried to add the raw_input line to my code, and it ended up in an infinite loop too.