Is there anyway way to shorten this? - python

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

Related

Why is my While loop not breaking? I used != to a string and when it changes it does not break the loop

I'm using a while loop "while continuation_variable != "X":" but under certain circumstances I later define continuation_variable = "X". Why would this not break the loop?
This is an example of the code:
continuation_variable = "Y"
personal_information_disclaimer = input("Do you understand that you will have to provide personal\n\
information to complete this assessment (Y/N)? ")
personal_information_disclaimer = personal_information_disclaimer.upper()
print()
ynx_list = ["X","Y","N"]
ynx_all = [item for item in ynx_list]
while continuation_variable != "X":
while personal_information_disclaimer not in ynx_all:
print("Sorry, the answer you provided is a non-valid input.")
personal_information_disclaimer = input("Please input if you understand that going forward you will have\n\
to provide personal information (Y/N):")
personal_information_disclaimer = personal_information_disclaimer.upper()
if personal_information_disclaimer == "Y" or personal_information_disclaimer == "N":
if personal_information_disclaimer == "Y":
print("Awesome!")
use_of_personal_info = input("Do you agree to the use of your personal information for the assessment (Y/N)? ")
use_of_personal_info = use_of_personal_info.upper()
while use_of_personal_info not in ynx_all:
print("Sorry, the answer you provided is a non-valid input.")
use_of_personal_info = input("Do you agree to the use of your personal information for the assessment (Y/N)? ")
use_of_personal_info = use_of_personal_info.upper()
if use_of_personal_info == "Y":
print("Thank you! Time to move on to the important questions!")
else:
print("Sorry to hear that. Hope you have a great day!")
continuation_variable = "X"
else:
print("Sorry to hear that. The information needed would allow for the\n\
propper use of the app.")
print("Please return if you change your mind. Have a great day!")
continuation_variable = "X"
else:
print("Thanks for participating!")
continuation_variable = "X"

How to break a function to a specific spot after a failed test

def joe():
while True:
name = ""
answer = ""
print("What is your name? ")
name = input()
if name != "Joe":
continue
print("What is your password? (it is a fish) ")
answer = input()
if answer == "swordfish":
break
print("nice job, Joe")
joe()
If I pass the frist statement and type in "Joe" i continue with the function, and all is good. but if I fail the second test, I break the function and get retrieved back to the "what is your name?" part of the function. How can I write a test that will upon failiure retreive me back to the "what is your password"? instead of the name test?
or try this:
def joe():
name = ""
answer = ""
print("What is your name? ")
name = input()
if name == "Joe":
print("What is your password? (it is a fish) ")
answer = input()
if answer == "swordfish":
return print("nice job, Joe")
joe()
joe()
Try using the combination of a while True and `return statement my bro!
def joe():
while True:
print("What is your name? ")
name = input()
if name != "Joe":
continue
while True:
print("What is your password? (it is a fish) ")
answer = input()
if answer == "swordfish":
print("nice job, Joe")
return
joe()
Add another while loop for the password part.
def joe():
while True:
print("What is your name? ")
name = input()
if name == "Joe":
break
while True:
print("What is your password? (it is a fish) ")
answer = input()
if answer == "swordfish":
break
print("nice job, Joe")

Create Loop in if / else statement

I am trying to loop this function in the case the 'else' is reached but I'm having difficulties.
I tried while False and it doesn't do the print statements, I guess it kicks out of the function as soon as it ends up being false. I tried the True and I think that's the way to go but when it hits Else it just repeats. I'm thinking... maybe I need to do another Elif for the repeat of the whole function and the else as just an escape if needed.
def login(answer):
while False:
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")
while False:
should be
while True:
otherwise you never enter the loop
Further:
else:
print("I don't understand your selection")
should be:
else:
print("I don't understand your selection")
answer = input("enter a new choice")
You might even refactor your code to call the function without parameter:
def login():
while True:
answer = input("enter a choice (a for login or b for account creation")
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")

Name 'y' is not defined, python code to find even or odd numbers

I am writing a simple code to find even or odd numbers, the code was working just fine but maybe I did something wrong and it started giving me this error.
File "d:\Python\EvenOddFinder.py", line 12, in restart
restartornot = input()
File "", line 1, in
NameError: name 'y' is not defined
#Even or Odd Number Finder.
def start():
userInput = input("Please input your number:")
userInput = int(userInput)
if userInput %2 == 0:
print("The number " + str(userInput) + " is Even.")
else:
print("The number " + str(userInput) + " is Odd.")
def restart():
print("Do you want to restart?")
print("Y/N")
restartornot = input()
if restartornot == "Y":
start()
elif restartornot == "y":
start()
elif restartornot == "N":
exit()
elif restartornot == "n":
exit()
else:
print("Invalid Input.")
restart()
restart()
start()
Please help me I am quite new to Python.
Assuming you are using Python 2 you should try using
restartornot = raw_input()

How to detect own files name

I have some code, which I will rather not share but this a portion
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + "maze_game.exe"
exit()
else:
exit()
I want the file to open itself (to start at the beginning) I have tested it and it DOES work but, if the user renames the file (unlikely but possable) clearly this wont work unless they decompile, edit, and recompile. so I want to get the name of itself, store that in a variabe and open like this:
file_name = how ever I get the name
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + file_name
exit()
else:
exit()
so how might I get the file name?
EDIT: here is my whole code:
import os
import time
clear = lambda: os.system('cls')
name = input ("What is your name? ")
friend = "Charels"
if name == "Charels" or name == "charels" or name == "Charles" or name == "charles":
friend = "Chuck"
print ("Welcome to the Maze Game Dr. " + name)
time.sleep(1.5)
clear()
print ("No one has made it out of Colwoods' labrynth,\nhowever there are rumours of untold riches at the end. \nThe most recent victim of the Maze is your best friend, " + friend)
time.sleep(1.5)
clear()
print ("Are you sure you want to continue?")
answer = input ("Y or N? ")
if answer == "Y" or answer == "y":
("")
else:
friend = friend + " for dead. R.I.P."
print ("Shame on you, you left " + friend)
time.sleep(1.5)
clear()
print ("YOU LOSE")
time.sleep(1.5)
clear()
file_name = how ever I get the name
try_again = input ("Try again?")
if answer == "Y" or answer == "y":
clear()
file_path = os.path.dirname(os.path.realpath(__file__))
open file_path + file_name
exit()
else:
exit()
input ("...")
no, the program is not completed and ignore the last line
Maybe I am misunderstanding what you want, but I think os.path.basename(__file__) will do the trick.
This will give you just the file part of your path, so if you have a filefoo/bar/baz.py and pass that path like os.path.basename('foo/bar/baz.py'), it will return the string 'baz.py'.
So try:
file_name = os.path.basename(__file__)
That being said, your approach seems a little atypical as #Blender points out, and I have never tried to have a program restart itself in this way. I am not sure if this answer will make your program work correctly, but it will give you the name of the file that is running your program, which seems to be what you are looking for.

Categories

Resources