How to fix a loop with boolean variable - python-2.7

I'm doing a project for a class, and I opted to make a text based game in python. I'm trying to set it up so that the question will loop until the player confirms their choice, and I'm having problems with the while loop in this section.
def pc_cls_sc(x):
# code does some stuff
print "You are sure about" + str(x)
exVar = raw_input("Right?")
if exVar == "y":
print "Alright!"
conf_Class = True
else:
print "Ok then."
conf_Class = False
while conf_Class is False:
pc_Class = raw_input(#asks some question)
pc_cls_sc(pc_Class)
The rest of this code functions properly, but the loop continues after the conf_Class variable is supposed to be set to true. I have a similar loop earlier in my code, which works just fine. I've tried moving the variable reassignment outside of the pc_cls_sc function, but all it did was cause double output. Can anyone tell me how to fix this?

You can use break to exit the loop. The code below will keep asking a user for input until they say 'y'.
while True:
x=input("Right? " )
if (x=='y'):
break

Related

how to use a conditional statement to stop a code with several inputs?

I wrote a code and want to end it after the first input is equal to "done".
If I write the condition after all of the inputs, the user should answer all the useless questions.
On the other hand, I don't want to write the condition in the middle of the inputs as you see in the following part.
I would appreciate it if anyone could help me with this.
Here is the code:
while True:
ind1=input('please enter your personal number:')
if ind1=='done':
break
ind2=input('please enter your name:')
ind3=input('please enter your family name:')
ind4=int(input('please enter your working hours:'))
ind5=int(input('please enter your payment:'))
Instead of using multiple variables, use an array.
pseudo code:
inputs = []
count = 0
while true:
if inputs[count] == 'done': break
inputs[count] = input('...')
count++

Order of if statements?

I wonder if the first if statement is True, whether are the following elif executed or not (even if they are also True) ?
I have tried:
if True:
print "Hi"
elif True:
print "hello"
And it prints only "Hi". But in a more complex part of my code, I see some print outputs displayed that are within some elif statements and I just basically switch the very first if to True so that none of the elif should be executed for testing purposes. So why are the print statement that are within the elif printed?
(code is too long to print here, I just wonder if it could be an answer without...)
An elif will only be entered if the condition matches and the previous condition does not:
>>> if x == True:
... print 'hi'
... elif x == False:
... print 'bye'
...
hi
>>> if x == True:
... print 'hi'
... elif x == True:
... print 'bye' #not entered because previous condition was valid
...
hi
>>>
I'm not sure if I understand this correctly, but have you tried else?
if True:
print "Hi"
else:
print "Hello"
EDIT: Sorry, understood what you mean now..
I might be wrong, but "elif" means "else if"
So what you're basicly writing is like this:
If i have 5 apples, i put up a hand
else if i have 5 apples, i put up a leg.
using elif should however not be used at the end of a statement/code. If you aren't going to compare more than 2 statements, use 'if' and 'else'
But why should you have 2 'True'?
In an [if, elif, else] blocks only the first block with the condition that checks out will be executed.
but considering your situation I guess it needs more context to understand it fully, post part of the code you're testing or something with the same logic.

Returning to the beginning of a piece of code when if statement condition is not met

I am totally new to programming and I have been trying to get a simple piece of code working. However I keep getting multiple different errors so I assume I am doing something very wrong somewhere along the line... Here is my code at the moment:
userName = input('Please enter your name: ')
age = input('Please enter your age: ')
if int(age) <= 5:
print(userName, 'you are too young to play') break
else:
print (userName, 'Your old enough')
factor = 2
finalAge = int(age) + int(factor)
multAge = int(age) * int(factor)
divAge = float(age) / int(factor)
print('In', factor, 'years you will be', finalAge, 'years old', userName )
print('Your age multiplied by', factor, 'is', multAge)
print('Your age divided by', factor, 'is', divAge)
What I want to do is, if the user's age is not higher than 5, then they get the message that they are too young to play and it returns to the start of the piece of code - asking for the name again.
Does anyone have any advice on how to do this?
You'll need to use a loop. Syntax depends on language, which you haven't specified. As pseudo-code, you could do
loop indefinitely
prompt for name and age
if age is less than 5
print error
otherwise
print that age is ok
break loop
Take a look at while loops. For this you'd be able to set some kind of condition (such as an "old_enough" variable and when that becomes true, the loop stops running.
You would set this value inside the if statement. By default it should be whatever will make the loop run
There's loads of tutorials online for this, but here's an example in python (your code sample looks like Python3):
old_enough = False
while not old_enough:
# do something
if age > 5:
print("You're old enough")
old_enough = True
else:
print("you're not old enough")
That should make sense. if not, please do look up documentation. It'll be better for you in the long term

How to create multiple loops in python

I'm trying to create a basic maths program which will randomly generate a numerical question and then allows 3 attempts to complete it before it moves onto the next question however cant figure out how to make it do both together.
My code currently looks like this
print "What is your name?"
score = 0
Attempt = 0
loop = True
Name = raw_input()
import random
for i in range (1,6):
question_1_part_1 = random.randint(1,30)
question_1_part_2 = random.randint(1,30)
print "What is", question_1_part_1, "+", question_1_part_2, "?"
while Attempt <3: # inputing this while loop here means it will retry the same question.
Guess = raw_input()
Guess = int(Guess)
answer = question_1_part_1 + question_1_part_2
if Guess == answer:
print "Well done"
score = score + 1
else: print "try again"
Attempt = Attempt + 1
if Attempt == 3: print "You failed"
print Name, "your score is", score
A simple break statement will take you out of the loop when the answer is correct.
if Guess == answer:
print "Well done"
score += 1
break
else: print "try again"
Note the change to your assignment; this is considered a cleaner increment.
To answer your comment ... you don't use this when the person gets the question wrong. Your program logic freezes out the user after three wrong guesses total, on all questions. If you want them to have up to three guesses on every problem, then you have to reset the Attempt counter for every question. Pull that line into the outer loop:
for i in range (1,6):
Attempt = 0
loop = True
question_1_part_1 = random.randint(1,30)
question_1_part_2 = random.randint(1,30)
In the future, I strongly recommend that you program incrementally: get a few lines working before you add more. Insert tracing print statements to check that the values and program flow are correct. Don't remove them until that part of the code is solid -- and even then only comment them out until the entire program is working. Some of your problems stem from trying to write more than you can comfortably hold in your mind at once -- which is common at most levels of programming. :-)
Add another argument to your while loop.
while Attempt <3 and Guess != ... :
rest of loop code
Then you are exiting your loop when they get the correct answer. Or you could break from the statement when they get the answer right.

Any ideas for why two side by side print statements in python would not execute?

I have a class defined as this:
class decider(object):
def __init__(self, brain):
self.brain = brain
##stuff
## brain is an object
In a class function I have two print statements, right next to each other, like so:
def somefunction(self, someParam):
print "Something First"
print "Another something: " + self.brain.aVariable + ", " + self.brain.anotherVariable
# more stuff
# execution continues as normal
# the object called in brain exists (ive checked)
In another function (in the same class) I call this function.The first print statement is printing, the second one is not. No exceptions are raised and the code just skips that line. No crashes either. I find this pretty bizarre and had not happened to me until now. Is there a reason for why this could possibly be happening?
If it matters, I'm running python 2.7 on an embedded system with an ATOM Z530 processor.
Could be buffered? Does anything print after the second call?
Add another print after the second call to force to clear the buffer