I'm writing a code that asks the user for a percentage, and keeps asking until an acceptable input is entered by the user. However when I run this, the while loop does not break no matter what kind of input I enter.
Here is my code:
import math
while True:
try:
entered = float(raw_input("Please enter the velocity (as a percentage of the speed of light): "))
except ValueError:
print("Sorry, an acceptable input was not entered. Try again.")
continue
if entered > 100:
print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
continue
elif entered <= 0:
print("Sorry, a percent cannot be negative. Try again.")
continue
else:
#the percent entered is valid, break out of while loop
break
print("Ship is traveling at ", entered, "% the speed of light.")
print(" ")
speedOfLight = 299792458 #speed of light constant
percentage = entered / 100 #turn entered percent into decimal
speed = speedOfLight * percentage #actual speed (in m/s)
denominator = math.sqrt(1 - (percentage ** 2)) #denominator of factor equation
factor = 1 / denominator #solve for given factor equation
shipWeight = 70000 * factor #given ship weight * factor
alphaCentauri = 4.3 / factor # given times divided by the factor
barnardsStar = 6.0 / factor
betelgeuse = 309 /factor
andromeda = 2000000 / factor
print("At this speed: ")
print(" Weight of the shuttle is ", shipWeight)
print(" Perceived time to travel to Alpha Centauri is ", alphaCentauri, " years.")
print(" Perceived time to travel to Barnard's Star is ", barnardsStar, " years.")
print(" Perceived time to travel to Betelgeuse is ", betelgeuse, " years.")
print(" Perceived time to travel to Andromeda Galaxy is ", andromeda, " years.")
You are checking the inputs of your data inside your except. You are never going to get inside your except unless the casting to float raises a ValueError.
You simply want to move your conditions outside of the except block, so you can check the data that passes the float casting:
while True:
try:
entered = float(input("Please enter the velocity (as a percentage of the speed of light): "))
except ValueError:
print("Sorry, an acceptable input was not entered. Try again.")
continue
if entered > 100:
print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
continue
elif entered <= 0:
print("Sorry, a percent cannot be negative. Try again.")
continue
else:
#the percent entered is valid, break out of while loop
break
Your indentation is a little wonky, and the code never reaches the break statement because you continue the loop before then. Luckily, you can use and else keyword to make it work:
while True:
try:
entered = float(raw_input("Please enter the velocity (as a percentage of the speed of light): "))
except ValueError:
print("Sorry, an acceptable input was not entered. Try again.")
continue
else: # no exception
if entered > 100:
print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
continue
elif entered <= 0:
print("Sorry, a percent cannot be negative. Try again.")
continue
else:
#the percent entered is valid, break out of while loop
break
You don't even need the continues/breaks to make this work. You also will need to "import math" which will matter once you eventually break out of the while loop.
What you do need to do is watch the indention. The try/except were out of position -- if that reflects how the code was actually written that would account for your never ending while loop.
The below works as you desired with only indention fixes and "import math"
import math
valid = False
while not valid:
try:
entered = float(raw_input("Please enter the velocity (as a percentage of the speed of light): "))
except ValueError:
print("Sorry, an acceptable input was not entered. Try again.")
continue
if entered > 100:
print("Sorry, a velocity greater than the speed of light cannot be used. Try again.")
elif entered <= 0:
print("Sorry, a percent cannot be negative. Try again.")
else:
#the percent entered is valid, break out of while loop
valid = True
print("Ship is traveling at ", entered, "% the speed of light.")
print(" ")
speedOfLight = 299792458 #speed of light constant
percentage = entered / 100 #turn entered percent into decimal
speed = speedOfLight * percentage #actual speed (in m/s)
denominator = math.sqrt(1 - (percentage ** 2)) #denominator of factor equation
factor = 1 / denominator #solve for given factor equation
shipWeight = 70000 * factor #given ship weight * factor
alphaCentauri = 4.3 / factor # given times divided by the factor
barnardsStar = 6.0 / factor
betelgeuse = 309 /factor
andromeda = 2000000 / factor
print("At this speed: ")
print(" Weight of the shuttle is ", shipWeight)
print(" Perceived time to travel to Alpha Centauri is ", alphaCentauri, " years.")
print(" Perceived time to travel to Barnard's Star is ", barnardsStar, " years.")
print(" Perceived time to travel to Betelgeuse is ", betelgeuse, " years.")
print(" Perceived time to travel to Andromeda Galaxy is ", andromeda, " years.")
Related
I'm having an issue with my program. I'm working on a program that lets you play a small game of guessing the correct number. The problem is if you guess the correct number it will not print out: "You guessed it correctly". The program will not continue and will stay stuck on the correct number. This only happens if you have to guess multiple times. I've tried changing the else to a break command but it didn't work.
Is there anyone with a suggestion?
This is what I use to test it:
smallest number: 1
biggest number: 10
how many times can u guess: 10
If you try to guess the correct number two or three times (maybe more if u need more guesses) it will not print out you won.
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
#while loop until the guess is the same as the random number
while guess != x:
#this is if u guessed to much u get the error that you've guessed to much
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else: print("\n \nYou Lost, You've guessed", x, "times\n")
break
#this part is not working, only if you guess it at the first time. it should also print this if you guessed it in 3 times
else: print("You guessed it correctly", x)
test = (input("this is just a test if it continues out of the loop "))
print(test)
The main issue is that once guess == x and count < amount you have a while loop running that will never stop, since you don't take new inputs. At that point, you should break out of the loop, which will also conclude the outer loop
You can do it simply by using one while loop as follows:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#this is if u guessed too much u get the error that you've guessed too much
while count <= amount:
guess = int(input("guess the number: "))
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
if guess!=x:
print("\n \nYou Lost, You've guessed", count, "times\n")
As Lukas says, you've kind of created a situation where you get into a loop you can never escape because you don't ask again.
One common pattern you could try is to deliberately make a while loop that will run and run, until you explicitly break out of it (either because the player has guessed too many times, or because they guessed correctly). Also, you can get away with only asking for a guess in one part of your code, inside that while loop, rather than in a few places.
Here's my tweak to your code - one of lots of ways of doing what you want to:
import random
#counts the mistakes
count = 0
#asks to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#asks how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
#while loop until the guess is the same as the random number
while True:
if count < amount:
guess = int(input("guess the number: "))
#this is if u guessed to much u get the error that you've guessed to much
if guess > x:
print("this is not the correct number, the correct number is lower \n")
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("\n \nYou Lost, You've guessed", x, "times\n")
PS: You got pretty close to making it work, so nice one for getting as far as you did!
This condition is never checked again when the guessed number is correct so the program hangs:
while guess != x:
How about you check for equality as the first condition and break out of the loop if true:
import random
#counts the mistakes
count = 1
#askes to give up a minimum and maximum to guess between
minimum = int(input("what is the smallest number? "))
maximum = int(input("what is the biggest number? "))
#askes how many times u can guess in total
amount = int(input("How many times can you guess? "))
#random number between the 2 variables minimum and maximum
x = random.randrange(minimum, maximum)
guess = int(input("guess the number: "))
if guess == x:
print("You guessed it correctly", x)
else:
while count < amount:
if guess > x:
print("this is not the correct number, the correct number is lower \n")
guess = int(input("guess the number: "))
count += 1
elif guess < x:
print("this is not the correct number, the correct number is higher \n")
guess = int(input("guess the number: "))
count += 1
else:
print("You guessed it correctly", x)
break
else:
print("You guessed too many times")
This question already has answers here:
How can I check if string input is a number?
(30 answers)
Closed 3 years ago.
I'm starting out with Python after taking a class that taught us pseudocode. How could I make a validation loop to continue the function if a user inputted a decimal rather than a whole number? At its current state, I've gotten it to recognize when a user enters a number outside of the acceptable range, but if the user enters a decimal number, it crashes. Is there another validation loop that can recognize a decimal?
def main():
again = 'Y'
while again == 'y' or again == 'Y':
strength_score = int(input('Please enter a strength score between 1 and 30: '))
# validation loop
while strength_score < 1 or strength_score > 30 :
print ()
print ('Error, invalid selection!')
strength_score = int(input('Please enter a whole (non-decmial) number between 1 and 30: '))
# calculations
capacity = (strength_score * 15)
push = (capacity * 2)
encumbered = (strength_score * 5)
encumbered_heavily = (strength_score * 10)
# show results
print ()
print ('Your carrying capacity is' , capacity, 'pounds.')
print ('Your push/drag/lift limit is' , push, 'pounds.')
print ('You are encumbered when holding' , encumbered, 'pounds.')
print ('You are heavyily encumbered when holding' , encumbered_heavily, 'pounds.')
print ()
# technically, any response other than Y or y would result in an exit.
again = input('Would you like to try another number? Y or N: ')
print ()
else:
exit()
main()
Depending on what you want the behavior to be:
If you want to accept non-integer numbers, just use float(input()). If you want to accept them but turn them into integers, use int(float(input())) to truncate or round(float(input())) to round to the nearest integer.
If you want to print an error message and prompt for a new number, use a try-catch block:
try:
strength_score = int(input('Please enter a strength score between 1 and 30: '))
except ValueError:
again = input("Invalid input, try again? Y / N")
continue # skip the rest of the loop
That is because you have strength_score as an int, and not a float.
Try changing
strength_score = int(input('Please enter a strength score between 1 and 30: '))
to
strength_score = float(input('Please enter a strength score between 1 and 30: '))
Tested with 0.1 and 0.0001 and both are working properly.
Thank you for your patience everyone.
Thank you Ben10 for your answer. (posted below with my corrected print statements) My print statements were wrong. I needed to take the parenthesis out and separate the variable with commas on either side.
print("It only took you ", counter, " attempts!")
The number guessing game asks for hints after a certain number of responses as well as the option to type in cheat to have number revealed. One to last hints to to let the person guessing see if the number is divisible by another number. I wanted to have this hint available until the end of the game to help narrow down options of the number.
Again thank you everyone for your time and feedback.
guessing_game.py
import random
counter = 1
random_ = random.randint(1, 101)
print("Random number: ", random_) #Remove when releasing final prduct
divisor = random.randint(2, 6)
cheat = random_
print("I have generated a random number for you to guess (between 1-100)" )
while counter < 10:
if counter == 3:
print("Nope. Do you have what it takes? If not, type in 'cheat' to have the random number revealed. ")
if random_ % divisor == 0:
print("Not it quite yet. The random number can be divided by ", divisor, ". ")
else:
print("Not it quite yet, The random number is NOT divisible by ", divisor, ". ")
guess = input("What is your guess? ")
#If the counter is above 3 then they are allowed to type 'cheat'
if counter <= 3 and guess.lower() == "cheat":
print("The number is ", cheat, ".")
#If the player gets it right
elif int(guess) == random_:
print("You guessed the right number! :)")
print("It only took you ", counter, " attempts!")
#Break out of the while loop
break
#If the user types cheat , then we don't want the lines below to run as it will give us an error, hence the elif
elif int(guess) < random_:
print("Your guess is smaller than the random number. ")
elif int(guess) > random_:
print("Your guess is bigger than the random number. ")
#Spacer to seperate attempts
print("")
counter += 1
#Print be careful as below code will run if they win or lose
if int(guess) != random_:
print("You failed!!!!!!!!!!!!!!!!")
I rewrite the code, to allow it to be more versitile. Noticed quite a few errors, like how you forgot to put a closing bracket at the end of a print statement. Also in the print statements you were doing String concatenation (where you combine strings together) incorrectly.
import random
counter = 1
random_ = random.randint(1, 101)
print("Random number: " + str(random_)) #Remove when releasing final prduct
divisor = random.randint(2, 6)
cheat = random_
print("I have generated a random number for you to guess (between 1-100)" )
while counter < 5:
if counter == 3:
print("Nope. Do you have what it takes? If not, type in 'cheat' to have the random number revealed. ")
if random_ % divisor == 0:
print("Not it quite yet. The random number can be divided by " + str(divisor) + ". ")
else:
print("Not it quite yet, The random number is NOT divisible by " + str(divisor) + ". ")
guess = input("What is your guess? ")
#If the counter is above 3 then they are allowed to type 'cheat'
if counter <= 3 and guess.lower() == "cheat":
print("The number is " + str(cheat) +".")
#If the player gets it right
elif int(guess) == random_:
print("You guessed the right number! :)")
print("It only took you " + str(counter) + " attempts!")
#Break out of the while loop
break
#If the user types cheat , then we don't want the lines below to run as it will give us an error, hence the elif
elif int(guess) < random_:
print("Your guess is smaller than the random number. ")
elif int(guess) > random_:
print("Your guess is bigger than the random number. ")
#Spacer to seperate attempts
print("")
counter += 1
#Print be careful as below code will run if they win or lose
if int(guess) != random_:
print("You failed!!!!!!!!!!!!!!!!")
Evening Stack Overflow. Im a beginner in Python, which is why i decided to come on here for some help. Specifically, i'm having trouble understanding "do-while loop".
Here is the assignment i where given:
[Design the logic for a program that allows the user to enter a number. The program will display the sum of every number from 1 through the entered number. The program will allow the user to continuously enter numbers until the user enters 0.]
Here is my code without the "Do-while loop":
#Number Sum Conversion Calculator - V 0.0.1
#Author: Dena, Rene
print('Welcome to "Sum Conversion Calculator!"')
print('\nThis script will allow you to insert an integer and will thus display the total \ sum of the number you entered using summation methodology.')
print("\n Let's begin.")
name = input("In starting, what is your name?")
print('\n')
print("Hello %s. Let's get started." % (name))
base_number = 1
user_number = int(input("Insert your integer:"))
par = user_number + 1
n = user_number
num = 2
dom = par * n
answer = dom / num
print ("\n\nThe sum of the integer you entered is %s." % (answer))
print ('\nThank you for using "Number Sum Conversion Calculator". \
Please press ENTER to exit.')
Works great. Essentially do what i want it to do.
Now, from the assignment......it states:
The program will allow the user to continuously enter numbers until the user enters 0.
So here is my code/attempt for that:
#Number Sum Conversion Calculator - V 0.0.1
#Author: Dena, Rene
print('Welcome to "Sum Conversion Calculator!"')
print('\nThis script will allow you to insert an integer and will thus display \
the total sum of the number you entered using summation methodology.')
print("\n Let's begin.")
name = input("In starting, what is your name?")
print('\n')
print("Hello %s. Let's get started." % (name))
base_number = 1
user_number = int(input("Insert your integer:"))
def equation_run(EQ):
par = user_number + 1
n = user_number
num = 2
dom = par * n
answer = dom / num
print ("\n\nThe sum of the integer you entered is %s." % (answer))
zero = 0
while zero < user_number:
print (equation_run)
elif zero == user_number:
print ('Thank you for using "Number Sum Conversion Calculator". \
Please press ENTER to exit.')
When running this code, i get a syntax error. It highlights the elif part. Ive tried trial-and-error, but cant seem to get it to work. Please help.
Any comments/suggestion would be greatly appreciated. Thank you in advance and good day.
elif comes after an if, not a while. Replace it with a simple if:
while zero < user_number:
...
if zero == user_number:
...
something like:
while True:
number = int(input("Enter a number: "))
if number == 0:
break
print(0.5*number*(number+1))
should work
I am trying to find the average number of times a user guesses a number. The user is asked how many problems they want to do and then the program will give them that many problems. I am having trouble recording the amount of times they guess and get wrong and guess and get right and finding the average between the two. This is what I have so far
print("Hello!")
from random import randint
def HOOBLAH():
randomA = randint(0,12)
randomB = randint(0,12)
answer = 0
CORRECTanswer = (randomA*randomB)
REALanswer = (randomA*randomB)
AVGcounter = 0
AVGcorrect = 0
AVERAGE = 0
print("What is {0} * {1} ?".format(randomA,randomB))
while answer != REALanswer:
an = input("What's the answer? ")
answer = int(an)
if answer == CORRECTanswer:
AVGcorrect+=1
print("Correct!")
AVERAGE+=((AVGcorrect+AVGcounter)/AVGcorrect)
else:
AVGcounter+=1
if answer > CORRECTanswer:
print("Too high!")
else:
print("Too low!")
def main():
numPROBLEMS = input("How many problems would you like to solve? ")
PROBLEMS = int(numPROBLEMS)
if PROBLEMS in range(1,11):
for PROBLEMS in range(PROBLEMS):
HOOBLAH()
else:
print("Average number of tries: {0}".format(HOOBLAH,AVERAGE))
else:
print("Please input a value between 1 through 10!")
main()
Thanks!
So I tried to change as little as possible as to not cramp your style. So think about it like this, the average number of guesses needed to get the correct answer is just the total number of guesses divided by the number of correct guesses. Because you make sure the user eventually gets the correct answer, the number of correct guesses will just be the number of problems!
So each time you run HOOBLAH(), return the number of guesses it took to get the correct answer. Add all those up together outside the for loop, then at the end of the loop, divide the number of guesses by the number of problems and then you've got your answer! Also, I don't think python supports '+=', so you may need to change AVGcounter+=1 to AVGcounter = AVGcounter +1, but I totally may be mistaken, I switch between languages a bunch!
One note is I cast numGuesses to a float ( float(numGuesses) ), that is to make sure the int data type doesn't truncate your average. For example, you wouldn't want 5/2 to come out to 2, you want it to be 2.5, a float!
Hopefully that helps!
from random import randint
def HOOBLAH():
randomA = randint(0,12)
randomB = randint(0,12)
answer = 0
CORRECTanswer = (randomA*randomB)
REALanswer = (randomA*randomB)
AVGcounter = 0
AVERAGE = 0
print("What is {0} * {1} ?".format(randomA,randomB))
while answer != REALanswer:
an = input("What's the answer? ")
answer = int(an)
if answer == CORRECTanswer:
print("Correct!")
return AVGcounter
else:
AVGcounter+=1
if answer > CORRECTanswer:
print("Too high!")
else:
print("Too low!")
def main():
problemsString = input("How many problems would you like to solve? ")
numProblems = int(problemsString)
numGuesses = 0
if numProblems in range(1,11):
for problem in range(numProblems):
numGuesses = numGuesses + HOOBLAH()
print("Average number of tries: " + str(float(numGuesses)/numProblems)
else:
print("Please input a value between 1 through 10!")
main()
I'm not totally sure what you're trying to do, but if you want to give the user x number of problems, and find the average number of guesses per problem, you'll want your HOOBLAH() function to return the number of guesses for each run. You can keep track of this outside your method call and average it at the end. But right now, your program has no access to AVGcounter, which seems to be the variable you're using to count the number of guesses, outside the HOOBLAH() function call.