How to use while loop with nested if statements in Python [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
After getting a bunch of undesired output(s) from my code I realised that I may have no clear understanding of for and while loops. My intention is to "nest" an if block in a while or for loop, where instead of exiting when the user inputs an unxpected answer it simple loops back (not infinitely)until the correct or at least desired input is taken in. Please help and possibly explain. Thank you.
employment_history = str(input("Have you ever been employed? Y/N: " ).title())
if employment_history == "Y":
comp_name = str(input("What was the name of the company you worked for? ").title())
ref_1 = str(input("Who was your reference at "+ comp_name +"? ").title())
ref_1_num = input("What was "+ ref_1 + "'s number? ")
ref_1_number = ref_1_num[0:3]+'-'+ ref_1_num[3:6]+'-'+ ref_1_num[6:10]
print("The company you worked for was "+comp_name+", "+ ref_1 +" was your reference ", "their number was "+ ref_1_number +".")
elif employment_history == "N":
print("No employment record entered.")
while employment_history != "Y" and "N":
print("Please enter Y for 'YES' and N for 'NO'.")
return

You could put the if statements inside the loop so that it reaches them every time it loops
while True:
print("Please enter Y for 'YES' and N for 'NO'.")
employment_history = str(input("Have you ever been employed? Y/N: " ).title())
if employment_history == "Y":
comp_name = str(input("What was the name of the company you worked for? ").title())
ref_1 = str(input("Who was your reference at "+ comp_name +"? ").title())
ref_1_num = input("What was "+ ref_1 + "'s number? ")
ref_1_number = ref_1_num[0:3]+'-'+ ref_1_num[3:6]+'-'+ ref_1_num[6:10]
print("The company you worked for was "+comp_name+", "+ ref_1 +" was your reference ", "their number was "+ ref_1_number +".")
break
elif employment_history == "N":
print("No employment record entered.")
This code is an infinite loop, however, you have the if statement to check if requirements are met. If they are, then it goes through the code, and at the end of the statement it breaks the loop so it does not ask again.

employment_history = None
while employment_history != "N":
employment_history = str(raw_input("Have you ever been employed? Y/N: " ))
if employment_history == "Y":
comp_name = str(raw_input("What was the name of the company you worked for? ").title())
ref_1 = str(raw_input("Who was your reference at "+ comp_name +"? ").title())
ref_1_num = raw_input("What was "+ ref_1 + "'s number? ")
ref_1_number = ref_1_num[0:3]+'-'+ ref_1_num[3:6]+'-'+ ref_1_num[6:10]
print("The company you worked for was "+comp_name+", "+ ref_1 +" was your reference ", "their number was "+ ref_1_number +".")
elif employment_history == "N":
print("No employment record entered.")

Related

If I add OR options to IF, the code doesn't run properly [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed last month.
When I put in line 7 or the code doesn't work as intended.
Can someone please tell me the reason for that?
# x = int(input("Insert price for your product :"))
x=100
print ("Does your product include taxes?")
# answer = input(" yes or no ")
answer = "no"
if answer == "yes" or "Yes" or "YES":
print ("final price is : ", x, "\n the tax is :" ,x*0.17)
elif answer == "no":
print ("final price is : ", x*1.17, "\n the taxes is ", x*0.17)
else:
print ("Your answer is not according to the dictionnary - try again")
I expect that any input for the word YES will work for the if in the code.
Try:
if answer in ["yes","Yes","YES"]:
OR
if answer == "yes" or answer=="Yes" or answer=="YES":
Instead of.
if answer == "yes" or "Yes" or "YES":
instead of using if answer == "yes" or "Yes" or "YES":. you should try
if answer == "yes" or answer == "Yes" or answer == "YES":.
OR use python built-in method called lower(), so that you can lowercase your input
x = int(input("Insert price for your product :"))
print ("Does your product include taxes?")
answer = input(" yes or no ").lower()
if answer == "yes":
print ("finel price is : ", x, "\nthe tax is :" ,x*0.17)
elif answer == "no":
print ("finel price is : ", x*1.17, "\nthe taxes is ", x*0.17)
else:
print ("Your answer is not according to the dictionary - try agin")
It's an issue with syntax.
if answer == "yes" or "Yes" or "YES":
In this context in Python you need to spell out each time what variable you are using, for example:
if answer == "yes" or answer== "Yes" or answer== "YES":
or you can format it a different way such as:
answer = answer.lower()
if answer == "yes":
print ("final price is : ", x, "\nthe tax is : " , x*0.17)
elif answer == "no":
print ("final price is : ", x*1.17, "\nthe tax is : ", x*0.17)
else:
print ("Your answer is not according to the dictionary - try again")
this solution will change answer to be all lowercase which allows people to also write things such as YeS or yeS. This also keeps the code from looking cluttered.

If statement not working as intended (Python)

This code I wrote for my study on if statements in Python doesn't seem to work properly since it asks the same question twice after the first one being asked.
Identity = input("Who are you? ")
if Identity == "Jane":
print("You must be John's sister.")
elif Identity != "John":
print("My database doesn't recognise you. Who are you I wonder...")
elif Identity == "John":
if input("What is your last name? ") != "Travolta":
print("False! John's name is Travolta and not " + input("What is your last name? ") + ".")
elif input("How old are you? ") == "Travolta":
if input("How old are you? ") != "20 yo":
print("False! John is 20 yo and not " + input("How old are you? ") + ".")
elif input("How old are you? ") == "20 yo":
print("You must in fact be John!")
if input("What is your last name? ") != "Travolta":
print("False! John's name is Travolta and not " + input("What is your last name? ") + ".")
Here you aren't storing the value of the input and printing it. You are asking the person to input again "what is your last name?".
Do something like
last_name = input("What is your last name? ")
and use it instead of the input() in the if statement.
Here I am putting the snippet in the way I would've done it.
identity = input("Who are you? ")
if identity == "Jane":
print("You must be John's sister.")
elif identity != "John":
print("My database doesn't recognise you. Who are you I wonder...")
elif identity == "John":
last_name = input("What is your last name? ")
if last_name != "Travolta":
print("False! John's last name is Travolta and not " + last_name + ".")
else:
age = input("How old are you? ")
if age != "20 yo":
print("False! John is 20 yo and not " + age + ".")
else:
print("You must in fact be John!")
It is working properly for every possibility. Examples:

I'm trying to make a quiz on Python but my code keeps repeating

So, I'm trying to make a basic quiz in Python and when I get to a certain point when I'm testing the program my code will repeat for reasons I can't seem to work out...
My code:
`if choice == "2": #If the user enters 2 they will be taken here.
print (" ") #Makes a break between lines.
username=input ("Please enter your username:")
print (" ") #Makes a break between lines.
password=input ("Please enter your password:")
file=open ("userinformation.txt","r")
for line in file:
if username and password in line:
print (" ") #Makes a break between lines.
print ("Thank you for logging in " + username+".")
time.sleep (3)
#file.close()
print (" ") #Makes a break between lines.
print ("Please choose a topic and a difficulty for your quiz.")
time.sleep (4)
print (" ") #Makes a break between lines.
print("a.History - Easy.")
print (" ") #Makes a break between lines.
print("b.History - Medium.")
print (" ") #Makes a break between lines.
print("c.History - Hard.")
print (" ") #Makes a break between lines.
print("d.Music - Easy.")
print (" ") #Makes a break between lines.
print("e.Music - Medium.")
print (" ") #Makes a break between lines.
print("f.Music - Hard.")
print (" ") #Makes a break between lines.
print("g.Computer Science - Easy.")
print (" ") #Makes a break between lines.
print("h.Computer Science - Medium.")
print (" ") #Makes a break between lines.
print("i.Computer Science - Hard.")
print (" ") #Makes a break between lines.
topic = input("To choose a topic please enter the corrosponding letter:")
if topic == "a":
print (" ") #Makes a break between lines.
time.sleep(2)
print ("You have selected option a, History - Easy.") #Tells the user what subject they picked (Same result but with a different topic and difficulty displayed for each one
print (" ")
print ("Rules: You have an unlimited amount of time to anwser each question. You will be anwsering 2 questions and each question anwsered correctly")
print ("will reward you with 10 points.")
time.sleep(9)
print (" ")
print ("The maximum amount of points you can get is 20.")
time.sleep(3)
print (" ")
print ("Good luck!")
print (" ")
time.sleep(2)
print ("Question 1 -")
print ("When did World War 1 begin and end?")
print ("a. 1913 - 1917") #Incorrect anwser
print (" ")
print ("b. 1914 - 1919") #Incorrect anwser
print (" ")
print ("c. 1914 - 1918") #Correct anwser
anwserq1he = input ("Please pick an anwser:")
if anwserq1he == "b":
print(" ")
print("Sorry, that's the wrong anwser...")
time.sleep(3)
print(" ")
hisready = input ("Type ok when you are ready to proceed to the next question.")
elif anwserq1he == "a":
print(" ")
print("Sorry, that's the wrong anwser...")
time.sleep(3)
print(" ")
hisready = input ("Type ok when you are ready to proceed to the next question.")
elif anwserq1he == "c":
print(" ")
print ("That's the right anwser!")
print(" ")
time.sleep(2)
print ("Adding 10 points to your score...")
score = score +10
print(" ")
time.sleep(3)
hisready = input ("Type ok when you are ready to proceed to the next question.")
if hisready == "ok":
print(" ")
time.sleep(2)
print ("Question 2-")
print ("Which historical figure is commonly known as 'The lady with the lamp'?")
print ("a. Margaret Fuller")
print (" ")
print ("b. Florence Nightingale")
print (" ")
print ("c. Rosa Luxemburg")
anwserq2he = input ("Please pick an anwser:")
if anwserq2he == "a":
print ("Sorry, that's the wrong anwser...")
results = input("Please type results to get your results")
elif anwserq2he == "c":
print ("Sorry, that's the wrong anwser...")
results = input("Please type results to get your results")
elif anwserq2he == "b":
print (" ")
time.sleep(2)
print ("That's the right anwser!")
print(" ")
time.sleep(2)
print ("Adding 10 points to your score...")
score = score + 10
results = input("Please type results to get your results.")
if results == "results":
print(" ")
time.sleep(3)
print ("Getting your results...")
if score == 20:
print ("Congratulations, you scored 20 points. That's the best score you can get!")
elif score == 10:
print ("Well done, you scored 10 points. Almost there!")
elif score == 0:
print ("You scored 0 points. Try again and you might do better!")`
When I complete the quiz everything beyond print ("Thank you for logging in " + username+".")repeats...I'd appreciate it if anyone could help me. Thank you.
Sidenote: The #file.close is intentional.
Alright, so first of all we need to improve the program layout , maybe call in some functions would be useful. Here is some tips to fix the program.
First of all use : if username.strip() and password.strip() in line: [Use the .strip() function so it will match a word.
Your program is inefficient because if you press another value as in 2 it will break the program. You want to loop it and loop it over and over again therefore use the while True statement and create a function.
Add a function called exampleFunction() (I.E) and then on the bottom of the code ad this line but obviously indent it.
while True:
exampleFunction()
You don't need to use a or r just do file=open("your file.txt")
For example,
genre=input("What is the film you would like to search?: ")
f=open("Films.txt")
for line in f:
if genre in line.strip():
print(line)
I would personally fix this myself and post a copy of the code however this is too minor to fix therefore i'm leaving it to you.
Goodluck,
Matin

Is there anyway way to shorten this?

Very beginner programmer here in the process of learning. I am just wondering if this simple code I have typed is the most optimal way to do it.
with open('guest_book.txt', 'a') as file_object:
while True:
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = input("Do you need to add another name?(Y/N)")
if another == "y":
continue
elif another == "n":
break
else:
print("That was not a proper input!")
while True:
another = input("Do you need to add another name?(Y/N)")
if another == "y":
a = "t"
break
if another == "n":
a = "f"
break
if a == "t":
continue
else:
break
My questions is in the if statements. When I ask the input("Do you need to add another name?(y/n)", is what I have typed the best way to re-ask the question if I get an answer other than y or n. Basically I want the question to be repeated if I don't get either a yes or no answer, and the solution I found does not seem like the most optimal solution.
You are basically there. You can simply:
with open('guest_book.txt', 'a') as file_object:
while True:
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = input("Do you need to add another name?(Y/N)")
if another == "y":
continue
elif another == "n":
break
else:
print("That was not a proper input!")
continue
You can use function to write your all logic at one place.
def calculate(file_object):
name=raw_input("What is your name?")
print("Welcome " + name + ", have a nice day!")
file_object.write(name + " has visited! \n")
another = raw_input("Do you need to add another name?(Y/N)")
if another == "y":
calculate(file_object)
elif another == "n":
return
else:
print("That was not a proper input!")
calculate(file_object)
if __name__=='__main__':
with open('guest_book.txt', 'a') as file_object:
calculate(file_object)
You can do it this way, but there will not be any invalid input for saying no. It will only check for saying y
with open('guest_book.txt', 'a') as file_object:
another = 'y'
while another.lower() == 'y':
name=input("What is your name?")
print("Welcome " + name + ", have a nice day!")
another = input("Do you need to add another name?(Y/N)")

local variable referenced before assignment python issue

So I'm coding a small project and I'm struggling with a certain aspect so far.
Here is the code:
import re
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = input(">>>")
print("Please enter your post code")
postCode = input(">>>")
print("Is your house a number, or a name?")
nameOrNumber = input(">>>")
if nameOrNumber == "number" or nameOrNumber == "Number":
print("Please enter your house number")
houseNumber = input(">>>")
elif nameOrNumber == "Name" or nameOrNumber == "name":
print("Please enter your house name")
houseName = input(">>>")
else:
print("Invalid")
house = (houseNumber) + (houseName)
address = (postCode) + ", " + (house)
print("Thank you for your information")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = input(">>>")
if clientDetailsCorrect == "no" or clientDetailsCorrect == "No":
clientDetails()
clientDetails()
Not sure what's going wrong as I haven't actually referenced the variable anywhere else. Someone help.
It would help if you posted the traceback.
That said, this line is the likely source of the problem:
house = (houseNumber) + (houseName)
The way your code is currently written, only one of houseNumber or houseName will be defined. So Python is likely complaining about the missing one.
Given how your code looks so far, it's probably better to just do:
print("Please enter your house name or number")
house = input(">>>")
And remove the house = (houseNumber) + (houseName) line.
Try this:
def clientDetails():
print("Welcome to the InHouse Solutions Room Painting Price Calculator\n")
print("STEP 1 - CLIENT DETAILS")
print("Please enter your full name")
userName = raw_input(">>>")
print("Please enter your post code")
postCode = raw_input(">>>")
print("Please enter your hose number or name")
house = raw_input(">>>")
address = "{}, {}".format(postCode, house)
print("Thank you for your information.\n")
print (userName)
print (address)
print (" ")
print ("Is this information correct? Pleast enter Yes or No")
clientDetailsCorrect = raw_input(">>>")
if clientDetailsCorrect.lower().startswith('n'):
clientDetails()
Using raw_input is better, it will input everything as a string. Also it will allow users to not type quotations to input text (I assume you will run this from CLI). If you later on need to separate houses that are numbers from names Python has very good string methods you can use to do so many wonderful things, I used a couple of them to simplify your code :)
N

Categories

Resources