What if i want to ask the user whether he wants to perform another calculation or not everytime the user makes a calculation and gets the answer? I just want the code to run again from start everytime user performs calculation
var = int(raw_input("Enter 1,2,3 or 4 for add,subtract,multiplication,division respectively: "))
if var == 1:
print "You chose to add.Lets add!! :)"
def main ():
total = 0.0
while True:
number = float(raw_input('enter a number: '))
total+=number
if number == 0:
break
print "your answer is:",total
main()
elif var == 3:
print "You chose to multiply.Lets multiply!! :) "
def main ():
total = 1.0
while True:
number = float(raw_input('enter a number:'))
total*=number
if number == 1:
break
print "the answer is", total
main()
Just put
while True:
around the whole thing. This will continue looping indefinitely. If you want the user to be able to choose to end the program, try:
while True:
...
continue = raw_input("Continue? (Y/N) ")
if continue.lower in ("n", "no"):
break
Related
I need to find 2 random numbers from 1-100 and send a message:
to high or to low according to the random number,
This is the code I wrote..., it doesn't work after the first if...,
from random import randint
a = int(randint(1, 101))
guess = int(raw_input("guess the number:"))
while guess != a:
if guess > a:
print "bigger"
print guess
print a
elif guess < a:
print "smaller"
print guess
print a
else:
print "correct"
print guess
print a
break
guess = raw_input("guess a new number:")
from random import randint
a = randint(1, 101)
guess = input("guess the number:")
while True:
if guess > a:
print "your guess is too high"
elif guess < a:
print "your guess is too low"
else:
print 'You are correct'
break
guess = input("guess again:")
If I understood correctly your aim this code will work. It will stop when he guesses correctly the number. You had many mistakes with input and int. For future reference - if you use input() instead of raw_input() it will automatically pick the right type for the var.
In order to make your code work as intended just fix the input:
from random import randint
a = int(randint(1, 101))
guess = int(raw_input("guess the number:"))
while True:
if guess > a:
print "bigger"
print guess
print a
elif guess < a:
print "smaller"
print guess
print a
else:
print "correct"
print guess
print a
break
guess = input("guess a new number:") #not raw_input()
Im trying to calculate the average when an user will enter the numbers and will stop when he decide. I manage to get the sum however I cant divided it because I need somehow get the quantity of the inputs before he stops entering. Here is my code so far:
print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")
s = 0
x = raw_input ('please enter the number')
while (num != 'f'):
x = eval (x)
s = s + x
x = raw_input ('please enter the number')
print (' the average is'), s
Like you see I manage to get the sum however I dont know how I can get the quantity of the input to then divide the sum with this to get the average. Any help will be appreciated
You just needed to add a counter inside your while loop:
print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")
s = i = 0 #declare counter: i = 0
x = raw_input ('please enter the number')
while (x != 'f'):
x = eval (x)
s = s + x
i+=1 #increment counter: i=i+1 or i+=1 (these 2 options are equivalent)
x = raw_input ('please enter the number')
print (' the average is'), s/i #divide the sum by counter
I'm having this strange problem with a simple coin flip program where, instead of giving me some sort of error, whenever i run this code it just sort of crashes. I type in a yes or no answer and hit enter, but it does nothing. Then I hit enter again and it closes out completely.
import time
import random
constant = 1
FirstRun = True
def Intro():
raw_input("Hello and welcome to the coin flip game. Do you wish to flip a coin? (yes or no): ")
def CoinToss():
print "You flip the coin"
time.sleep(1)
print "and the result is..."
time.sleep(1)
result = random.randint(1,2)
if result == 1:
print "heads"
if result == 2:
print "tails"
while constant == 1:
if FirstRun == True:
Intro()
FirstRun = False
else:
answer = raw_input()
if answer == "yes":
CoinToss()
raw_input("Do you want to flip again? (yes or no): ")
else:
exit()
As you simply ignore the return value of the raw_input method, you don't know what the user is entered in order to break out of the loop.
Here is a simplified version of your program, note how I store the result of the raw_input method in result and use that to control the execution loop:
import random
import time
result = raw_input('Hello and welcome to the coin flip game. Do you wish to flip a coin? (yes or no): ')
while result != 'no':
print('You flip the coin....')
time.sleep(1)
print('...and the result is...')
toss_result = random.randint(1,2)
if toss_result == 1:
print('Heads')
else:
print('Tails')
result = raw_input('Do you want to flip again? (yes or no): ')
print('Goodbye!')
Ok, so, this is the longest code I've ever written, so I apologize if it's a bit messy. First computer science assignment ever.
def main():
#generate random value
import random
rand = random.randint(1, 99)
#instructions
print("""The purpose of this exercise is to enter a number of coin values
that add up to a displayed target value. Enter coins as 1=penny, 5-nickel,
10-dime, 25-quarter. Hit return after the last entered coin value.""")
#defining function for 'first coin'
def firstCoin ():
coins = []
global coins
coin = int(input("Enter first coin: "))
if coin > rand:
print("Sorry, total value exceeds", rand, "cents.")
again = input("Try again (y/n): ")
if again == "y" or "Y":
main()
else:
sys.exit() #ends program
elif coin in possible:
coins.append(coin)
nextCoinplease()
#defining function for 'next coin'
def nextCoinplease ():
while True:
nextcoin = (input("Enter next coin: "))
if nextcoin in possible:
coins.append(nextcoin)
elif nextcoin == "":
break
else: print("Invalid entry.")
#making lists
possible = [1, 5, 10, 25]
print("Enter coins that add up to", rand, "cents, one per line.") #program start
firstCoin ()
sumcoin = sum(coins)
print(sumcoin)
if sumcoin == rand:
print("Correct!")
else:
print("Invalid entry.")
firstCoin()
main()
So, this is my issue. For some reason, user input in the function nextCoinplease does not get added to the list "coins", only the first input from the function firstCoin does. This means that sum(coins) is literally only the first input. I cannot for the life of me figure out why, so any input would be greatly appreciated, thanks!
You have two input statements, one to get coin and one to get nextcoin. They are different. What's the difference?
(I'm deliberately not giving the answer outright because from what you've written so far, I am sure you can figure this one out given this hint.)
The return type of input is a string, so nextcoin in possible always fails since possible only contains integers. Try using int() to parse the input as an integer.
Your code never gets to check if the rand is equal to sumCoin, so it never stopped. I've fixed the problem, this code works now.
Demo on repl.it
What did I do?
I moved your if statement that checked if rand == sumCoin at the beginning of the while loop in nextCoinPlease(), so that it will check the sumCoin value before entering each next coin value and will stop once it equals rand.
Code:
import random
import sys
def main():
rand = random.randint(1, 99)
print('''The purpose of this exercise is to enter a number of coin values \
that add up to a displayed target value. Enter coins as 1=penny, \
5=nickel, 10-dime, 25-quarter. Hit return after the last entered \
coin value.''')
coins = []
def firstCoin():
coin = int(input("Enter first coin: "))
if coin > rand:
print('Sorry, total value exceeds ', rand, ' cents.')
again = input('Try again? (y/n): ')
if again == 'y' or 'Y':
main()
else:
sys.exit()
elif coin in possible:
coins.append(coin)
nextCoinPlease()
def nextCoinPlease():
while True:
sumCoin = sum(coins)
print('Total Value: ' + str(sumCoin))
print ''
if sumCoin == rand:
print('Correct! You Win!')
sys.exit()
elif sumCoin > rand:
print('You exceeded the total value! You lose! Try again!')
sys.exit()
nextCoin = (input('Enter next coin: '))
if nextCoin in possible:
coins.append(nextCoin)
elif nextCoin == "":
break
else:
print('Invalid entry.')
possible = [1, 5, 10, 25]
print('Enter coins that add up to', rand, 'cents, one per line.')
firstCoin()
main()
I want to apply this while loop into the for loop below.
I have tried putting the while loop before the if statements, in each if statement.
When i put it before the if statement( in the for loop ) it asks the user once and then returns the same input for the whole range (1,8).
I want this while loop to apply to each question, the seven items 2 to 8
how do i implement it. can anyone help please, Thanks
def valid_entry ():
price = 110
invalid_input = 1
while price< 0 or price> 100:
if invalid_input >=2:
print "This is an invalid entry"
print "Please enter a number between 0 and 100"
try:
price= int(raw_input("Please enter your price : "))
except ValueError:
price = -1
invalid_input +=1
End of the while loop
def prices ():
x = range (1,8)
item=2
price=0
for item in x:
item +=1
print "\n\t\titem",item
price = int(raw_input("Enter your price : "))
if price <10:
price=1
print "This is ok"
if price >9 and price <45:
price +=5
print "This is great"
if price >44 and price <70:
price +=15
print "This is really great"
if price >69:
price +=40
print "This is more than i expected"
print "\nYou now have spent a total of ",price
prices ()
Is the lack of responses a sign that its a stupid question or is it not possible to do?
does this make it any clearer ?
def prices ():
x = range (1,8)
item=2
price=0
for item in x:
item +=1
print "\n\t\titem",item
valid_entry ()#should it go here
price = int(raw_input("Enter your price : "))
valid_entry ()#should it go here
if price <10:
valid_entry ()#should it go here and so on for the following 3 if conditions
price=1
print "This is ok"
if price >9 and price <45:
price +=5
print "This is great"
if price >44 and price <70:
price +=15
print "This is really great"
if price >69:
price +=40
print "This is more than i expected"
print "\nYou now have spent a total of ",price
You could try something like this (apologies if this isn't what you were looking for). Happy to explain anything that doesn't make sense - overall idea is that it loops through a range of 8 items, asking for a valid price each time and continuing to ask if the entered value is either not a number or not in the specified range. As this may be for an assignment, I tried to keep it as closely aligned to the concepts you already demonstrated that you knew (the only exception here may be continue):
def valid_entry():
# Here we define a number of attempts (which is what I think
# you were doing with invalid_input). If the person enters 10
# invalid attempts, the return value is None. We then check to
# see if the value we get back from our function is None, and if
# not, proceed as expected.
num_attempts = 0
while num_attempts < 10:
# Here we do the input piece. Note that if we hit a ValueError,
# the 'continue' statement skips the rest of the code and goes
# back to the beginning of the while loop, which will prompt
# again for the price.
try:
price = int(raw_input("Enter your price : "))
except ValueError:
print 'Please enter a number.'
num_attempts += 1
continue
# Now check the price, and if it isn't in our range, increment
# our attempts and go back to the beginning of the loop.
if price < 0 or price > 100:
print "This is an invalid entry"
print "Please enter a number between 0 and 100"
num_attempts += 1
else:
# If we get here, we know that the price is both a number
# and within our target range. Therefore we can safely return
# this number.
return price
# If we get here, we have exhausted our number of attempts and we will
# therefore return 'None' (and alert the user this is happening).
print 'Too many invalid attempts. Moving to the next item.'
return None
def prices():
# Here we go from 1-8 (since the upper bound is not included when
# using range).
x = range(1,9)
# Here we use a variable (total) to store our running total, which will
# then be presented at the end.
total = 0
# Now we iterate through our range.
for item in x:
print "\n\t\titem",item
# Here is the important part - we call our valid_entry function and
# store the result in the 'price' variable. If the price is not
# None (which as we saw is the return value if the number of attempts
# is > 10), we proceed as usual.
price = valid_entry()
if price is not None:
if price <10:
# Note this should probably be += 1
total += 1
print "This is ok"
elif price >= 10 and price < 45:
total += 5
print "This is great"
elif price >= 45 and price < 70:
total += 15
print "This is really great"
# We know that price >= 70 here
else:
total += 40
print "This is more than i expected"
# Now print out the total amount spent
print "\nYou now have spent a total of ", total
prices()