Issue With Infinite While Loop in Python 3.1 - python

I am creating a travel agent game in Python 3.1. I have reached an error with my while loop. It will constantly repeat the print() response. I know this is because it is true as long as here is a response for people, but I have no clue how to fix it.
people = int(input("Will you be travelling by yourself (1), or as a group of
two (2)?: "))
while people:
if people == 1:
print("\nAh, a holiday for one! How adventurous.")
elif people == 2:
print("\nOoh, bringing a friend! Sounds like fun!")
else:
print("\nPlease enter either 1 or 2 to determine the number of
travellers.")
people = int(input("Will you be travelling by yourself (1), or as a
group of two (2)?: "))

There is no any issue with the python version regard to you question.The problem is that, loop will run infinitely because there is no condition to exit from the loop.So to exit from the loop after print statement insert break keyword as follows.
people = int(input("Will you be travelling by yourself (1), or as a group of two (2)?: "))
while people:
if people == 1:
print("\nAh, a holiday for one! How adventurous.")
break
elif people == 2:
print("\nOoh, bringing a friend! Sounds like fun!")
break
else:
print("\nPlease enter either 1 or 2 to determine the number of travellers.")
people = int(input("Will you be travelling by yourself (1), or as a group of two (2)?: "))

Related

Betting system won't seem to process the user input correctly, how can this be improved?

I'm trying to code a game of craps in which the player has a virtual 'wallet' to gamble with. I've gotten to the user input part and it's not going as planned.
Here is what I have so far:
import random
import sys
money = "500"
# start the game
a = input("Hello travler, to start the game, please type 'yes'. If you are not ready to begin your journey, type 'no' ")
if a.lower() == "no":
sys.exit()
else:
print("Welcome")
print("Hold on... I'm missing something,")
name = input("What is your name, traveler?: ")
print("Welcome,", (name))
# those who need instructions can ask for it,
# others can start the game directly.
a = input("Welcome to a game that'll determine the rest of your life. Do you need instructions? (yes) or (no)? \n")
if a.lower() == "yes":
print('''1. the player will roll two six sided dice. the sum of the two dice is the player's number for the round.
2. rolling a 7 or an 11 as your first roll win you the game, but be weary, a 2, 3, or 12 automatically causes the player to lose. no more game for you. If a 4, 5, 6, 8, 9, or 10 are rolled on this first roll, that number becomes the 'point.'
3. the fated player continues to roll the two dice again until one of two things occur: either they roll the 'point' again, causing them to win the game; or they roll a 7, causing them to be doomed to the eternals.''')
elif a.lower() == "no":
print("may luck be with you on this fateful day,", name)
print("You will start off with 500 pieces of luck, if you leave this game with over 1000 pieces of luck, you will be fated for sucsess. On the other hand, should you drop below 0 peices of luck, you will find yourself in debt to the universe, a misfortune that few recover from.")
print("You currently have", money, "luck to spare")
# betting time
while True:
bet = input("How much luck do you wish to bet? ")
if bet.isdigit() is True:
if money > bet:
print("Bet accepted")
if bet.isdigit() is True:
if bet > money:
print("How unfortunate, you do not have the luck to make this bet.")
elif bet.isdigit() is False:
print ("Sorry, luck can only be quantitated in number values.")
# if you bet higher than your money, it wont allow you to bet within after that.
The code below the line # betting time is where I am hitting my head over.
I need the code to do the following:
check if the user input is in fact a number, if it's not a number, make them enter a new input
if the user input is a number, determine if it is within the amount they have in their 'wallet' (if not, make them input a new number)
if the number is within the amount in their 'wallet' and is a digit, give the user the option to "roll dice" triggering the game to start.
If they win, they need to be granted double what they bet, if they lose, they need to lose the amount they bet. The wallet will need to update after each play, giving the user the option to play again with their updated wallet (so if they bet 50 and win, their new balance will be 550. The process continues until the user either reaches 1000 or 0, causing the game to end either way.)
For checking if the user's bet is a number use the .isnumeric() function on your bet like:
bet.isnumeric()
to do the second thing you needed help with you could do:
if bet < wallet: blah blah blah elif
bet > wallet: print("You do not enough money")
around like that it with actual good syntax
to do dice you could use the random.randint() function like this:
random.randint(1,6)
I hope that helps!

How do I incorporate an if statement inside of another if statement?

I'm sort of a beginner at Python; I'm trying to write a text adventure game that prompts the user to explore a room given different options. After the user enters "1," I want the game to enter more choices through another if statement. How should I do that? And if this way is incorrect, what function should I use instead? I've tried putting another if statement in, but that leads to the program producing different results, like outputting a different part of the code instead of the one I want. Here is my code right now:
Name = input("What is your name, visitor?")
print(Name + (", you are being watched. Proceed carefully. A breeze of howling wind enters the room. Within the echo, something reaches out to you and offers a candle. Do you want to light the candle?"))
print("1 for YES")
print("2 for NO")
try:
Choice = int(input("What do you choose?"))
print("Choice:", Choice)
except ValueError:
print("Please input 1 or 2 only...")
Choice = int(input("What do you choose?"))
if Choice == 1 :
print("A flickering candlelight bursts forth. You are blinded momentarily. When your eyes adjust, you see a table, drawer, and lamp in the room. You can check:")
print("1 for Table")
print("2 for Drawer")
print("3 for Lamp")
if Choice == 2 :
print("You sit in silence, wondering what to do. Without sight, you're losing options. Eventually, you muster up the courage to stand up. You can't hear your own steps. Fear climbs up your throat. The floor gives way under your feet. You are swallowed by the darkness. GAME OVER.")
quit()
if not 1:
print("Please enter either 1 or 2.")
if not 2:
print("Please enter either 1 or 2")```
There are several issues with this code, but to address your question: nest the if within the outer if:
if Choice == 1 :
print("A flickering candlelight bursts forth. You are blinded momentarily. When your eyes adjust, you see a table, drawer, and lamp in the room. You can check:")
print("1 for Table")
print("2 for Drawer")
print("3 for Lamp")
Choice = int(input("What do you choose?"))
if Choice == 1:
# Do table stuff
elif Choice == 2:
# Do drawer stuff
elif Choice == 3:
# Do lamp stuff
else:
# Handle error

in range loop skipping through

salary=0
salaryArray=[]
loop=0
noYears=int(input("How many years do you want to do salaries for? "))
for i in range(0,noYears):
while loop==0:
print()
print("You can add multiple sources of income, one at a time")
salaryType=input("Do you want to put in your salary hourly or yearly? (h/y) ")
if salaryType=="y":
salarySection=float(input("What is your salary? "))
salary=salarySection+salary
else:
salaryHourly=float(input("What are you payed per hour? "))
salaryWeekly=float(input("How many hours per week will you work? "))
salaryYearly=float(input("How many weeks per year will you work? "))
print()
salarySection=salaryHourly*salaryWeekly*salaryYearly
salary=salary+salarySection
repeat=input("Do you wish to add another source of income? (y/n) ")
if repeat=="n":
print("This year's anual salary is", salary)
salaryArray.append(salary)
loop=1
For some reason the for i in range(0,noYears) isn't working?
It just moves on to the next line of code after doing it through once - even though I put the answer to noYears as 3.
Anyone know why this might be as I cannot see what is wrong?
:)
The code isn't working because the while loop never executes. You could solve this two ways.
Use a break statement instead of setting loop to 1:
#previous code
repeat=input("Do you wish to add another source of income? (y/n) ")
if repeat=="n":
print("This year's anual salary is", salary)
salaryArray.append(salary)
break
Reset the variable loop to 0 inside of the for loop:
for i in range(0,noYears):
loop = 0
while loop==0:
# remaining code

This python works, but looking for a more elegant solution (Try and Catch with 1/0 hack)

I am trying to prevent user from entering a number of team members that exceeds the player pool.
while True:
try:
numMembers = int(input("How many students per team (2, or 3) "))
if numMembers > totalStudents:
errorHand = 1/0
except:
print("Too many members per team, please try again")
continue
else:
break
Just trying to avoid the hackity div/0 trick I came up with.
Since you need to do something different in each error case, there isn’t much complexity that can be taken out, but you can reduce the try to a specific exception in a specific place and avoid the division by zero hack:
while True:
try:
numMembers = int(input("How many students per team (2, or 3) "))
except ValueError:
continue
if numMembers > totalStudents:
print("Too many members per team, please try again")
continue
break

Python beginner, text-based game

I'm fairly new to the programming game; I'm 3/4 of the way through Learn Python the Hard Way and I had a question about a little text-based game I made... So in this game my guy is stranded on a desert island and you have the option(raw input) of going left right or into the jungle. After choosing a direction, you're given the option to choose how many miles to walk. Each direction is supposed to have a different end result (and mile distance).
If you enter a number that is less than the number of miles to the destination, you're prompted with a choice to either "turn around or "keep going". If you enter turn around, you're taken back to the beginning, where you're again asked to choose a direction. If you enter keep going, the program returns to miles(), where you can choose a new amount of miles to walk.
def miles():
print "How many miles do you walk?"
miles_choice = raw_input("> ")
how_much = int(miles_choice)
if how_much >= 10:
right_dest()
elif how_much < 10:
turn()
else:
print "You can't just stand here..."
miles()
Ok so here's two questions:
How would I make it so that if the user originally enters a number of miles less than the destination distance, and the second mile input + the first mile input == the amount of miles to the destination, it will add the inputs and run my destination function, not just repeat miles().
Since all three final destinations will have different distances, should I write three separate mile functions? Is there a way to make it so that depending on the original direction chosen, miles() will run the different endpoints?
I'm sorry if this doesn't make a lick of sense... I'm still learning and I'm not sure how to fully explain what I'm trying to get across.
You could store the amount of miles to walk in each direction in a dict, and then check the dict to see if the user has walked far enough:
distances = {
'right': 7,
'left': 17,
'forward': 4
}
direction_choice = raw_input("> ")
miles_choice = raw_input("> ")
if how_much >= distances['direction_choice']:
right_dest()
elif how_much < distances['direction_choice']:
turn()
else:
print "You can't just stand here..."
miles()
Be sure to properly validate and cast the user input, which I have not addressed. Good luck!
I don't fully understand the requirements (the intended behavior and constraints). However, you might consider passing a parameter to your function (through and argument) to convey the maximum number of miles which the play could go in that direction).
For example:
#!/usr/bin/env python
# ...
def miles(max_miles=10):
print "How many miles do you walk?"
while True:
miles_choice = raw_input("> ")
try:
how_much = int(miles_choice)
except ValueError, e:
print >> sys.stderr, "That wasn't a valid entry: %s" % e
continue
if max_miles > how_much > 0:
break
else:
print "That's either too far or makes no sense"
return how_much
... in this case you pass maximum valid number of miles into the function through the "max_miles" argument and you return a valid integer (between 1 and max_miles) back.
It would be the responsibility of this function's caller to then call right_dest() or turn() as appropriate.
Note that I've removed your recursive call to miles() and replace it with a while True: loop, around a try: ... except ValueError: ... validation loop. That's more appropriate than recursion in this case. The code does a break out of the loop when the value of how_much is valid.
(By the way, if you call miles() with no parameter then the argument will be set to 10 as per the "defaulted argument" feature. That's unusual to Python (and Ruby) ... but basically makes the argument optional for cases where there's a sensible default value).
#Question #1: I used Class intern variables. You will maybe need them for further programming parts and should take it to zero when you are done on one direction, to start with zero for next step/lvl.
#Question #2: Dictionaries are the best way to do so,self.dest. Parameter pos used as key to get the value from the dictionary.
class MyGame:
def __init__(self):
self.current_miles = 0
self.dest = {'Left' : 10, 'Into the jungle' : 7, 'Right' : 22}
def miles(self,pos):
print "How many miles do you walk?"
miles_choice = raw_input("> ")
self.current_miles += int(miles_choice)
if self.current_miles >= self.dest.get(pos):
self.miles("Right")
elif self.current_miles < self.dest.get(pos):
print "you went "+ str(self.current_miles) + " miles"
else:
print "You can't just stand here..."
self.miles(pos)
mg = MyGame()
mg.miles('Into the jungle')

Categories