I tried this... but it doesn't work
question = input("do you want the program to start? Type Y/y to start: ")
y = TRUE
Y = TRUE
if(question == TRUE):
run statements
else:
what am i doing wrong? this doesn't work.
To answer your specific question, it is not working because of these issues:
TRUE is not a defined variable in python. True is.
question == TRUE won't work. See 1.
run statements isn't real code.
You need to put something in your else: block.
EDIT:
question can never become True in this code. – #adsmith
NOTE:
Just trying to be comprehensive with my coverage.
The boolean is True in Python, not true or TRUE. In any case, this doesn't do what you expect it to. This is what I'd do.
question = input("...")
if question.lower() == 'y': # or `question in ('y','Y'):` or `question.upper() == "Y":` or `question.casefold() == 'y':` or................
do_things
else:
handle_it
What you had written assigns the variables y and Y to some (undefined) variable TRUE. This will trigger a NameError since there is no such variable TRUE. If you had done:
y = True
Y = True
It still wouldn't have done what you wanted, since your input (fed into the variable question) is a string and those are variables. You could have done that with if globals()[question] but that's really bad practice, and COMPLETELY unnecessary in this situation.
As a side note -- there's never a reason to type == True. if foo will evaluate to True or False, which will fulfill the conditional on its own. It just does a needless compare :)
I think you probably want to use code something along these lines:
answer = raw_input("Do you want the program to start? Type Y/y to start: ")
if answer[0].lower() != "y": # first character not a "Y" or "y"?
exit()
rest of program...
1) You have five (5) spaces indenting your if clause. Should follow Generally Accepted Python Practices (GAPP) ;) (Yes, I just made this up. It may or may not become a thing :p) you should use four (4) spaces.
2) Try adding pass after else:
else:
pass
3) In Python, case matters. As such, boolean testing must be True or False (or 1/0 :p)
4) Don't you mean Y/N? Not Y/y?
Related
I have a complex project and I will try to simplify one of the main problem of the project. So there is the simplification:
We can Imagine a while loop like this:
while(condition):
statement1
statement2
statement3
...
statementn
In this loop there n statements, and each statement can be whatever(function, loop, if statement,...) and there is a condition in the loop, this condition i want to check it BEFORE the while loop do it. Because if the condition is respect since the first statement I have to wait until the end of the while to check if the condition is respect... So there is my question is possible to check the condition BEFORE the loop without have a check-function between EACH statements of the whileloop ?
Because in fact, it's work... BUT the code isn't clear, I really think this way we pollute my code and i want to work more efficiently and with a beautiful code, so how can I solve my problem without this constraint ?
PS: I think about event listener like javascript but i found poor information about them on python, but if there is a tool which act like event listener it would be great !
It sounds like you want to clean up all your if-then-break statements into a single function that handles the "checking" of the value of a. For that purpose you could use exceptions:
import random
class ItIsFiveException(Exception): pass
def check(a):
if a == 5:
raise ItIsFiveException
try:
a = 0
while(a != 5):
a = random.randint(1,5); check(a)
a = random.randint(1,5); check(a)
a = random.randint(1,5); check(a)
a = random.randint(1,5); check(a)
except ItIsFiveException:
print("I saw a five!")
You just have to define your own python Exception as a class, and the raise it in your manually-defined check(a) function. Then you can wrap your entire while loop in a try-except block and catch your exception.
I am not sure if I understand you right, but this is what I'd do:
flag = False
while not flag:
for i in range(4):
a = random.randint(1, 5)
if a == 4:
flag = True
break
I don't know exactly what it happens with "a" but if if you can chain the conditions and will stop when the first one fails
while(checkRandom()):
...
def checkRandom(a):
return random.randint(1,5) == 5 and random.randint(1,5)....
If you can loop the generation of random values you can use
while(a!=5):
for item in range(1, 5):
a=random.randint(1,5)
if a==5:
break
I'm writing some code in Python that calculates the area of a triangle or a circle, depending on the user's choice. I want to write "if the user's choice is a C (for circle), continue running", but everything I write doesn't work and it shows an error.
I have:
option = raw_input('Enter C for Circle and T for Triangle: ')
circle = 'C'
tringle = 'T'
if option == circle:
return option
As noted in the comments, you cannot return a value unless it is from a function.
If you want to accomplish a running example you can easily use a while loop like so:
circle = 'C'
tringle = 'T'
value = True
while value:
option = raw_input('Enter C for Circle and T for Triangle: ')
# check lower() so capitalization doesn't matter
if option.lower() == circle:
# do something
print("Do something, 'C' has been selected")
pass
else:
value = False
As an explanation, if you are unclear on what is happening above. The while loop is always True if the selected option is circle, thus the loop never terminates and the iteration continues. If the selected option is not circle, the value of value will not be True, so the loop breaks before the code in the loop is executed again.
You're getting a SyntaxError because you are calling return despite not having any function defined. According to Python syntax, you can only return from inside of a function. I'd recommend reading up on how to create Python functions (this article does a good job of explaining it)
So, I am working on a small project. I am making a text-based temperature calculator but I have run into a problem with an if statement in the program, just as the title of this question suggests.
This is the code that I am having issues with.
running = True
fahr = "fahrenheit"
cel = "celsius"
kel = "kelvin"
temperatures = [fahr, cel, kel]
while running == True:
try:
temperature_type = str.lower(input("What is the current temperature unit you are using? \nFahrenheit, Celsius, or Kelvin?\n"))
except ValueError:
print("I do not understand. Please try again.")
continue
if temperature_type == any(temperatures) and not all(temperatures):
break
else:
print("Please enter a valid input.")
continue
It seems that there is something wrong with the logic that I am not seeing, and I have tried multiple combinations, even ones that are suggested from this post and none of them seem to work the way I want it to. The way I want it to work is to let the variable temperature_type be equal to only one of the temperatures such as Fahrenheit and then ask another question (which is not shown here). If the variable temperature_type does not equal any of the three, then I want to loop to repeat. The issue I am having is that no matter what I input, it always asks for the temperature. If anyone has an answer I would be thrilled to know what I am doing wrong and I would also love an explanation of the logic because I am not the best with this sort of logic yet. Thanks again for any answers and/or guidance!
any and all return True or False, not some object that can be compared meaningfully to a str. All non-empty str are "truthy", so you're checking if temperature_type == True and not True, which of course will never pass.
You're desired logic would probably be:
if temperature_type in temperatures:
It's impossible for someone to enter multiple temperature types in your design, so you don't need any equivalent to the all test, you just want to know if the entered string matches one of the three known strings.
Here's a simpler version of the check that simply checks that the input string is one of the valid temperatures. It uses the in operator to check that the provided string is in temperatures.
running = True
fahr = "fahrenheit"
cel = "celsius"
kel = "kelvin"
temperatures = [fahr, cel, kel]
while running:
temperature_type = str.lower(input("What is the current temperature unit you are using? \nFahrenheit, Celsius, or Kelvin?\n"))
if temperature_type in temperatures:
break
print("Please enter a valid input.")
OR:
while 1:
if input("What is the current temperature unit you are using? \nFahrenheit, Celsius, or Kelvin?\n").lower() in temperatures:
break
print("Please enter a valid input.")
Explanation:
all and any returns True or False so it will not work so use in
I removed running because just use 1
You can do True too, see:
>>> 1==True
True
Maybe expand to include all of the scales, and make it the user interface easier.
scales = ['F', 'R', 'C', 'K']
while True:
if input("What temperature scale are you using [F, C, K, R]? ")[0].upper() in scales: break
[0]
myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
ready = input("Are you readyyyy!?")
if ready = "yes" or "yeah" or "totally" or "hell yeah" or "yupp" or "yepp" or "uhumm" or "sure": <-- here's the problem it says, at "sure"'s 1st "-sign
print("Let's go!")
loop = "y"
else:
print("I'm sorry to hear that.")
loop "n"
Could please anyone help, beginner here. I tried to delete and add new word, I restared the program and the computer because there's something clearly wrong. If I delete a word like "sure" the pointer will still point to the same exact place but there's nothing there...
You're using a single = sign in your if statement. That's not allowed. If you want to check for equality, you'll need to use ==. The = operator is only for assignment statements.
While changing = to == will fix the syntax error, your code still won't work exactly right. That's because == will not be distributed over all the or options you show. The expression a == b or c gets interpreted as (a == b) or c, and if c is "truthy" (as any non-empty string will be), the expression will be considered true.
Instead, you probably want to use something like if ready in {"yes", "yeah", "totally"}. This creates a constant set object and tests if the value of the ready variable is in the set (which is a fast check).
You are using a = instead of a == in your if statement. However, I would recommend doing if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp"} to account for them using all uppercase.
Also, you seem to be missing your actual loop statements. I noticed you had variables named loop that are 'y' and 'n' but don't actually use them. You should also do something like this:
myName = input("Hey there, what's your name?")
print("Hello",myName,"!")
print("Here's a game called ''Guess my number'', in this game you will have to guess my number in 5 tips, I will think of a number between 1 and 20.")
loop = True
while loop:
ready = input("Are you readyyyy!?")
if ready.lower() in {"yes", "yeah", "totally", "hell yeah", "yupp", "yepp", "uhumm", "sure"}:
print("Let's go!")
loop = False
#To break out of the while loop that will keep asking them when they are ready
else:
print("I'm sorry to hear that.")
I have a problem in Python language that is described in a title.
for slovo in slova:
if pygame.mouse.get_pressed()[0] and slovo["rect"].collidepoint(pygame.mouse.get_pos()):
for i in range (len(randRijec)):
if slovo["name"] in randRijec[i]:
if i == 0:
slovo1 = randRijec[i].upper()
prvoSlovo = 1
...
...
else:
pogresnoBrojac += 1
slova.remove(slovo)
So, even this IF statement is true, ELSE statement is being executed! However, else statement should be skipped if the if statement is fulfilled.
How to fix this issue?
p.s. I've had this problem few times before and I was not able to solve it...
You have a mixture of tabs and spaces in your code:
Running cat -A test.py (on Unix) yields
for slovo in slova:$
if pygame.mouse.get_pressed()[0] and slovo["rect"].collidepoint(pygame.mouse.get_pos()):$
for i in range (len(randRijec)):$
if slovo["name"] in randRijec[i]:$
if i == 0:$
slovo1 = randRijec[i].upper()$
prvoSlovo = 1$
^I^I^I^I^I^I...$
^I^I^I^I^I^I...$
else:$
pogresnoBrojac += 1$
slova.remove(slovo)$
The ^I indicate tabs.
Thus, the else block is not being interpreted as being at the indentation level on which it appears to be.
Your python code should never mix tabs and spaces for indentation. You can check that your script is not mixing tabs and spaces by running python -t script.py.
In Python you must commit to using either only spaces or only tabs for indentation. PEP8 recommends spaces-only indentation.
You can convert tabs to spaces using the reindent.py program.
So, even this IF statement is true, ELSE statement is being executed!
I can assure you that this is not what happens.
I notice that in the outline of your code the if is inside a for loop. Make sure that in your actual code the else is not accidentally lined up with the for instead of the if. I've seen this mistake more than once.
In Python, for-else is a valid construct. For example, the following is perfectly valid Python:
for i in range(10):
if i < 100:
pass
else:
print 'In else clause'
When run, this prints out In else clause.
Contrast this with the following, which doesn't print anything when run:
for i in range(10):
if i < 100:
pass
else:
print 'In else clause'
It's a question from a long time ago and I stumbled upon it as I was troubleshooting the very same issue - the solution was actually pretty silly and most probably was also the case - as it's a for loop it iterates through every list element, if even one of those elements doesn't fulfill the if condition, it will automatically trigger the else - pretty self-evident but easy to miss for beginners.
Well at least that was the problem in my case :)
Next solution fixed my problem:
for slovo in slova:
if pygame.mouse.get_pressed()[0] and slovo["rect"].collidepoint(pygame.mouse.get_pos()):
xy = 0
for i in range (len(randRijec)):
if slovo["name"] in randRijec[i]:
xy = 1
if i == 0:
slovo1 = randRijec[i].upper()
prvoSlovo = 1
break
if i == 1:
slovo2 = randRijec[i].upper()
drugoSlovo = 1
break
slova.remove(slovo)
if xy == 0:
pogresnoBrojac += 1
...
...
...
xy = 1
pygame.display.update()
time.tick(value)
So, I have just added that xy counter that makes my code work how it should work. When IF statement is met, xy becomes 1, if IF statement isn't fulfilled, xy is set to 0 and then this "else" statement executes. At the end of the code, xy is set to 1 again to prevent executing this "else" (if xy == 0) block.