I've mostly been using Python 3.2 but moving on to 2.7 just for visual base purposes. I can't seem to make my loop form an endless cycle, say if the user enters the incorrect phrase, the code just breaks after inputting the wrong variable.
measure = raw_input("what form of measurement do you want to use:
(enter CM or IN): ")
while True:
if measure == str('cm'):
break
elif measure == str("in"):
break
else:
measure = input("please enter cm or in")
continue
The following code is a mashup of the code in the comments that was tested to work
measure = raw_input("what form of measurement do you want to use: (enter CM or IN): ")
while True:
if measure == 'cm':
break
elif measure == "in":
break
else:
measure = raw_input("please enter cm or in: ")
continue
What about indentation? Don't forget that indentation is the way python knows if you are still in the while/if/for/... statement.
I don't have a python interpreter right here but my guess is that it should work if you indent it right. Moreover, it would be much better to use another condition like while measure != "cm" and measure != "in"
measure = raw_input("blablabla")
while measure != "cm" and measure != "in":
measure = raw_input("please enter cm or in: ")
measure = raw_input("what form of measurement do you want to use: (enter CM or IN): ")
b = True
while b:
if measure == 'cm' or measure == "in":
b = False
else:
measure = raw_input("please enter cm or in ")
Just change your last input to raw_input
You can rework your code so that you have a single prompt for data. Remove unneeded str conversions, test using upper case, and just check if the entered value is in a list of wanted values. (and get rid of that syntax error you get by putting the string on multiple lines)
while True:
measure = raw_input("what form of measurement do you want to use:"
" (enter CM or IN): ").strip()
if measure.upper() in ("CM", "IN"):
break
print("Incorrect input, try again")
When I tried it you were throwing an error by trying to use input over raw_input in your else block. Try the below:
measure = raw_input("what form of measurement do you want to use:
(enter CM or IN): ")
while True:
if measure == str('cm'):
break
elif measure == str("in"):
break
else:
measure = input("please enter cm or in")
continue
Even better, to avoid using break or continue, you can use the below, which simplifies your logic and takes upper and lower case into account:
measure = raw_input("what form of measurement do you want to use: (enter CM or IN): ").lower()
while measure != 'cm' and measure != 'in':
measure = raw_input("please enter cm or in").lower()
Related
I want it to say welcome, ask for the user input (a,b,c), validate the user input and if the validation returns that the input is reasonable then carry out the quadratic formula on a,b,c. I suspect the problem is in the while-loop. The program just welcomes, asks for input then says welcome again and so on.
from math import sqrt
def quadratic_formula(a,b,c):
a=float(a) #The quadratic formula
b=float(b)
c=float(c)
x1_numerator = -1*b + sqrt((b**2)-4*(a*c))
x2_numerator = -1*b - sqrt((b**2)-4*(a*c))
denominator = 2*a
x1_solution = x1_numerator/denominator
x2_solution = x2_numerator/denominator
print("x= "+str(x1_solution)+" , x= "+str(x2_solution))
def number_check(a,b,c,check): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
check == False
else:
check == True
check = False
while check == False:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
number_check(a,b,c,check)
else:
quadratic_formula(a,b,c)
You are correct in your suspicion. You have a problem in your while loop. does not work the way your code assumes.
Instead you need to write something like:
def number_check(a,b,c): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
check = False
else:
check = True
return check
check = False
print("Welcome to the Quadratic Equation Calculator!")
while check == False:
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
check = number_check(a,b,c)
quadratic_formula(a,b,c)
Note, that in addition to changing the while loop you also need to update number_check as input parameters are not updated in calling scope. Instead the function has to explicitly return the updated value.
Try using return, not attempting to modify a global variable.
There's a way to use global variables (see global statement), but it's not necessary for this code.
The check variable itself isn't really necessary, though
def number_check(a,b,c):
a=float(a)
b=float(b)
c=float(c)
return (b**2)-4*a*c >= 0 # return the check
while True:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
if not number_check(a,b,c):
print("The values you have entered result in a complex solution. Please check your input.")
else:
break # getting out of the loop
There are two problems with the way you're using the check variable in the number_check function.
First, you're not assigning new values to it, because you're using == (which tests equality) rather than =.
But also, since it's a parameter variable, it's local to the function. So assigning it inside the function does not modify the global variable that you test in the while loop. Rather than use a global variable, you can simply test the result of number_check directly, and use break when you want to end the loop.
If you make this change, you need to move the call to quadratic_formula out of the else: clause, because that's only executed when the while condition fails, not when we end the loop with break.
def number_check(a,b,c): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
return False
else:
return True
while True:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
if number_check(a,b,c):
break
quadratic_formula(a,b,c)
I'm new to python, and I was wondering how I could recall a function until the user gives invalid input.
Here's a sample of code:
start = input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. "
"\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. "
"\nIf you would like to exit, type 'exit':")
def main_function(start):
while start.lower() != "exit":
if start.lower() in "squares":
initial = input("What is the initial constant for the sum of the squares: ")
terms = input("Number of terms: ")
if start.lower() in "cubes":
initial = input("What is the initial constant for the the sum of the cubes: ")
terms = input("Number of terms: ")
if start.lower() in "power":
initial = input("What is the initial constant for the the sum: ")
terms = input("Number of terms: ")
else:
print("Program halted normally.")
quit()
main_function(start)
What I am trying to get it to do is to reprompt 'start' if the user inputs a proper input, and then get it to run through the function again. I have tried putting 'start' within the function above and below the 'else' statement, but it never accepts the new input.
I would do it like this, define the start input in a method and call it inside the loop, when it's equal to "exit" than break the loop.
Also use elif, this way if the first condition statement is True than you won't check the others, unless that what you want of course.
def get_start_input():
return input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. "
"\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. "
"\nIf you would like to exit, type 'exit':")
def main_function():
while True:
start = get_start_input()
if start.lower() == "squares":
initial = input("What is the initial constant for the sum of the squares: ")
terms = input("Number of terms: ")
elif start.lower() == "cubes":
initial = input("What is the initial constant for the the sum of the cubes: ")
terms = input("Number of terms: ")
elif start.lower() == "power":
initial = input("What is the initial constant for the the sum: ")
terms = input("Number of terms: ")
elif start.lower() == "exit":
print("Program halted normally.")
break
main_function()
EDIT:
As dawg wrote in comment, it's preferred to use here == instead of in because you can have several matches and ambiguous meanings.
I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list.
I want to be able to find the mean of all the numbers that are in the list and print out the result.
And in the String section I want to be able to print out everything within the string and its length.
User types 'save' to exit and if input is valid that's caught.
Numbers = []
String = []
while(True):
user_input = input("What's your input? ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(user_input)
for i in range(len(Numbers)):
Numbers[i] = int(Numbers[i])
print(sum(Numbers)/len(Numbers)
elif isinstance(user_input, str):
String.append(user_input)
print(String)
print (len(String)-1)
else:
print("Invalid input.")
break
#use isalpha to check enterted input is string or not
#isalpha returns a boolean value
Numbers = []
String = []
while(True):
user_input = input("input : ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(int(user_input))
print(sum(Numbers)/len(Numbers))
elif user_input.isalpha():
String.append(user_input)
print(String)
print (len(String))
else:
print("Invalid input.")
break
There is good thing called statistics.mean:
from statistics import mean
mean(your_list)
You are using Length, which has not been defined. I think what you wanted was
print(sum(Numbers)/len(Numbers))
and you probably don't want it inside the loop, but just after it (although that might be another typo).
I found other more convenient way to produce the mean: Use statistics model and output the mean.
#import useful packages
import statistics
#Create an empty list
user_list = []
#get user request
user_input = input("Welcome to the average game. The computer is clever enough to get the average of the list of numbers you give. Please press enter to have a try.")
#game start
while True:
#user will input their number into a the empty list
user_number = input("Type the number you want to input or type 'a' to get the average and quit the game:")
#help the user to get an average number
if user_number == 'a':
num_average = statistics.mean(user_list)
print("The mean is: {}.".format(num_average))
break #Game break
else:
user_list.append(int(user_number))
print(user_list)
Just started python a few hours ago and stumbles across a problem.
The blow snippet shows that initially I store a userInput as 1 or 2 then execute a if block. Issue is that the code jumps straight to else (even if i type 1 in the console window).
I know Im making a simple mistake but any help will be appreciated.
using Python 3.5 === running in Visual Studio 2015 === specifically cPython
userInput = float(input("Choose 1 (calculator) or 2 (area check)\n"))
if(userInput =='1') :
shape = input("Please enter name of shape you would like to calculate the area for\n")
if(shape == 'triangle') :
base = int(input("Please enter length of BASE\n"))
height = int(input("Please enter HEIGHT\n"))
print("The area of the triangle is %f" % ((base * height)*0.5))
elif (shape == 'circle') :
radius = int(input("Please enter RADIUS\n"))
print("The Area of the circle is %f" % ((radius**2)*22/7))
elif (shape == 'square') :
length = int(input("Please Enter LENGTH\n"))
print("The area of the square is %f" % ((length**2)*4))
else :
initial1 = float(input("Please enter a number\n"))
sign1 = input("please enter either +,-,*,/ \nwhen you wish to exit please type exit\n")
initial2 = float(input("Please enter number 2\n"))
if(sign1 == '+') :
answer = float(initial1) + float(initial2)
print(answer)
elif(sign1 == '*') :
answer = float(initial1) * float(initial2)
print(answer)
elif(sign1 == '-') :
answer = float(initial1) - float(initial2)
print(answer)
elif(sign1 == '/') :
answer = float(initial1) / float(initial2)
print(answer)
PS. if [possible] could you keep the help as basic as possible as I wanna make sure i understand the basics perfectly.
Thanks for all the help!! :D
You are converting your input to float but checking for the string of the number. Change it to:
If userInput == 1.0:
Or better yet, keep it the way it is and just don't convert your user input to float in the first place. It is only necessary to convert the input to float or int if you want to do math on it. In your case you are just using it as an option, so you can keep it as a string:
userInput = input("Choose 1 (calculator) or 2 (area check)\n")
P.S. make sure to be very careful with indentation in Python. I assume your indentation is correct in your code editor, but also take care when pasting into this site. You have everything on the same level here, but some of your if blocks will need to be indented further in order for your program to work properly.
After 4th line, even if u type something else other than yes, it still prints okay?
x = input("Enter any number of your choice: ")
print("the number you picked is", x)
yes = x
input(" right? : ")
if yes:
print("ok")
else:
print("you liar")
Unless you don't enter anything when you prompt for this:
x = input("Enter any number of your choice: ")
if yes: # it's always going to be true
Also this is not doing anything:
input(" right? : ")
you need to assign it to a variable
I think what you want is this:
sure = input(" right? : ")
if sure == 'yes':
You may want to use isnumeric() in case you want to check for a number.
Some documentation on isnumeric() is located at http://www.tutorialspoint.com/python/string_isnumeric.htm
At the moment, you are basically just checking the existence of the variable yes.
BTW: The output for checking up on the number can be rewritten to a formatted statement as follows:
print("The number you picked is {:d} right?".format(x))
Checking, if the user answers with a "yes", can be done easily as well:
yes = input("The number you picked is {:d} right?".format(x))
if (yes == "yes"):
print("ok")
else:
print("you liar")
In case of python2.x you should use raw_input() instead of input(), which is fine for python3.
You want to check what the user is saying for the "Right?" prompt:
x = input("Enter any number of your choice: ")
print("the number you picked is", x)
yes = input(" right? : ") # capture the user input
if yes == "yes": # check if the user said yes
print("ok")
else:
print("you liar")