Break or continue a while loop from a function - python

I'm trying to have a while loop ask a series of question and restart when the last question is asked. The thing is, I want the user to have the ability to quit by typing a specific word at any question. I also want as little code as possible in the loop, so the if/elif statements lays in functions.
My question is: Can I continue or break a loop from a function?
My code:
def check_gender(q):
if q == "f":
number_women = number_women + 1
elif q == "m":
number_men = number_men + 1
elif q == "foo":
#break the loop
else:
print("Please answer M or F: ")
q = input("Are you a male or female (M/F)? ").lower()
check_gender(q)
def check_age(q):
if not(16 <= int(q) <= 25):
print("You are not in the age range for this survey")
#Jump back to first question here
if q == "foo":
#break the loop
while True:
gender = input("Are you a male or female (M/F)? ").lower()
check_gender(gender)
age = input("Please enter your age: ")
check_age(age)
#And so on with questions
Is this possible?

You can return some(for example bool) value from function check_age(q) and check it.
def check_age(q):
if not(16 <= int(q) <= 25):
print("You are not in the age range for this survey")
#Jump back to first question here
if q == "foo":
return True
else:
return False
while True:
gender = input("Are you a male or female (M/F)? ").lower()
check_gender(gender)
age = input("Please enter your age: ")
if check_age(age):
break

The best way probably is to raise a custom Exception from inside the question functions as follows:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
NUMBER_MEN, NUMBER_WOMEN = 0, 0
class ExitLoop(Exception):
pass
def check_gender(reply):
global NUMBER_WOMEN, NUMBER_MEN
while True:
if reply == "f":
NUMBER_WOMEN += 1
return
elif reply == "m":
NUMBER_MEN += 1
return
elif reply == "foo":
raise ExitLoop
else:
print("Please answer M or F: ")
reply = input("Are you a male or female (M/F)? ").lower()
def check_age(reply):
if reply == "foo":
raise ExitLoop
if not 16 <= int(reply) <= 25:
print("You are not in the age range for this survey")
return False
return True
while True:
try:
gender = input("Are you a male or female (M/F)? ").lower()
check_gender(gender)
age = input("Please enter your age: ")
inrange = check_age(age)
if not inrange:
continue
except ExitLoop:
break
I made a few other changes to your code to make it a bit more pythonic. Be careful by the way, the code above fails when the user enters anything but 'foo' or a number in reply to the age question.
By the way, if you want to ask your user a lot of questions, you might want to check out the excellent Click package.
Hope this helps!

You should try this code, is someone put other letter the loop will break
def check_gender(q):
if q == "f":
number_women = number_women + 1
elif q == "m":
number_men = number_men + 1
# elif q == "foo":
#break the loop
else:
print("Please answer M or F: ")
q = input("Are you a male or female (M/F)? ").lower()
check_gender(q)
def check_age(q):
if not(16 <= int(q) <= 25):
print("You are not in the age range for this survey")
#Jump back to first question here
#if q == "foo":
#break the loop
while True:
gender = input("Are you a male or female (M/F)? ").lower()
if gender != "f" and gender != "m":
break
else:
check_gender(gender)
age = input("Please enter your age: ")
try:
ageValue = int(age)
check_age(age)
except ValueError:
print ("You must enter a number")
break

Related

Question about the while loop for supermarket checkout case

I tried to make simple codes for supermarket checkout, but I have an issue with the while loop statement. Please check the code below and picture I sent.
I don't know why after I input "n", it does not go back to the loop.
def start():
quan = 1
price = 0
end = False
total = 0
while end == False:
food = (input("Enter your food: "))
quan = int(input("Enter quantative: "))
price = float(input("Price of food: "))
disscount = float(input("Do you have disscount? enter '0' for no disccount. "))
end = input("Finish? y or n: ")
sum = price * quan
sub_total = sum - (sum * disscount * 0.01)
total += sub_total
if end == "y":
print("Total price is ", total)
end = True
elif end == "n":
end = False
else:
again = input("Wrong message! Do you want to try again? enter 'y' to try again or 'n' to end: ")
if again == "y":
return start()
elif again == "n":
print("Bye!")
break
start()
The if again block needs to be indented:
else:
again = input("Wrong message! Do you want to try again? enter 'y' to try again or 'n' to end: ")
if again == "y":
return start()
elif again == "n":
print("Bye!")
break
Otherwise, you hit your if statement without necessarily having defined again. If it is not defined, you get the error you cite.

i need help combining loop with if statement

i want to add loop inside my code like if the input was no in (maty) the code will say try again and it will loop to Step on mat
mat = input("Step on mat : ")
maty = input("Is your weight between 40 and 50 ? : ")
if maty == ("yes"):
h = input("Select your height on the scale : ")
j = input("Is "+ h +" your height ? : ")
if j == ("yes"):
print("You are ready to go !")
else:
print("Try again")
if maty == ("no"):
print("try again")
im a beginner in python
thanks
Answer:
Below i have used a while loop that will run until one will give input as "yes". and also to perform a case-insensitive comparison of user input("yes"/"no") , i have modified your code as maty.lower().
maty = "no"
while maty.lower() == "no":
maty = input("Step on mat :")
maty = input("Is your weight between 40 & 50 ? : ")
if maty.lower() == "yes":
h = input("Select your height on the scale :")
j = input("IS “+h +” your height ? :")
if j == "yes":
print("You are ready to go! ")
else:
print("Try again")
if maty == "no":
print("try again")
A while loop should do the job:
while maty == "no":
mat = input("Step on mat : ")
maty = input("Is your weight between 40 and 50 ? : ")
if maty == ("yes"):
h = input("Select your height on the scale : ")
j = input("Is "+ h +" your height ? : ")
if j == ("yes"):
print("You are ready to go !")
else:
print("Try again")
if maty == ("no"):
print("try again")
You can use a while loop.
mat = 'no'
tries = 0
while (mat != 'yes') and (tries < 5):
mat = input("Step on mat : ")
if mat != yes:
print('Please answer "yes" to continue')
tries += 1
continue
elif tries == 5:
print('Please restart program and try again')
maty = input("Is your weight between 40 and 50 ? : ")
if maty == ("yes"):
h = input("Select your height on the scale : ")
j = input("Is "+ h +" your height ? : ")
if j == ("yes"):
print("You are ready to go !")
else:
print("Try again")

Have couple mistakes in python with while and elif statements

from random import randint
play = "yes"
while play == "yes":
choice = int(input("Would you like to play yourself(1) or let machine(2) play? press '1' or '2': "))
if choice == 1:
print("You chose to play yourself")
num = randint(1,9999)
counter = 0
while True:
num_guess = int(input("Guess the number: "))
if num_guess == 0:
print("Player has left the game")
break
else:
if num_guess > num:
print("Your guess is too high")
elif num_guess < num:
print("Your guess is too low")
elif num_guess == num:
print("Yay,you found it")
print("It took you " + str(counter) + " tries to guess the number")
break
counter += 1
elif choice == 2:
print("You chose to let the machine play")
your_num = int(input("Enter your number: "))
lowest = 1
highest = 9999
counter = 0
machine_guess = randint(1,9999)
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
else:
while True:
print("My guess is ",machine_guess)
is_it_right = input("Is it too small(<) or too big(>) or machine found(=) the number?: ")
if is_it_right == ">":
if machine_guess > your_num:
highest = machine_guess
counter += 1
else:
print("!!!Don't cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" < " + str(your_number) + ",so you should have written '<' instead of what you wrote.Continue ")
elif is_it_right == "<":
if machine_guess < your_num:
lowest = machine_guess + 1
counter += 1
else:
print("!!!Don't Cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" > " + str(your_number) + ",so you should have written '>' instead of what you wrote.Continue ")
elif is_it_right == "=":
if machine_guess == your_num:
if your_num == machine_guess:
counter += 1
print("Yayy,I found it")
print("It took me " + str(counter) + " tries to guess the number")
else:
print("You cheated and changed the number during the game.Please play fairly")
your_number = input("What was your number?: ")
print(str(machine_guess) +" = " + str(your_number) + ",so you should have written '=' instead of what you wrote ")
break
elif is_it_right == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
machine_guess = (lowest+highest)//2
elif choice == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player has left the game")
break
request = input("Do you want to play again? Answer with 'yes' or 'no': ")
if request == "no":
print("You quitted the game")
break
elif request == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
This is my code for game "guess my number",here the complicated ones is me trying to make the program prevent user from cheating (It is a university task,due in 3 hours)
So choice 1 is when user decides to play game "guess my number" and 2nd choice when computer plays the game.The problem that I have is :
I can't make the code make the user input the number in range of(1,9999) and THEN continue the process
As you see I have a lot of "if ... == 0" --> .In task it is said that whenever(any of inputs) user types 0 the game has to stop.The others work well but the one in choice 2 the first if is not working
If somebody has solution for this,please help.I would be grateful
Whenever you want to ask a question repeatedly until the correct input is given, use a while loop
print("You chose to let the machine play")
your_num = -1
while your_num < 0 or your_num > 9999:
your_num = int(input("Enter your number [0..9999]: "))
1- To force the user to input a number in the range of (1,9999), you must have an a condition like:
while True:
try:
num_guess= int(input("Enter your number in range 1-9999: "))
except ValueError:
print("That's not a number!")
else:
if 1 <= num_guess <= 9999:
break
else:
print("Out of range. Try again")
Edit: I didn't understand which input you wanted to keep in the range of 1-9999. I gave answer with num_guess but you can use it with your_num, too.
2- Add play = "no" line to the condition when the user inputs 0:
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
play = "no"
break

How do I make python react to strings? [duplicate]

This question already has answers here:
In Python, how do I check that the user has entered a name instead of a number?
(3 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
Let's get straight to the problem: when i run the code, and type letters instead of numbers to the first input my python gets an error. How do i make my python know that if someone types in letters instead of numbers should get warned and repeat the code? Im trying to fix it from about two hours.
Thank you for help
Also sorry for my really bad english
import time
import random
def repeatt():
od = int(input("Wpisz do ktorej liczby liczba ma byc losowana: "))
doo = int(input("Do ktorej: "))
if od >= doo:
print("Jeszcze raz :")
repeatt()
elif od <= doo:
wylosowana = random.randint(od, doo)
print("Wylosowana liczba: ", wylosowana)
print("Witaj! Od czego chcialbys zaczac?:")
print(
"""
1. forin slowo
2. oblicz ile ja zyje
3. oblicz, ile mam zaplacic
4. tekst
5. losowanie liczby
"""
)
choice = int(input("Wpisz liczbe: "))
if choice == 1:
slowo = input("Wprowadz slowo: ")
for letter in slowo:
print(letter)
elif choice == 2:
obliczanie = int(input("Wprowadz, ile masz lat: "))
oblicz = obliczanie * 60 * 60
print("Zyjesz juz ponad ", obliczanie * 60 * 60, "sekund")
elif choice == 3:
pieniadze = int(input("Ile podczas miesiacu zarabiasz?: "))
print("Na jedzenie: ", pieniadze / 5)
elif choice == 4:
wiadomosc = input("Wpisz jakąs wiadomosc: ")
def repeat():
wybor = input("upper, lower, title?: ")
if wybor == "upper":
print(wiadomosc.upper())
elif wybor == "lower":
print(wiadomosc.lower())
elif wybor == "title":
print(wiadomosc.title())
else:
print("Wpisz upper, lower lub title")
wybor = input("upper, lower, title?: ")
if wybor == "upper":
print(wiadomosc.upper())
elif wybor == "lower":
print(wiadomosc.lower())
elif wybor == "title":
print(wiadomosc.title())
else:
print("Wpisz proprawnie")
repeat()
elif choice == 5:
od = int(input("Wpisz liczbe od ktorej ma byc losowana: "))
doo = int(input("Do ktorej: "))
if od >= doo:
print("Jeszcze raz :")
repeatt()
elif od <= doo:
wylosowana = random.randint(od, doo)
print("Wylosowana liczba: ", wylosowana)
else:
print("Tylko liczby")
else:
print("Wpisz liczbe od 1 do 3")
choice = int(input("Wpisz liczbe: "))
Replace the above line with below code
While True:
choice = input("Wpisz liczbe: ")
if choice.isdigit():
choice = int(choice)
# your code of if conditions
else:
print("please enter valid input")
continue
while True:
try:
choice = int(input("Wpisz liczbe: "))
break
except ValueError:
print("No letters allowed, please try again")
def repeatt():
def redo(): #Repeating function
try:
od = int(input("Wpisz do ktorej liczby liczba ma byc losowana: "))
except: #If the user enters a string instead of int it will go back to redo() which will repeat until user enters a int.
print("Enter A Number!")
redo()
redo() #Leads to the input
repeatt()

I am trying to find out how to convert python code to pseudocode, it seems easy with other code but I am not sure about my own

I am still working with the same code as before (I will post lower), I just need help converting the first 10-15 lines to pseudocode so I have an idea on how to do it myself.
Code works, indents are weird because I quickly added spaces to put into code.
Apologies for the non professional code, I am still new to python!
Also, please don't do the whole of the pseudocode, just upto the end of the first while true loop so I can figure it out and do the rest myself. thank you :)
#Taran Gill - S1714318
#Please Open in Python and not IDLE
#Code for car hire
import sys
import pc
from datetime import date
import time
import os
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
#Opening Statement
while True:
opening = input("Welcome, would you like to hire a car? Please state
'Yes' or 'No'\n")
if opening.lower() == 'yes':
print ("Thats good! First we need to take some details")
break
if opening.lower() == 'no':
print ("Hope you have a good day!")
print ("Exiting...")
time.sleep(1)
sys.exit()
break
else:
print ("Invalid answer")
print ("Restarting...")
time.sleep(1)
restart_program()
continue
#Asks user for First Name
correct_name1 = False
while correct_name1 == False:
firstName = input("Please enter your First Name\n")
if (firstName.replace (' ','').isalpha()==False):
print("Not Acceptable")
continue
print ("Your First Name is", firstName.title())
while True:
correct1 = input("Is this correct?\n")
if correct1.lower() == "yes":
correct_name1 = True
break
if correct1.lower() == "no":
correct_name1 = False
break
else:
print ("Please say yes or no")
#Asks user for Last Name
correct_name2 = False
while correct_name2 == False:
lastName = input("Please enter your Last Name\n")
if (lastName.replace (' ','').isalpha()==False):
print("Not Acceptable")
continue
print ("Your Last Name is", lastName.title())
while True:
correct2 = input("Is this correct?\n")
if correct2.lower() == "yes":
correct_name2 = True
break
if correct2.lower() == "no":
correct_name2 = False
break
else:
print ("Please say yes or no")
#Asks user for House Number
correct_name3 = False
while correct_name3 == False:
try:
houseNumber = int(input("Please enter your House Number\n"))
if houseNumber < 1 or houseNumber > 2500:
print ("Please put a number in between 1 and 2500")
continue
print ("Your House Number is", houseNumber)
except ValueError:
print ("Invalid Format")
continue
while True:
correct3 = input("Is this correct?\n")
if correct3.lower() == "yes":
correct_name3 = True
break
if correct3.lower() == "no":
correct_name3 = False
break
else:
print ("Please say yes or no")
#Asks user for Street Name
correct_name4 = False
while correct_name4 == False:
try:
streetName = input("Please enter your Street Name\n")
if (len(streetName) <=4 or streetName.replace (' ','').isalpha()==False):
print("Not Acceptable")
continue
print ("Your Street Name is", streetName.title())
except ValueError:
print ("Invalid Format")
continue
while True:
correct4 = input("Is this correct?\n")
if correct4.lower() == "yes":
correct_name4 = True
break
if correct4.lower() == "no":
correct_name4 = False
break
else:
print ("Please say yes or no")
#Asks user for City
correct_name5 = False
while correct_name5 == False:
try:
city = input("Please enter your City\n")
if (len(city) <3 or city.replace (' ','').isalpha()==False):
print("Not Acceptable")
continue
print("Your City is",city.title())
except ValueError:
print ("Invalid Format")
continue
while True:
correct5 = input("Is this correct?\n")
if correct5.lower() == "yes":
correct_name5 = True
break
if correct5.lower() == "no":
correct_name5 = False
break
else:
print ("Please say yes or no")
#Asks user for Post Code
correct_name6 = False
while correct_name6 == False:
postcode = input ("Please enter your Post Code\n")
try:
checkpc = pc.parse_uk_postcode(postcode)
except ValueError:
print ("Invalid Post Code, Please try again")
continue
else:
print ("Your Post Code is", postcode.upper())
while True:
correct6 = input("Is this correct?\n")
if correct6.lower() == "yes":
correct_name6 = True
break
if correct6.lower() == "no":
correct_name6 = False
break
else:
print ("Please say yes or no")
#Asks user for Date Of Hire
correct_name7 = False
while correct_name7 == False:
dateOfHire = input("Please enter the date of start of hire in the format - dd/mm/yyyy\n")
try:
valid_date = time.strptime(dateOfHire, '%d/%m/%Y')
except ValueError:
print("Invalid format, please try again")
continue
else:
print("The date of start of hire is", dateOfHire)
while True:
correct7 = input("Is this correct?\n")
if correct7.lower() == "yes":
correct_name7 = True
break
if correct7.lower() == "no":
correct_name7 = False
break
else:
print ("Please say yes or no")
#Asks the user for the Amount of Days they would like to hire the car for
correct_name8 = False
while correct_name8 == False:
try:
amountOfDays = int(input("Please enter the amount of days you would like to hire for\n"))
if amountOfDays <1 or amountOfDays > 100:
print ("Please enter a sensible number!")
continue
except ValueError:
print ("Invalid Format")
continue
else:
print ("The amount of days you would like to hire the vehicle is", amountOfDays, "days")
while True:
correct8 = input("Is this correct?\n")
if correct8.lower() == "yes":
correct_name8 = True
break
if correct8.lower() == "no":
correct_name8 = False
break
else:
print ("Please say yes or no")
#Tells the user what the prices are for each vehicle
print ("""
Estate costs 50 pounds a day
Saloon costs 60 pounds a day
Sports costs 70 pounds a day
There will be an additional 10 pound charge for each day
if the estimated miles is above 100 miles
""")
#Asks the user what vehicle they want
correct_name9 = False
while correct_name9 == False:
car = input("Would you like an Estate, Saloon or Sports?\n")
if car.lower() in ["estate", "saloon", "sports"]:
print("The car you have chosen is", car.title())
else:
print ("Invalid car, please try again")
continue
while True:
correct9 = input("Is this correct?\n")
if correct9.lower() == "yes":
correct_name9 = True
break
if correct9.lower() == "no":
correct_name9 = False
break
else:
print ("Please say yes or no")
#Asks the user how many miles they think they will do in a day
correct_name10 = False
while correct_name10 == False:
try:
estMiles = int(input("How many miles do you think you will do in a day?\n"))
if estMiles < 1 or estMiles > 1500:
print ("Please enter a sensible number!")
continue
except ValueError:
print ("Invalid Format")
continue
else:
print ("The amount of miles you think you will do in a day is", estMiles)
while True:
correct10 = input("Is this correct?\n")
if correct10.lower() == "yes":
correct_name10 = True
break
if correct10.lower() == "no":
correct_name10 = False
break
else:
print ("Please say yes or no")
#Calculations for each vehicle
if car == "estate":
calculation = 50 * amountOfDays
elif car == "saloon":
calculation = 60 * amountOfDays
elif car == "sports":
calculation = 70 * amountOfDays
if estMiles > 100:
calculation = calculation + (10*amountOfDays)
print ("It will cost you", calculation, "pounds.")
#Lets the user decide if they want to input another vehicle or exit
while True:
answer = input("Type restart to start over, type exit to exit program\n")
if answer.lower() == 'restart':
print ("Restarting...")
time.sleep(1)
restart_program()
elif answer.lower() == 'exit':
print ("Exiting...")
time.sleep(1)
sys.exit
break
else:
print ("Invalid Format, Please try again")
continue
In Pseudo code? I'd try and read up a bit on Python, its really not hard to understand what is going on. Basically:
import imports various python modules needed in this code.
def restart_program(): defines a function which you can run later in the code with restart_program()
While True: means do something forever, or until break
.lower() is the lowercase version of the string
If you're using this code as a basis, it is not particularly pythonic, it uses a style like an old linear basic program, with an overuse of While True loops. There is definitely much shorter and more readable ways of writing the same program.

Categories

Resources