Double or quit/while loop - python

I know how to use a while loop, but I'm not sure about the part where I need to make a command to double the previous score.
The task is to double or quit.
And this is my code at the moment:
import random
play = 'y'
Original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
newnumber = Original*2
print (newnumber)
play = input("Play again?[y/n]: ")

No need for defining a new var newnumber, just rewrite the Original
by doing original = original*2
import random
play = 'y'
original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
original = original*2
print (original)
play = input("Play again?[y/n]: ")

No need to bring in variable newnumber. Also, dont use mix of upper and lower case variables.
import random
play = 'y'
original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
original= original*2 # or shorthand: original *= 2
print (original)
play = input("Play again?[y/n]: ")

You were assigning the new variable value (original * 2) to a locally scoped variable to the loop, so every iteration, original is still 1.
import random
play = 'y'
original = 1
while play.lower() == 'y':
if (random.randint(0, 3) == 0):
print('Unlucky... better luck next time')
else:
original *= 2; print(original)
play = input('Play again? [y/n]: ')

If you are trying to get the Original variable to be doubled, there's no need for bringing newNumber into the mix. Just use
Original = Original * 2 (or Original *= 2, for short).

Related

Python not summing list correctly

Python is not summing all items in the list. What did I do wrong?
I'm trying to make a program that calculates the average of inputed numbers and it seems like the len() is working correctly but sum() is only summing some numbers.
numbers = []
More = True
while More:
xInp = input('Number: ')
yInp = input('Again?(y/n) ')
if yInp == 'y':
numbers.append(int(xInp))
elif yInp == 'n':
break
print(sum(numbers))
print(len(numbers) + 1)
print(sum(numbers) / int(len(numbers) + 1))
The problem is the order, you are exiting the program without considering the last value being input. Altering the order a bit will help you solve the issue. Furthermore be careful with apostrophes and doble apostrophes, I've edited that in the answer too, as it will return a SyntaxError otherwise:
numbers = []
while True:
xInp = input('Number: ')
numbers.append(int(xInp))
yInp = input('Again?(y/n) ')
if yInp == 'y':
pass
elif yInp == 'n':
break
print(sum(numbers))
print(len(numbers))
print(sum(numbers) / int(len(numbers)))
Your code will only add the most recently-entered number to the array if the user selects y at the next prompt. Once they enter n, the last number entered is not appended to the list.
You need to append the number right after it has been entered, then check if the user wants to add more.
numbers = []
while True: # No need for a variable here
xInp = input("Number: ")
numbers.append(int(xInp))
yInp = input("Again? (y/n): ")
if yInp == "y":
pass
elif yInp == "n":
break
print(sum(numbers))
By convention, variables start with lowercase letters. Uppercase first letters are for class definitions (not instances). I had originally changed More to more, but as mentioned in the comments, it is not even necessary, so I replaced it with while True.
You missed the last value in more than one values.
numbers = []
More = True
while More:
xInp = input('Number: ')
yInp = input('Again?(y/n) ')
if yInp == 'y':
numbers.append(int(xInp))
elif yInp == 'n':
if xInp:
numbers.append(int(xInp))
break
print(sum(numbers))
print(len(numbers))
print(sum(numbers) / int(len(numbers)))

While loop with functions and if/break statement?

I’m just starting to learn functions and I am practicing on implementing some into my code. Just a simple example... how can I code this to loop properly and break out when the user wants?
def profit(i,c):
gain = c - i
print('Your profit is:' + '' + str(gain))
def beginning():
x = float(input("What was your initial investment?"))
y = float(input("What is your investment worth now?"))
profit(x,y)
beginning()
ans = 'y'
while ans == 'y' or ans == 'Y':
ans = str(input('Would you like to calculate another investment? (Y/N)'))
beginning()
if ans != 'y' or ans != 'Y':
break
There are two ways to break out of a while loop. The first way is obviously the break statement, kind of like you have done. For it to work correctly, you need to change the condition:
if ans != 'y' or ans != 'Y':
break
This will always be true, since ans cannot be "y" and "Y" at the same time. You should change it into:
if ans not in ["y", "Y"]:
Or
if ans.upper() != "Y":
In your case however, you don't need it at all. Since in both the if statement and the while condition you are checking ans, you can get rid of the if and just rely on this.
while ans.upper() == "Y":
This will end the loop automatically when ans becomes anything other than "Y" or "y".
The only reason you would use a break here is if you wanted to exit the loop immediately, and not complete the current iteration. For example:
while ans.upper() == "Y":
ans = input("Enter selection: ")
if ans == "I want to stop right now!":
break
print("Do other things, even if ans is not Y")
In this example, "Do other things" will always be printed regardless of ans, unless ans is "I want to stop", in which case it won't get printed.
One thing you can do is ans = ans.capitalize() after you get the user input. Then remove the ans != 'y' since that's causing your loop to break.

While loop/ Double or quit

I know how to use a while loop, but I'm not sure about the part where I need to make a command to double the previous score.
The task is to double or quit.
And this is my current code :
import random
play = 'y'
Original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
newnumber = Original*2
print (newnumber)
play = input("Play again?[y/n]: ")
A for-loop is better suited for your problem:
from itertools import count
import random
for pot in count():
if random.randint(0, 3) == 0:
print("Unlucky.... better luck next time")
break
print(2 ** pot)
if input("Play again?[y/n]: ").lower() != 'y':
break
You are currently repeating the same fixed output calculation over and over again:
newnumber = Original*2
Original is a constant since you only define it at the beginning and never change it.
You should instead use the result from the last run iteratively:
import random
play = 'y'
result = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
break
else:
result *= 2
print(result)
play = input("Play again?[y/n]: ")

User interaction via while-loops / jumping out of 2 while loops

Hello fellow programmers,
I'm quite a Python and overall programming newbie and I don't know how to process user input the bestimmt. A friend of mine suggested while loops and they worked quite well but now I have a serious problem.
The program is about asking the user which one of 3 ways to calculate Pi he wants. After his/her selection, e.g. the way to calculate Pi using a polygon which doubles the number of corners after each iteration, it asks how many digit the user wants to see or how many loops should be calculated etc. I also have added some code that checks what the user has written, e.g. if the user is asked to either type y or n but types b the program reminds him of that and asks again.
This style has led to whiles, inside whiles, inside whiles and now looks more like HTML code than Python and is a little complicated to understand...
Take a look:
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
prgrm_ctrl_main_while_start = 0
while prgrm_ctrl_main_while_start == 0:
print "Please select the type of algorithm you want to calculate Pi."
usr_ctrl_slct_algrthm = raw_input("'p' to use polygons, 'm' to use the Monte-Carlo algorithm or 'c' for the Chudnovsky algorithm: ")
print " "
if usr_ctrl_slct_algrthm == 'p':
#import libraries
import time
from mpmath import *
#starting values
n_corners = mpf(8)
counter = 0
while_loop_check_itertions = 0
while while_loop_check_itertions == 0:
print "Pi will be calculated more precisely the more iterations you select but it'll also take longer!"
loops = int(input("Please select number of iterations (1 - 10.000.000): "))
print " "
if 1 <= loops <= 10000000:
loops = loops - 1
decimals = int(input("Please select the amount of decimals you want to see: "))
print " "
decimals = decimals + 1
starttime = time.clock()
mp.dps = decimals
while counter <= loops:
counter = counter + 1
n_corners = mpf(n_corners) * mpf(2)
circle = mpf(360)
alpha = mpf(circle) / mpf(n_corners)
beta = mpf(alpha) / mpf(2)
radiansBeta = mpf(mp.radians(beta))
opp_leg = mpf(mp.sin(radiansBeta))
edge_lngth = mpf(opp_leg) * mpf(2)
circmfrnce = mpf(n_corners) * mpf(edge_lngth)
pi = mpf(circmfrnce) / mpf(2)
print "Pi: ", mpf(pi)
print "Time to calculate: ", time.clock() - starttime, "seconds"
print " "
prgrm_ctrl_p_algrthm_while_start = 0
while prgrm_ctrl_p_algrthm_while_start == 0:
usr_ctrl_slct_p_algrthm = raw_input("Would you like to try this algorithm again? (y/n): ")
print " "
if usr_ctrl_slct_p_algrthm == 'y':
usr_ctrl_slct_p_algrthm_slction = 0
break
elif usr_ctrl_slct_p_algrthm == 'n':
usr_ctrl_slct_p_algrthm_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_p_algrthm_slction == 0:
continue
else:
usr_ctrl_slct_diffrt_algrthm_while_start = 0
while usr_ctrl_slct_diffrt_algrthm_while_start == 0:
usr_ctrl_slct_diffrt_algrthm = raw_input("Do you want to use another algorithm? (y/n): ")
print " "
if usr_ctrl_slct_diffrt_algrthm == 'y':
usr_ctrl_slct_diffrt_algrthm_slction = 0
break
elif usr_ctrl_slct_diffrt_algrthm == 'n':
print "See you next time!"
print " "
usr_ctrl_slct_diffrt_algrthm_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_diffrt_algrthm_slction == 0: #The program gets to this line and in case of the user selecting 'y' should continue in the first while-loop
continue
else: #if the user says 'n' the program should interrupt and stop, in the best case it should close the command line (in my case IDLE)
break #instead of doing all this the code gets executed again in the 2nd while loop not the 1st
"""NOTE: I also know the lines above continue or quit the 2nd while-loop"""
elif loops < 1:
print "Please select at least one iteration!"
while_loop_check_algrthm_slct = 0
while while_loop_check_algrthm_slct == 0:
usr_ctrl_slct_algrthm_p_try_agn = raw_input("Do you want to try it again? (y/n): ")
print " "
if usr_ctrl_slct_algrthm_p_try_agn == 'y':
usr_ctrl_slct_algrthm_p_try_agn_slction = 0
break
elif usr_ctrl_slct_algrthm_p_try_agn == 'n':
usr_ctrl_slct_algrthm_p_try_agn_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_algrthm_p_try_agn_slction == 1:
break
else:
continue
else:
print "The maximum amount of iterations is 10 million!"
while_loop_check_algrthm_slct = 0
while while_loop_check_algrthm_slct == 0:
usr_ctrl_slct_algrthm_p_try_agn = raw_input("Do you want to try it again? (y/n): ")
print " "
if usr_ctrl_slct_algrthm_p_try_agn == 'y':
usr_ctrl_slct_algrthm_p_try_agn_slction = 0
break
elif usr_ctrl_slct_algrthm_p_try_agn == 'n':
usr_ctrl_slct_algrthm_p_try_agn_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_algrthm_p_try_agn_slction == 1:
break
else:
continue
I have commented the lines that are effected...
I can't solve the problem with the main-while-loop therefore I'm asking you how I can solve this. Is there a better way of handling user input and checking if it's correct? I'm stuck at a point where I wish I had goto because I can't imagine any other solution.
Hopefully you can help me and thank you for reading this long code! I appreciate that! :)
holofox
My first thought is simplify things, please see this "pseudo-code":
while True: #select algorithm type
#code: ask for algorithm
if answer not in "pmc":
#some message
continue #non-valid algorithm selected, ask again
#...
if answer == 'p':
while True: #select iteration range
#code: ask for iteration
if answer_not_in_range:
#some message
continue #non-valid iteration value, ask again
#...
#perform calculation upon valid selections
#...
#calculation ends
#code: ask for try again with other iteration (algorithm stays same)
if answer != "yes":
break #break out of "iteration" loop
#else loop continues asking for new iteration
#code: ask for try again with other algorithm
if answer != "yes":
break #"algorithm" loop ends, program ends
As Robert Rossney says in an answer to another question:
My first instinct would be to refactor the nested loop into a function and use return to break out.

trying to loop to the beginning of a function(sort of) in python

I am trying to go back to the top of a function (not restart it, but go to the top) but can not figure out how to do this. Instead of giving you the long code I'm just going to make up an example of what I want:
used = [0,0,0]
def fun():
score = input("please enter a place to put it: ")
if score == "this one":
score [0] = total
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")
#### Go back to score so it can let you choice somewhere else.
list = [this one, here]
I need to be able to go back so essentially it forgets you tried to use "here" again without wiping the memory. All though I know they are awful, I basically need a go to but they don't exist in python. Any ideas?
*Edit: Ah sorry, I forgot to mention that when it's already in use, I need to be able to pick somewhere else for it to go (I just didn't want to bog down the code). I added the score == "this one"- so if I tried to put it in "here", "here" was already taken, it would give me the option of redoing score = input("") and then I could take that value and plug it into "this one" instead of "here". Your loop statement will get back to the top, but doesn't let me take the value I just found and put it somewhere else. I hope this is making sense:p
What you are looking for is a while loop. You want to set up your loop to keep going until a place is found. Something like this:
def fun():
found_place = False
while not found_place:
score = input("please enter a place to put it: ")
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
found_place = True
elif used[1] == 1:
print("Already used")
That way, once you've found a place, you set found_place to True which stops the loop. If you haven't found a place, found_place remains False and you go through the loop again.
As Ashwini correctly points out, you should do a while loop
def fun():
end_condition = False
while not end_condition:
score = input("please enter a place to put it: ")
if score == "here":
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")

Categories