Why doesn't the menu in this Python program function? - python-2.7

I have looked over this code 100 times and I feel like it may be something small that I am missing. Program will allow you to login, and display the menu but after entering your selection it continuously displays the menu again.
import sys
def main():
login = 'yes'
choice = 0
hours = [0] * 7
wages = 0
totalHours = 0
totalWages = 0
print
login = raw_input('Do you want to login?')
while not (login == 'yes' or login == 'no'):
print
print 'Please enter a yes or no'
while login == 'yes':
print
userId = raw_input ('Enter user name:')
passWord = raw_input('Enter password:')
while passWord != userId:
print 'Incorrect Password, please try again.'
passWord = raw_input('Enter password:')
while passWord == userId:
print 'Login Success!'
print
print 'Enter 1 to view upcoming schedule'
print 'Enter 2 to view previous schedule'
print 'Enter 3 to calculate wages due'
print 'Enter 4 to verify clock in/out times'
print
choice = raw_input('Enter 1 to 4 from menu.')
def readFromNext(nextWeek):
inFile = open('nextweek.txt', 'r')
str1 = inFile.read()
print str1
str2 = inFile.read()
print str2
print
inFile.close()
def readFromLast(lastWeek):
inFile = open('lastweek.txt', 'r')
str1 = inFile.read()
print str1
str2 = inFile.read()
print str2
print
inFile.close()
def getHours(hours):
counter = 0
while counter < 7:
hours[counter] = input('Enter hours worked per day')
counter = countr + 1
return hours
def getTotalHours(hours, totalHours):
counter = 0
while counter < 7:
totalHours = totalHours + hours[counter]
counter = counter + 1
return totalHours
def getWages(wages):
wages = input('Enter your hourly wage.')
return wages
def getTotalWages(totalHours, wages):
totalWages = totalHours * wages
print 'Your total pay due is:' , totalWages
return totalWages
def readFromClock(clockHours):
inFile = open('clockhours.txt', 'r')
str1 = inFile.read()
print str1
str2 = inFile.read()
print str2
print
inFile.close()
while choice != '5':
if choice == '1':
readFromNext(nextWeek)
print 'Upcoming schedules'
if choice == '2':
readFromLast(lastWeek)
print 'Previous schedules'
if choice == '3':
hours = getHours(hours)
totalHours = getTotalHours(hours, totalHours)
wages = getWages(wages)
totalWages = gettotalWages(totalHours, wages)
print 'Paycheck calculator'
if choice == '4':
readFromClock(clockHours)
print 'Clock in/out times'
main()

What do you expect it to do? You have added many functions but they appear to be unused. You end up printing the menu over and over again because you are in the loop
while passWord == userId:
...
You have to do something with the choice variable and break out of that loop if you want anything else to happen.
For example:
choice = raw_input('Enter 1 to 4 from menu.')
if choice == 1:
readFromNext(nextWeek)
elif choice == 2:
readFromLast(lastWeek)
elif choice == 3:
getTotalWages(totalHours, wages)
elif choice == 4:
getHours(hours)
Obviously you will need to figure out which function maps to which user input, but currently you are not doing anything with the user's choice, merely asking them to choose over and over again with no control over the termination of the loop.

You are not changing the value of login in your while not loop.
login = 'default'
while not (login == 'yes' or login == 'no'):
print 'Please enter a yes or no'
login = raw_input('Do you want to login?')
... for example. The way you currently have it is never going to end:
while not (login == 'yes' or login == 'no'):
print
print 'Please enter a yes or no'
This is conceptually identical as:
while True:
if login == 'yes' or login == 'no':
break
print
print 'Please enter a yes or no'
So if the login is never changed, it will never end.

Related

How do I get my code to repeat itself if the desired input is not entered?

I just started python 2 weeks ago and I don't know how to make my code repeat itself when the input is something like "fox" when that is not one of the three options I'm accepting (horse, oxen, mule). Also if I want to total up the cost of 2 horse and say 3 mules by having it ask "do you want to buy any more animals", how would i do that? Any help would be very appreciated.
zoo = {}
def main():
print ("Animals available to purchase: " + "horse: 50, oxen: 35, mule: 20")
total_money = 1000
print ("You have " + str(total_money) + " to spend")
cost(total_money)
def animal_cost(total_money):
animal_type = raw_input("Please enter an animal:")
print ("Animal Type Entered: " + str(animal_type))
global animal_quantity
animal_quantity = int(raw_input("Please enter quantity of animals:"))
print ("Animal Quantity Entered: " + str(animal_quantity))
if animal_type in zoo:
zoo[animal_type] += animal_quantity
else: zoo[animal_type] = animal_quantity
while True:
if animal_type == 'horse':
return 50 * animal_quantity
if animal_type == 'oxen':
return 35 * animal_quantity
if animal_type == 'mule':
return 20 * animal_quantity
else:
cost(total_money)
def cost(total_money):
costing = animal_cost(total_money)
total_money -= costing
if total_money <= 0:
print ("No money left, resetting money to 1000.")
total_money = 1000
zoo.clear()
print ("Cost of Animals: " + str(costing))
print ("Remaining Balance:" + str(total_money))
choice = raw_input("Do you want to buy any more animals?(Y/N):")
if choice in('Y','y'):
cost(total_money)
elif choice in ('N','n'):
choice_2 = raw_input("Enter 'zoo' to see the animals you have purchased:")
if choice_2 in('zoo','Zoo'):
print zoo
choice_3 = raw_input("is everything correct?(Y/N):")
if choice_3 in ('Y','y'):
print ("Thank you for shopping!")
elif choice in ('N','n'):
print ("Restarting Transaction")
zoo.clear()
cost(total_money)
if __name__ == '__main__':
main()
You may try this enhanced version of your code:
zoo = {} # creating global dictionary for adding all animals into it.
# function to get animal cost
def animal_cost(total_money):
animal_type = raw_input("Please enter an animal:")
print ("Animal Type Entered: " + str(animal_type))
animal_quantity = int(raw_input("Please enter quantity of animals:"))
print ("Animal Quantity Entered: " + str(animal_quantity))
if animal_type in zoo:
zoo[animal_type] += animal_quantity
else: zoo[animal_type] = animal_quantity
if animal_type == 'horse':
return 50 * animal_quantity
if animal_type == 'oxen':
return 35 * animal_quantity
if animal_type == 'mule':
return 20 * animal_quantity
# getting total_money after animal purchase
def cost(total_money):
costing = animal_cost(total_money)
total_money = total_money - costing
if total_money <=0: # condition when money is less than or equal to 0.
print("No Money left, resetting money to 1000.")
total_money = 1000
print ("Cost of Animals:" + str(costing))
print ("Total Money Left:" + str(total_money))
# Recursion for buying more animals:
choice = raw_input("Do you want to buy any more animals?:")
if choice in ('Yes','y','Y','yes','YES'):
cost(total_money)
# you can use this commented elif condition if you want.
else: # elif choice in('no','No','n','N','NO'):
print("thankyou!!")
print("You have total animals: "+str(zoo))
# main function to initiate program
def main():
print ("Animals available to purchase: " + "horse, oxen, mule")
total_money = 1000
print ("You have " + str(total_money) + " to spend")
cost(total_money)
if __name__ == '__main__':
main()
This might help you out.
Have a look into this for last two lines

Increasing money when the dealer or player win the game

I am a beginner I am trying to add money if I wont to the money that I typed in the very start of the game if I won the money will be added to the input money that I had it adding but repeating its looping example I typed 500 then I won 200 price It will display 700 but if I won again and the price 300 it will show 800 and forgetting about what I won before
below is the code I will really appreciate your hep thank you
import random, sys
from random import shuffle
from _ast import Num
# define global variables for the cards
suits = ('Clubs', 'Spades', 'Hearts', 'Diamonds')
pip = ('Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King')
pipValues = {'Ace':11, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, '10':10, 'Jack':10, 'Queen':10, 'King':10}
playing = True
global score
score=0
class Card:
#When you create an instance of Card, you pass it a suit ("C", "D", "H", or "S") and a "pip" (2, 3, 4, 5, 6, 7, 8, 9, 10 J, Q, K, A).
#These values should be stored as instance variables for the new card object.
#I recommend you also have an instance variable "value" that stores the point value of the card.
#It should have an __str__ method that lets you print an individual card (such as "3S" for three of spades).
#Note that the __str__ method for Decks should take advantage of the __str__ method for Cards.
def __init__(self, suit, pip):
self.suit = suit
self.pip = pip
self.value = pipValues.get(pip)
def __str__(self):
return str(self.pip) + " of " + str(self.suit)
def __repr__(self):
return self.__str__()
class Player:
#When you create an instance of Player, it should have an instance variable "hand" that's set to an empty list,
#and an instance variable "handTotal" that's set to zero. These instance variables will be modified
#by Deck's "dealOne()" method.
#It should have an __str__ method that lets you print out a Player's hand.
def __init__(self, isDealer):
self.hand = []
self.isDealer = isDealer
self.name = "Dealer" if self.isDealer else "You"
self.other = "Dealer" if not self.isDealer else "You"
self.has = "has" if self.isDealer else "have"
def __str__(self):
return ", ".join(map(str, self.hand))
def __repr__(self):
return self.__str__()
def discardHand(self):
self.hand = []
#property
def handTotal(self):
while sum(card.value for card in self.hand) > 21 and \
any(card.pip == 'Ace' and card.value == 11 for card in self.hand):
for card in self.hand:
if card.pip == 'Ace' and card.value == 11:
card.value = 1
break
return sum(card.value for card in self.hand)
def blackjack(self):
print ("%s %s %s for a total of 21" %
(self.name, self.has, str(self)))
print ("%s %s a Blackjack! %s win%s!" %
(self.name, self.has, self.name, "s" if self.isDealer else ""))
print ("Thanks for playing. Come back again soon! ")
#chips=chips+(bet*500)
score+1
return message()
def bust(self):
print ("%s hold%s %s for a total of %s" %
(self.name, "s" if self.isDealer else "", str(self), str(self.handTotal)))
print ("%s Bust%s! %s Win%s!" %
(self.name, "s" if self.isDealer else "", self.other, "s" if not self.isDealer else ""))
print ("Thanks for Playing! Come Back Soon!")
# chips=chips-2
return message()
class Deck:
#When you create an instance of Deck, it should add 52 Card objects to an instance variable "cardList".
#It should have a shuffle() method that rearranges the cards in cardList. You can do this easily by importing the
#"random" package into Python, and using the random.shuffle() method. random.shuffle(myList) rearranges the
#elements of the list "myList" into a random order.
#It should have a dealOne() method that removes the first card from your deck's cardList, and appends it to the
#hand of a specified player.
#It should have an __str__ method that lets you print out the entire deck for debugging purposes.
freshDeck = []
for i in range(len(suits)):
for j in range(len(pip)):
freshDeck.append(Card(suits[i], pip[j]))
def __init__(self):
self.cardList = self.freshDeck[:]
def shuffle(self):
random. shuffle (self.cardList)
def dealOne(self, player):
if len(self.cardList) < 4:
print("Out of cards... shuffling a new deck...")
exit
#self.cardList = self.freshDeck[:]
#self.shuffle()
(player.hand).append(self.cardList[0])
del self.cardList[0]
#print(self.cardList)
shuffle(self.cardList)
return self.cardList
def __str__(self):
printString = ""
for i in range(len(self.cardList)):
if i % 13 == 0:
printString += "\n \t"
printString += str(self.cardList[i]) + " "
else:
printString += str(self.cardList[i]) + " "
printString += "\n"
return printString
def showHands(player, opponent):
print ('Dealer shows ' + str(opponent.hand[0]) + ' faceup')
print ('You show ' + str(player))
def turn(deck, player, other):
#First, check scores to see if either player has a blackjack:
if player.handTotal == 21:
return player.blackjack()
if other.handTotal == 21:
return other.blackjack()
#See if the dealer less 16
hitOrStand = 0
while hitOrStand != 2:
print (player.name + ' hold%s ' % ("s" if player.isDealer else "") + str(player) + ' for a total of ' + str(player.handTotal) + '\n')
if player.isDealer:
if player.handTotal < 16:
hitOrStand = 1
if player.handTotal >= other.handTotal:
hitOrStand = 2
else:
hitOrStand = input('Do you hit or stand? Enter "1" for hit and "2" for stand: ')
while hitOrStand != 1 and hitOrStand != 2:
try:
hitOrStand = int(hitOrStand)
break
except ValueError:
print ("Enter a valid integer \n")
hitOrStand = input('Do you hit hit or stand? Enter "1" for hit and "2" for stand: ')
print()
if hitOrStand == 1:
print('Card dealt: ' + str(deck.cardList[0]) + '\n')
deck.dealOne(player)
if player.handTotal == 21:
return player.blackjack()
if player.handTotal > 21:
return player.bust()
#if player.handTotal <16 :
#return player.bust()
if hitOrStand == 2:
if player.isDealer:
print ("Dealer stands at " + str(player.handTotal))
global price
price=bet*500*2
print (price )
print ("Dealer Wins!")
return message()
else:
print (player.name + ' stand at: ' + str(player.handTotal))
print()
print ("Now Dealer's Turn\n")
def message():
global playing
again = raw_input("Do you want to play again? (Y/N) : ")
if again.lower() == "n":
print("\n\n-------Thank you for playing!--------\n\n")
playing = False
return True
#who won
def betValidation():
global number
number=input("Enter amount: ")
number
if (number<5000):
print "Minimum amount is 5000!!! "
exit()
elif (number > 50000):
print "You Exceeding the Maximum Amount...."
exit()
elif (number==5000 , number<=50000):
if number%500==0:
print ""
else:
print "Invalid"
exit()
def main():
cardDeck = Deck()
global bet
bet1=betValidation()
while playing:
global chips
print "Score:",score
chips=number/500
print "You have", chips ,"chips!"
betchips=chips/2
global bet
bet=input("How much would you like to bet: ")
if(bet==0):
print "Invalid"
elif (bet>=betchips):
if bet%1==0:
player = Player(isDealer=False)
opponent = Player(isDealer=True)
player.discardHand()
opponent.discardHand()
#give each player 2 cards, alternating
cardDeck.dealOne(player)
cardDeck.dealOne(opponent)
cardDeck.dealOne(player)
cardDeck.dealOne(opponent)
#show 1 faceup card for each player
showHands(player,opponent)
#start playing
if turn(cardDeck,player, opponent):
continue
turn(cardDeck, opponent, player)
main()
I imagine your problem lies in the function blackjack() but you haven't posted that.

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

Roulette program will not recognize correct guess. Why?

The following is the roulette portion of a casino game I'm putting together, but I can't seem to get it to work correctly. It won't recognize when the player chooses the correct number, and I'm hoping someone can tell me why. Obviously, a few other parts have not been completed, but I'm just trying to get the basics running. Also, I'm pretty new at this, so feel free to critique anything else! Thanks.
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets == True:
bets = True
return bets
else:
print "You bet on: ", bets
print "Better luck next time."
bets = False
return bets
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
self.spin(bets)
# payout for bets
if bets == True:
print "You win $", bet_amount*35
self.wallet += bet_amount*35
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()
Your main error was this:
# start spin
self.spin(bets)
# payout for bets
It should read:
#start spin
bets = self.spin(bets)
# payount bets
the modified code below does it correctly. Overwriting bets with a different type isn't good style, I'd suggest using a different variable. Also win in bets doesn't need to explicitly compared to True (unless for clarification during learning).
Hope that helps, if you have further questions, just comment ;-)
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets:
return True
else:
print "You bet on: ", bets
print "Better luck next time."
return False
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
did_win = self.spin(bets)
# payout for bets
if did_win == True:
ammount = bet_amount*35
self.wallet += ammount
print "You win $", ammount
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()