I need your help regarding the loop in a Python program. Can anyone show me how to loop the program below, like when I enter a wrong value it will keep prompting me to re-enter the value until it gets the correct values and moves to the next state.
I am trying the "while" loop but unsuccessful.
# Determine cleaning type
def CleaningType ():
while True:
# Prompt user to input Light or Complete cleaning type
cleanType = int(input("\n\tPlease select your cleaning type:\n(1) Light\n(2) Complete\n"))
if (cleanType == 1):
cleanCost = 20
elif (cleanType == 2):
cleanCost = 40
else:
# Display error msg
print("\t*** Invalid - Please re-enter your value...")
False
return (cleanType, cleanCost)
# Get number of rooms --------------------------------
def GetNumRooms ():
while True
# Prompt and get user reponse for number of rooms
numRooms = int(input('How many rooms would you like to be serviced (1-10)?\n'))
if (numRooms > 0 and numRooms <= 3):
print("\n\tYour cleaning size is small which costs $15 per room")
roomCost = 10
elif (numRooms > 3 and numRooms <= 5):
print("\n\tYour cleaning size is small which costs $25 per room")
roomCost = 15
elif (numRooms > 5 and numRooms <= 10):
print("\n\tYour cleaning size is small which costs $35 per room")
roomCost = 20
False
return (numRooms, roomCost)
You could use break to end the while loop when one of the current answers are submitted.
You can use a break statement to end a loop. Also, a function can call itself, like this:
# Determine cleaning type
def CleaningType ():
while True:
# Prompt user to input Light or Complete cleaning type
cleanType = int(input("\n\tPlease select your cleaning type:\n(1) Light\n(2) Complete\n"))
if (cleanType == 1):
cleanCost = 20
break
elif (cleanType == 2):
cleanCost = 40
break
else:
# Display error msg
print("\t*** Invalid - Please re-enter your value...")
CleaningType()
CleaningType()
Related
This question already has answers here:
Breaking out of nested loops [duplicate]
(8 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
As I am a new learner in python, I was trying to do an exercise having while loop in it.
I have written a piece of code which will ask user to enter his details.
After getting all the details the program should stop, but In my case after entering Account Number, it again start asking Mobile number to enter.
Please have a look at the code and suggest where I am going wrong.
bnkName = ["SBI", "PNB", "CBI", "ICICI", "BOB"]
targetattmpt = 10
appliedattmpt = 1
while (appliedattmpt <= targetattmpt):
mobilenum = input("Please Enter your Mobile Number:\n")
if (len(mobilenum) == 10):
while (True):
Bankname = input("Please Enter your Bank Name\n").upper()
if Bankname in bnkName:
print("Valid Bank\n")
print("Please enter your Account Number\n")
accnum = input("Account Number:\n")
print(accnum)
break
else:
print("Invalid Bank")
else:
print(mobilenum, "IS NOT VALID!!!", "You have", targetattmpt - appliedattmpt, "attempts left\n")
appliedattm = appliedattm + 1
if (appliedattmpt > targetattmpt):
print("Account locked!!")
The break statement inside the inner loop will break the inner loop but not the outer. You should re-think the logic and maybe add bool variable to check if inner loop broke so you can break the outer loop. For/while loops have else statements which will check if the loop called finished successfully or was aborted with a break. In the case of a while loop, the else will be executed if the condition in the is no longer true.
Take a look at: https://book.pythontips.com/en/latest/for_-_else.html
To give you an example:
j = 0
bank = True
while(j < 2):
print('check_this')
i = 0
while(i < 2):
print('check that')
if bank:
break
else:
i += 1
else:
break
print('I checked both !')
j += 1
Output:
check_this
check that
I checked both !
check_this
check that
I checked both !
Now change the bank to False
j = 0
bank = False
while(j < 2):
print('check_this')
i = 0
while(i < 2):
print('check that')
if bank:
break
else:
i += 1
else:
break
print('I checked both !')
j += 1
Output:
check_this
check that
check that
This question already has answers here:
Unbound Local Error
(2 answers)
Closed 2 years ago.
I got a error for refrencing the variable increment before I declared it. When I open the store and buy more money per click, I get a flood of errors. I require help please.
here's my code:
from time import sleep as wait
import os
coin = 0
autoclick = 0
incrementation = 25
uppergrades_bought = 1
increment = 1
clear = lambda: os.system('clear')
def store():
cmd = int(input("What do you want to do? 1 to buy autoclick and 2 to buy more money per click").strip())
if cmd == 1:
coin-incrementation*uppergrades_bought
autoclick+=1
elif cmd == 2:
coin-incrementation*uppergrades_bought
increment+=1
clear()
while 1 == 1:
print("You have {} coins!".format(coin))
coins = input("Press enter")
clear()
coin+=increment
if coin>=incrementation*uppergrades_bought:
storeyn = input("Hi, would you like to go into the store? you have enough to buy the next uppergrade")
if storeyn.strip().lower() == "yes" or storeyn.strip().lower() == "y":
store()
elif storeyn.strip().lower() == "no" or storeyn.strip().lower() == "n" :
pass
else:
pass
else:
pass
Your store function doesn't have access to the values that it's trying to update. There are many ways to address this -- global/nonlocal as suggested by another answer requires the smallest amount of code to change right now but it's likely to cause you a lot of problems later as your program grows and it's something you should completely avoid as a beginner IMO. My suggestion would be to restructure your program so that all this information is stored in a class:
from time import sleep as wait
import os
class ClickerGame:
def __init__(self):
self.coin = 0
self.autoclick = 0
self.incrementation = 25
self.upgrades_bought = 1
self.increment = 1
def click(self) -> None:
"""Click once, gaining coins"""
self.coin += self.increment
def can_afford_upgrade(self) -> bool:
"""Check if there are enough coins to afford an upgrade"""
return self.coin >= self.incrementation * self.upgrades_bought
def buy(self, upgrade: int) -> None:
"""1 to buy autoclick and 2 to buy more money per click"""
if upgrade == 1:
self.autoclick += 1
elif upgrade == 2:
self.increment += 1
else:
raise ValueError(f"Invalid upgrade option {upgrade}")
self.coin -= self.incrementation * self.upgrades_bought
self.upgrades_bought += 1
def store(self) -> None:
"""Visit the store, prompting the user for a purchase."""
try:
cmd = int(input(
f"What do you want to do? {self.buy.__doc__}"
).strip())
self.buy(cmd)
except ValueError as e:
print(e)
def clear() -> None:
os.system('clear')
clicker = ClickerGame()
while True:
print(f"You have {clicker.coin} coins!")
input("Press enter")
clear()
clicker.click()
if clicker.can_afford_upgrade():
storeyn = input(
"Hi, would you like to go into the store? "
"you have enough to buy the next upgrade"
).strip().lower()
if storeyn in {"yes", "y"}:
clicker.store()
elif storeyn in {"no", "n"}:
pass
else:
pass
else:
pass
I would like to achieve the following.
I have a proof of concept I am working.
I have Individual "Named RFID"Cards, then I have "Action RFID Cards".
So I might have cards like this:
Names
John - 12345
Mary - 12346
Actions
Start Work - 111
Finish Work - 222
Lunch - 333
So John Swipes his own card, then swipes an action card, which logs his action.
-Start Script
-Wait for User Card Input
-Once Input Received and Validated
- Wait for Action Card Input
- Start Timer
- Wait until Action Card Input matches a valid Action
- If a match, exit back to the main loop
- If no match, wait for one minute, then exit
-Continue Main Loop
I am reusing code from :
How would I stop a while loop after n amount of time?
import time
timeout = time.time() + 60*5 # 5 minutes from now
while True:
test = 0
if test == 5 or time.time() > timeout:
break
test = test - 1
and a Python Game example which waits and loops forever playing the game
https://dbader.org/blog/python-intro-reacting-to-user-input
My code for testing is as follows (I am not doing a card or action lookup at this point, expecting the user to be 12345 and card to be 54321: (the requirement for four spaces for indent has possibly broken Python Indent)
#
# Guess My Number
#
import random
import time
# Set our game ending flag to False
game_running = True
while game_running:
# Greet the user to our game
print()
print("I'm thinking of a number between 1 and 10, can you guess it?")
# Have the program pick a random number between 1 and 10
#secret_number = random.randint(0, 10)
secret_number = 12345
card_number_list = 54321
# Set the player's guess number to something outside the range
guess_number = -1
# Loop until the player guesses our number
while guess_number != secret_number:
# Get the player's guess from the player
print()
guess = input("Please enter a number: ")
# Does the user want to quit playing?
if guess == "quit":
game_running = False
break
# Otherwise, nope, the player wants to keep going
else:
# Convert the players guess from a string to an integer
guess_number = int(guess)
# Did the player guess the program's number?
if guess_number == secret_number:
print()
print("Hi you have logged on, please swipe Card- if you don't Swipe - will timeout in 1 minute!")
timeout = time.time() + 60*1 # 1 minutes from now
while True:
test = 0
if test == 1 or time.time() > timeout:
card = input("Please enter your card number")
card_number = int(card)
if card_number == card_number_list:
print("Thanks for your card number")
test = 1
break
test = test - 1
# Otherwise, whoops, nope, go around again
else:
print()
print("You need to use your wrist band first...")
# Say goodbye to the player
print()
print("Thanks for playing!")
But instead of exiting, the script waits...
Any feedback appreciated - I have basic python skills and am trying to reuse existing code where possible (with thanks to the creators!).
The python input() function will always wait for response from the keyboard before returning. Take a look at this answer for a technique to accomplish what you want.
My program keeps letting me continue forever even if I don't get it right except if I put in a number larger than 3.
You'll see what I mean if you try out my code:
#Ghost Game
while True:
print ('Welcome To...')
from random import randint
print ('Ghost Game')
feeling_brave = True
score = 0
while feeling_brave:
ghost_door = randint(1,3)
print('Three doors ahead...')
print('A ghost behind one.')
print('which door do you open?')
door = input('1,2 or 3')
door_num = int(door)
if door_num == ghost_door:
print('GHOST!')
feeling_brave = False
if door_num > 3:
print('GHOST!')
feeling_brave = False
else:
print('No Ghost')
print('You enter the next room...')
score = score + 1
print('Run away!')
print('GAME OVER YOU SCORED', score)
You need to use elif instead of the second if here:
if door_num == ghost_door:
print('GHOST!')
feeling_brave = False
elif door_num > 3:
print('GHOST!')
feeling_brave = False
else:
print('No Ghost')
print('You enter the next room...')
score = score + 1
otherwise else is executed independently of the first if test if door_num is not greater than 3.
if is a single statement, with optional elif and else blocks attached; Python will always execute at most one of the attached blocks (and else otherwise).
By using two separate if statements, the second if asks Python to execute one of two blocks; print GHOST when door_num is greater than 3, or increase the score, and do so regardless of what the first if door_num == ghost_door test outcome is.
So, I'm just fooling around in python, and I have a little error. The script is supposed to ask for either a 1,2 or 3. My issue is that when the user puts in something other than 1,2 or 3, I get a crash. Like, if the user puts in 4, or ROTFLOLMFAO, it crashes.
EDIT: okay, switched it to int(input()). Still having issues
Here is the code
#IMPORTS
import time
#VARIABLES
current = 1
running = True
string = ""
next = 0
#FUNCTIONS
#MAIN GAME
print("THIS IS A GAME BY LIAM WALTERS. THE NAME OF THIS GAME IS BROTHER")
#while running == True:
if current == 1:
next = 0
time.sleep(0.5)
print("You wake up.")
time.sleep(0.5)
print("")
print("1) Go back to sleep")
print("2) Get out of bed")
print("3) Smash alarm clock")
while next == 0:
next = int(input())
if next == 1:
current = 2
elif next == 2:
current = 3
elif next == 3:
current = 4
else:
print("invalid input")
next = 0
Use raw_input() not input() the latter eval's the input as code.
Also maybe just build a ask function
def ask(question, choices):
print(question)
for k, v in choices.items():
print(str(k)+') '+str(v))
a = None
while a not in choices:
a = raw_input("Choose: ")
return a
untested though
since the input() gives you string value and next is an integer it may be the case that crash happened for you because of that conflict. Try next=int(input()) , i hope it will work for you :)