If statement not working as intended (Python) - 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:

Related

Im trying to make a simple code where you enter your name and age and it will Say is this information correct but idk how to do the correct thingg

print ("Enter your details to create your account ")
Username = input("Enter your username " )
age = input("Enter your Age ")
print("Your username is " + Username)
print("Your age is "+ age)
This is my code, but I'm not sure how to do the "is this information correct" thing.
You were almost there. Something like this should be added to your code and you'll be done.
correct = input("Is this information correct? (y/n)")
And this correct variable will hold a value of "y" or "n" which u can check later in your code if you want.
Just add another prompt at the end like:
data = input("Is this information correct?")
if data.lower() in ['y','ye','yes','yep','yeah']:
# YES
elif data.lower() in ['n','no','nope']:
# No
else:
# Invalid input
One line solution is
verified = True if input("Is this information correct? (y/n)").lower() == 'y' else False
If y or Y entered, verified become True, otherwise False.
EDIT
If you need a loop and get values while not verified by user as you mention in comment, you can use
verified = False
while not verified:
print("Enter your details to create your account ")
username = input("Enter your username: ")
age = input("Enter your Age ")
print("Your username is " + username)
print("Your age is " + age)
verified = True if input("Is this information correct? (y/n)").lower() == 'y' else False

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

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.")

How would I make an infinite loop in Python until a user inputs otherwise?

To clarify, this is similar to another question but I feel the answer is easier to understand.
I am making a very simple program for saying what year you will turn "x" years old. (It's a practice from Practice Python... Starting to relearn Python after a while) I would like the program to ask the user what age they want to know, and it does so. This works fine, but I do not remember how to have it keep asking until they write "n" and otherwise keep asking. Any ideas?
Thanks for the help! Code Below:
I've tried using a Java-esque loop, but this isn't Java, and I don't know what I'm doing. Up to any ideas.
# Libraries
import time
# Initial Code
name = input("What's your name? ")
print("Thank you " + name + "!")
age = int(input("How old are you? "))
year = int(input("Now, just for clarification, what year is it? "))
new_age = input("Now enter what age you would like to know! ")
print("Thank you! Now, I'll tell you the year you will turn " +new_age+ "!")
time.sleep(3)
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
time.sleep(3)
# Loop Code
again = input("Would you like to know another age? Y/n ")
if again == 'Y':
new_age = input("Awesome! What age would you like to know? ")
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
All results work, it just can't loop after the second time.
You can use while instead of if. Whereas if executes its block of code once, while will execute it again and again until the condition becomes false.
# Loop Code
again = 'Y'
while again == 'Y':
new_age = input("Awesome! What age would you like to know? ")
print("Great, that calculation will only take a second or so!")
time.sleep(1.5)
math_year = year - age
answer = int(math_year) + int(new_age)
print(name + ", you will turn " + str(new_age) + " years old in " + str(answer) +"!")
again = input("Would you like to know another age? Y/n ")
As of python 3.8 (so, sometime after late October this year), you'll be able to use the assignment operator := to take care of those first two lines at once:
# Loop Code
while (again := 'Y'):
...
again = input("Would you like to know another age? Y/n ")
hello try something like
while True:
"""
your code
"""
answer = input("again"?)
if answer == 'Y':
continue
elif answer == 'N':
break
else:
# handle other input as you want to
pass

Create a vector given N input of names and ages python

I need to create a program that takes as inputs multiple entries of names and ages. Then I want it to return the names and ages of those entries that have higher age values than the average age of all entries.
For example:
input( "Enter a name: ") Albert
input( "Enter an age: ") 16
input( "Enter a name: ") Robert
input( "Enter an age: ") 18
input( "Enter a name: ") Rose
input( "Enter an age: ") 20
The average is = 18
Rose at 20 is higher than the average.
How can I do this?
answers = {}
# Use a flag to indicate that the questionnaire is active.
questions_active = True
while questions_active:
# Ask for the person's name and response.
name = raw_input("\nEnter a name: ")
response = raw_input("Enter an age: ")
# Store the response in the dictionary:
answers[name] = int(response)
# Check if anyone else is going to take the questionnaire.
repeat = raw_input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
questions_active = False
average_age = sum(answers.values())/float(len(answers))
print("The average is " + str(average_age))
# Questionnaire is complete. Show the results.
for name, response in answers.items():
if response > average_age:
print(name.title() + " at " + str(response) + " is higher than the average.")
This answer is based on a similar example from the book "Python Crash Course: A Hands-On, Project-Based Introduction to Programming" https://www.nostarch.com/pythoncrashcourse

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