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.
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 2 years ago.
What's poppin my coding gang. So atm I'm learning Python and I'm a totally a newbie and I face this problem. So I created a unit converting program and I was successful to make a while loop for unit and everything with the code below works just fine:
weight = int(input("Weight: "))
unit = input("(K)g or (L)bs ? ")
while unit.upper != ("K" or "L"):
if unit.upper()=="L":
converted = weight*0.45
print(f"You are {round(converted)} kilos")
break
elif unit.upper()=="K":
converted=weight//0.45
print(f"You are {converted} pounds")
break
else:
print("Invalid unit. Please type K or L: ")
unit=input()
continue
But I also wanted to experiment more and I also wanted to create a while loop for a weight input, so that it will go forever until you type any positive float or integer number, because when I run the program and in weight input I would accidently type a letter - a big red error would appear on my screen saying:
Exception has occurred: ValueError
invalid literal for int() with base 10: 'a'
line 1, in <module>
weight = int(input("Weight: "))
So when I tried to change it to a while loop, it didn't work and my final result looked like this:
weight = int(input("Weight: "))
while weight != int():
if weight==int():
break
else:
print("Invalid unit. Please type a number: ")
weight=int(input())
continue
unit = input("(K)g or (L)bs ? ")
while unit.upper != ("K" or "L"):
if unit.upper()=="L":
converted = weight*0.45
print(f"You are {round(converted)} kilos")
break
elif unit.upper()=="K":
converted=weight//0.45
print(f"You are {converted} pounds")
break
else:
print("Invalid unit. Please type K or L: ")
unit=input()
continue
I know it's shit and at this point I'm stuck, it's just constantly typing me "Invalid unit. Please type a number: " and I can't get out of that loop. I don't even know what to type or what to do anymore so I decided to come here for a help.
I want to make with this code that until you type a number in weight input - you won't be allowed to go further, but after you type correctly - the program will continue to a unit input. Thx
The or operator does not work as you expect.
I suggest to replace it by:
while unit.upper() in "KL":
✅ Tested - I think you need to check the input for weight like this:
weight = input("Weight: ")
while not weight.isdigit():
print("Invalid unit. Please type a number... ")
weight= input("Weight: ")
Question is to
Prompt the user for a number from 1 to 100. Using a while loop, if they entered an invalid number, tell them the number entered is invalid and then prompt them again for a number from 1 to 100. If they enter a valid number - thank them for their input.
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y is True:
print("invalid.")
int(input("please enter a number 1-100, inclusive: ")
else:
print("thank you for your input")
my code is incorrect. Help me fix it please?
Aren't you missing a parenthesis in the statement before else: ? Looks like it says else: is invalid due to that.
Besides the syntax error (missing ) before the line of else, your code also have logical error, you need to set the y = False when user give proper input to get out from the while loop, like :
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y is True:
print("invalid.")
value = int(input("please enter a number 1-100, inclusive: "))
if value >= 0 and value <= 100:
y = False
else:
print("thank you for your input")
Simplification and correction of your code
while True:
x = int(input("please enter a number 1-100, inclusive: "))
if 1 <= x <= 100: # range check
print("thank you for your input")
break # terminates while loop
else:
print("invalid.") # print then continue in while loop
#Krish says a really good answer about how you are missing a second bracket during the line that you prompt inside the while loop. I assume you receive a SyntaxError about it (probably listing the immediately following line--unfortunately common in software).
Solution
However, you have a much more fundamental issue with your code: you never update y so you have an infinite loop that will always think that the input is invalid.
x = int(input("please enter a number 1-100, inclusive: "))
y = x<0 or x>100
while y: # it is unnecessary to check a boolean against a condition
print("invalid.")
x = int(input("please enter a number 1-100, inclusive: ")) # missing bracket
y = x<0 or x>100 # necessary to end the loop
else:
print("thank you for your input")
Improvement
Another option is to use break to exit the loop on the spot. It can make for cleaner code with less duplication because now everything is inside the loop.
while True: # infinite loop...but not because of break
x = int(input("please enter a number 1-100, inclusive: "))
if x<0 or x>100:
print("invalid.")
else:
print("thank you for your input")
break
Advanced
For completeness I will also include a couple more advanced features. You can skip this part since you are starting out, but it may be interesting to come back to once you have become more familiar with the language.
Lambda
Helps make the code cleaner.
user_input = lambda: int(input("please enter a number 1-100, inclusive: "))
condition = lambda x: x<0 or x>100
while condition(user_input()):
print("invalid.")
else:
print("thank you for your input")
Cmd
This one is really advanced and overkill for what you are trying to accomplish. Still, it is good to know about for a later, more advanced problem that it would be appropriate for. Docs found here.
from cmd import Cmd
class ValidNumberPrompter(Cmd):
"""
This is a class for a CLI to prompt users for a valid number.
"""
prompt = "please enter a number 1-100, inclusive: "
def parseline(self, line): # normally would override precmd but this is modifying the way the line is parsed for commands later
command, args, line = super().parseline(line) # superclass behaviour
return (command, args, int(line))
def default(self, line): # don't care about commands
if line<0 or line>100:
print("invalid.")
return False
else:
print("thank you for your input")
return True
"""
Only start if module is being run at the cmdline.
If it is being imported, let the caller decide
what to do and when to run it.
"""
if __name__ = '__main__':
ValidNumberPrompter().cmdloop()
I'm new to Python, and for my second project, I decided to create an easy number guessing game. The issue that I'm running into is that when I run my code, it automatically jumps to the last elif statement and outputs " The number is higher. Please try again", even if I limit random.randint(1,1) and enter 1 as user input. However, when I run my code through the debugger, everything seems to be working perfectly fine. Is there any way to fix this issue? I have already tried to restart Pycharm and update it but to no avail. Is my code the issue, or is it Pycharm?
import random
Question1 = input(" Please choose a number 1 to 1")
print("You chose"+ Question1)
Num = random.randint(1,1)
if Question1 == str(Num):
print("Correct! The correct number was" + " " + str((Num)))
elif Question1 > str(Num):
print("The number is lower. Please try again:")
elif Question1 < str(Num):
print(" The number is higher. Please try again")
Output using "Run"
Please choose a number 1 to 1 1
You chose 1
The number is higher. Please try again
Output using "Debugger"
Please choose a number 1 to 1You chose1
Correct! The correct number was 1
Thank you for the help in advance
This is not at all a pycharm issue!
You need to convert Question1 to int not Num to str
This what your code should look like :
import random
Question1 = input(" Please choose a number 1 to 1")
print("You chose"+ Question1)
Num = random.randint(1,1)
if int(Question1) == Num:
print("Correct! The correct number was" + " " + str((Num)))
elif int(Question1) > Num:
print("The number is lower. Please try again:")
elif int(Question1) < Num:
print(" The number is higher. Please try again")
Comparison operators (+ . - . * , / etc.) are used only on the int values not the str values
I'm creating a python program that gives you the area for any shape you enter and I want to know how to make the program return to asking the user what shape they want
import math
user_choice = input("Choose a shape")
if user_choice == "rectangle" or "square":
a = input("enter your length in centimeters here")
b = input("enter your width in centimeters here")
area = int(a) * int (b)
print(area, "cm²")
else
print"Sorry, you may have made a spelling error, or have chose a shape that we cannot calculate. Please try again"
#Code that returns to first question here?
Also if possible, since the code is very long because it is just repeating the if statements as elif statements for new shapes, is there a way to shorten it so it isn't lots of elif statements.
Thanks
import math
done = 'n'
while done == 'n':
user_choice = input("Choose a shape")
if user_choice == "rectangle" or "square":
a = input("enter your length in centimeters here")
b = input("enter your width in centimeters here")
area = int(a) * int (b)
print(area, "cm²")
else
print("Sorry, you may have made a spelling error, or have chose a shape that we cannot calculate. Please try again")
done = input("Done? (Y/N)").lower()
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()