inserting a while loops into a for loop - python-2.7

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()

Related

Python Multidimension array(pointer technique: 4/5D samples build) cant save data into array

I have a test on building a multi-dimension array, doesn't matter it is for expert or rookie usage.
the program should run like this:
Main function: ask user to enter number_of_player
read function: loop and enter name and score of each player and save them into a dict
assign function: check their score, assign their score to a frequency_array to determine their rank and the frequency of players of the same rank.
search function: enable user to search and access data using name, score, location(address of player in dict), rank.
**haven't start working**
display function: print using the search keyword return from search function
**haven't start working**
so my problem comes in, i made all the array, but data doesn't goes in to it, when i print the whole array, it appears to be blank. Please help me, I don't where i got it wrong.
"""
there should be 5 tier ranking syst
there should be no upper boundary for no. of player
"""
def Main():
print "This is a eg of pointer technique(frequency dist) program \n"
Element = 0
score = 0
RecordArray = {}
scoreArray = {}
location=0
scoreArray[Element] = RecordArray
totalfrequencyArray = {}
frequencyArray1 = []
frequencyArray2 = []
frequencyArray3 = []
frequencyArray4 = []
frequencyArray5 = []
while True:
try:
NElement = raw_input("number of player: ")
NElement = int(NElement)
break
except ValueError:
print "Integer only!"
continue
reply = ""
find=""
selection=""
while Element != NElement:
Element += 1
Read(NElement, score, Element)
Assign(NElement, Element, score, location)
print totalfrequencyArray
Search(find, location, selection)
Display(selection, location, reply)
def Read(NElement, score, Element):
Name = raw_input("\n\n\nName: ")
while True:
try:
score = raw_input("Score(1-9K): ")
score = int(score)
if score in range(1, 9001):
break
else:
print "invalid score"
continue
except ValueError:
print "invalid input"
continue
RecordArray={}
scoreArray={}
RecordArray[Name] = score
scoreArray[Element] = RecordArray
return score
return Element
return NElement
"""
promblem encountered :
print function display empty array
"""
def Assign(NElement, Element, score, location):
if score in range(1, 2000):
location = 5
Rank = "Tier 5"
frequencyArray5[Element]
frequencyArray5=frequencyArray5+[Rank]
if Element==NElement:
totalfrequencyArray[location]=frequencyArray5
elif score in range(2001, 4000):
location = 4
Rank = "Bronze"
frequencyArray4[Element]
frequencyArray4=frequencyArray4+[Rank]
if Element==NElement:
totalfrequencyArray[location]=frequencyArray4
elif score in range(4001, 6000):
location = 3
Rank = "Silver"
frequencyArray3[Element]
frequencyArray3=frequencyArray3+[Rank]
if Element==NElement:
totalfrequencyArray[location]=frequencyArray3
elif score in range(6001, 8000):
location = 2
Rank = "Gold"
frequencyArray2[Element]
frequencyArray2=frequencyArray2+[Rank]
if Element==NElement:
totalfrequencyArray[location]=frequencyArray2
elif score in range(8001, 9000):
location = 1
Rank = "Diamond"
frequencyArray1[Element]
frequencyArray1=frequencyArray1+[Rank]
if Element==NElement:
totalfrequencyArray[location]=frequencyArray1
return location
def Display(selection, location, reply):
strformat = '{:<8}{:<20}{}'
if selection == 0:
print (strformat.format("", "scorelist", "ranklist"))
for i, (Element, location) in enumerate(zip(scoreArray, totalfrequencyArray)):
print (strformat.format(i, Element, location))
def Search(find, location, selection):
selection=0
return selection
Main()

How to calculate average / mean on python 2.7

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

(Super beginner) Can someone explain what's going wrong with my lists?

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()

How to run the code from start after calculation?

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

Using a dictionary to choose scenes in a game, but it's not playing the correct scene. Why?

At the start, if a random integer = 1, it will play a random event. The random event should be selected (also randomly) from a dictionary containing each scene name. Instead, it doesn't try to access the other scenes. It only runs each method(function?) in the order written. What am I doing wrong? Is this a bad way to go about this?
I'm still learning, so any pointers are appreciated!
from random import randint
from time import sleep
class RandomEvent(object):
def __init__(self, wallet):
self.wallet = wallet
def old_man(self):
#insert art
print "\nExcuse me, I have an unusual request."
print "My horoscope tells me it's my lucky day,"
print "but I don't have any money."
print "\nIf you'll let me borrow some money, I"
print "promise to give you half of all the winnings."
print "Do we have a deal?"
give_money = raw_input("(y)es or (n)o? ")
if give_money.lower() == "y":
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
if how_much <= self.wallet:
how_much *= randint(2,3)
print "Haha! I won $%d! Here's your share of the money, kiddo." % (how_much*2)
self.wallet += how_much
else:
print "Eh, kids these days... no faith in their elders... (grumble grumble)..."
sleep(2)
print "\nA few moments later you see the old man hit the jackpot at a slot machine."
return self.wallet
def robber(self):
#insert art
print "\nPsssst! Hey, you!"
#sleep(1)
print "\nYou glance down to see a knife discreetly placed"
print "to your stomach."
#sleep(1)
print "\nHand over all your cash. No funny business."
print "\nFunds: $", self.wallet
how_much = int(raw_input("How much money will you give? $"))
lie_success = randint(1,3)
if how_much == self.wallet:
self.wallet = 0
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking all your money with him."
if how_much != self.wallet and lie_success == 1:
self.wallet -= how_much
print "\nNice doin' business with ya."
print "The robber quickly disappears into a nearby crowd,"
print "taking your money with him."
else:
print "\nYou think you're a wise guy, eh?"
sleep(2)
print "\nYou are dead. GAME OVER"
sleep(2)
exit()
return self.wallet
def pretty_woman(self):
pass
###----------------------GAME CODE BELOW---------------
funds = 500
encounter = 1
while True:
if encounter == randint(1, 1): # 1,1 FOR TESTING
story = RandomEvent(funds)
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
funds = scene_list[2] #randint(1,3)] FOR TESTING
else:
print "\n\n\nWelcome to Dreams Casino."
print "Where would you like to go?"
print "(1) Slot Machines"
print "(2) Roulette Table"
print "(3) Leave the Casino"
print "\nFunds: $", funds
game_choice = int(raw_input("> "))
You're calling the functions when creating your dictionary:
scene_list = {1: story.old_man(), 2: story.robber(), 3: story.pretty_woman()}
Since you want scene_list[1] to refer to your function, pass the function:
scene_list = {1: story.old_man, 2: story.robber, 3: story.pretty_woman}