well, ive been wondering if such thing is possible in python
while True:
if True:
x = -5
x = 5
now i mean, whenever if statement is true,(in this example) the first time x to equal -5 and the second time is true, x to equal 5 ,and again the same
i know it sounds absurd but im trying to make a game which the ball has to go rightward and when returns leftward,and this thing over and over again
sorry for my bad english but it's really difficult for me to explain this
thanks in advance
Simply negate x each time the condition is true
x = 5
while True:
if True:
x = -x
You will need to count the iterations of the while loop so like this. This will let you switch between each iteration of the loop. If you just want to make it switch positive negative do x=-x.
x=0
while True:
if x%2==0: #if x is even do
y=5
else:
y=-5
print y
x+=1 #add 1 to x
if x==10: #quit at 10
break
Related
I am trying to create a game where i think of a number in my head. And then the computer guesses the number through me telling it if its guess is too low or high.
This is what I've come up with but i am pretty lost tbh.
maxguess = 100
minguess = 1
count = 0
print("Think of a number between {} and {}".format(minguess,maxguess))
def midpoint(maxguess, minguess) :
z = ((maxguess + minguess)/2)
def guessing(x) :
print("Is you number greater (>) , equal (=) ,or less (<) than" ,z,)
print("please answer <,=, or >! >")
x = input()
if x == (">") :
minpoint = z
count += 1
continue
elif x == ("<") :
maxpoint = z
count += 1
continue
elif x == ("=") :
print ("I have guessed it!")
count += 1
break
print("I needed {} steps!".format(count))
Purposely not a complete solution, but some hints for you:
I'd recommend avoiding the global variables like count, maxguess, and minguess. Instead, make a function that holds all these variables.
Change your midpoint function to return z instead, then call it inside your guessing function.
Your continue and break functions would need to be inside a for or while loop. Since you aren't sure how many iterations you need to guess the number, I think a while loop would make sense here
Your functions are never run. On a style point, bring all your 'main' statements down to the bottom so they're together. After the prompt to think of a number, you need to call the guessing() function. When you call it, you should pass the minguess and maxguess values to it.
I can see what you're trying to do with the if...elif statements, but they need to be in a while True: block. So should the three statements preceding them so the script repeatedly asks for new advice from you.
Either bring the content of the midpoint() function into guessing() or make it return the value of z.
You also offer the user a choice of '>1' but don't handle it - and you don't need it as far as I can tell.
You never use minpoint or maxpoint - and you dont need them. Call the midpoint function instead and pass it the appropriate values, e.g., if '>', z = midpoint(z, maxguess).
Also, you're going to spend forever trying to get it to guess as you are using floats. Make sure everything is an integer.
Finally, you should add some code to manage input that isn't expected, i.e., not '<', '>' or '='.
Good luck!
minguess=1
maxguess=100
z=50
count=0
print("Think of a number between 1 and 100")
condition = True
while condition:
z=((maxguess + minguess)//2)
print("Is your number greater (>) , equal (=) ,or less (<) than" ,z,)
print("Please answer <,=, or >! >")
x = input()
if x == (">"):
minguess=z
count += 1
elif x == ("<") :
maxguess=z
count += 1
elif x == ("=") :
print ("I have guessed it!")
count += 1
condition=False
I wasn't too sure what to call this post.
Anyways, what I'm trying to do is assign 'diff' to a user input, and if 'diff' is not average or advanced, recall the function so that the user can (hopefully) enter average or advanced.
However, no matter what I input, it will always recall the function, even if the input is 'average' or 'advanced'.
Code -
def choices():
global diff
diff = input("Choose a difficulty: Average/Advanced ")
diff = diff.lower()
x = 0
while x > 1:
if diff == 'average':
print('Difficulty set to average.')
x = x + 1
elif diff == 'advanced':
print('Difficulty set to advanced.')
x = x + 1
if diff != 'average' or 'advanced':
print('Your input is invalid. Please try again.')
choices()
choices()
The same thing is also happening for another decision I have that is similar to this, but I figured that there's no point in putting it down if it follows the same logic.
Sorry if this is a stupid question. I'm only a beginner.
You can also wrap it all into the while loop, I'm new to python but spawning recursive instances of a function seems dangerous to me.
def choices():
global diff
while true:
diff = input("Choose a difficulty: Average/Advanced ")
diff = diff.lower()
if diff == 'average':
print('Difficulty set to average.')
return
if diff == 'advanced':
print('Difficulty set to advanced.')
return
print('Your input is invalid. Please try again.')
Your first bug lies in this statement:
while x > 1:
You'll never execute the code within that loop because you set x = 0 at the top of the function. When it hits the while loop, x = 0 and so the while loop will be completely skipped.
There are a number of other problems, but this one is what's stopping the "if" logic from running.
I'm so confused about this function that I can't determine exactly what you're trying to do so I can't supply a complete working solution to your problem, only the first rather large bug in it.
I am a new coder, sorry if my question is bad or I am not following proper etiquette!
I am designing a basic program that rolls dice. It is supposed to roll dice until the total points of either the computer or the user equals 100. However, even though my point totaler is working, the loop won't end. Anyone know why this is? Thank you!
def main():
GAME_END_POINTS = 100
COMPUTER_HOLD = 10
is_user_turn = True
user_pt = 0
computer_pt = 0
welcome()
while computer_pt < GAME_END_POINTS or user_pt < GAME_END_POINTS:
print_current_player(is_user_turn)
if is_user_turn is True:
user_pt = user_pt + take_turn(is_user_turn, COMPUTER_HOLD)
elif is_user_turn is False:
computer_pt = computer_pt + take_turn(is_user_turn, COMPUTER_HOLD)
report_points(user_pt, computer_pt)
is_user_turn = get_next_player(is_user_turn)
The condition is always True because either the computer or the user will have a points total less than 100.
Instead of or use and:
while computer_pt < GAME_END_POINTS and user_pt < GAME_END_POINTS:
Now the loop will continue only when both the user and the computer have a points total less than 100. As soon as one of them has more than 100 the condition will be be False and the loop will terminate.
You while loop will only end if both computer_pt >= GAME_END_POINTS and user_pt >= GAME_END_POINTS. Are you sure that those two variables satisfy those two conditions?
you can print computer_pt and user_pt in the loop to see what happened in this two variable, then you will find the answer by your self.
Print variable in loop is a common way to debug your code.
I'm a beginner to Python, so this might sound pretty easy.
Anyway, I'm a little confused on when to use break, pass, or continue. I want to have a loop where it breaks out of it, but then after all the code runs again, then the loop will run again. This is some example code:
score = 100
while True:
score + 1
# break, continue, or pass
score - 30
Basically, what I want to happen is have score go up by 1, then have it go down by 30, and then keep going up by 1.
How can I achieve this? Thanks in advance!
score = 100
first = True
while True:
while True:
score += 1
if first:
first = False
break
score -= 30
I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!
To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)