Why isn't this code repeating? Python 3.3 - python

This is a code that I have used when repeating a sequence I have used but it doesnt seem to be working can anyone see any problems?The code is for a currency converter. Im using Python 3.3
userDoAgain = input("Would you like to use again? (Yes/No)\n")
if userDoAgain == "Yes":
getChoice()
elif userDoAgain == "No":
print("Thankyou for using this program, Scripted by PixelPuppet")
import time
time.sleep(3)
else:
print("Error: You entered invalid information.")
doagain()
Edit,This is the rest of the code:
if userChoice == "1":
userUSD = float(input("Enter the amount of USD you wish to convert.\n"))
UK = userUSD * 0.62
print("USD", userUSD, "= ", UK, "UK")
elif userChoice == "2":
UK = float(input("Enter the amount of UK Currency you wish to convert.\n"))
userUSD = UK * 1.62
print("UK", UK, "= ", userUSD, "USD")
def doagain():
userDoAgain = raw_input("Would you like to use again? (Yes/No)\n")
if userDoAgain == "Yes":
getChoice()
elif userDoAgain == "No":
print("Thankyou for using this program, Scripted by PixelPuppet")
import time
time.sleep(3)
else:
print("Error: You entered invalid information.")
doagain()

Generally speaking, using recursion to handle a repeated control flow in Python is a bad idea. It's much easier, and less problematic to use loops instead. So, rather than defining a function doagain to ensure you get an answer to your question about running again, I suggest using a while loop. For the larger function that you'll be repeating, I suggest using a loop as well.
def repeat_stuff():
while True: # keep looping until told otherwise
# do the actual stuff you want to do here, e.g. converting currencies
do_stuff_once()
while True: # ask about doing it again until we understand the answer
userDoAgain = input("Would you like to use again? (Yes/No)\n")
if userDoAgain.lower() == "yes":
break # go back to the outer loop
elif userDoAgain.lower() == "no":
print("Thank you for using this program")
return # exit the function
else:
print("Error: You entered invalid information.")
Note that I've changed the checks of the yes/no input strings to be case insenstive, which is a rather more user friendly way to go.

You are using recursion (the function calls itself) while it may be much nicer to just wrap the code you want to repeat in a while loop.
Example of this usage:
userContinue = "yes"
while (userContinue == "yes"):
userInput = input("Type something: ")
print("You typed in", userInput)
userContinue = input("Type in something else? (yes/no): ").lower()

Probably you need to use the function "raw_input" instead of only input.

Related

How do I clear an "if" condition

I'm trying to figure out how to clear an "if" condition and how to fix the result = print(x) part of my code. I'm trying to create a little search code based on the variable data, but I can't figure a few things out:
import time
def start():
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
def other():
name = input("Type the first name: ")
for x in data:
if name in x:
result = print(x)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem is in the result = print(x) part. It works, but when the answer is more than one name, only the first one appear and I don't know how to fix it.
The second problem is in the "confirm = input" part. Basically, if the person answered with "No", when they go back, the answer will still be saved and the input will run twice, the first time with the saved answer and the second with the new answer. So I want to be able to clear that before the person answer it again.
I want to apologize already if the code is ugly or weird, but I started a few days ago, so I'm still learning the basics. Also thanks in advance for the help.
There is quite a bit here to unpack and like the comment on the question suggests you should aim to look at how to ask a more concise question.
I have some suggestions to improve your code:
Split the other into its own function
Try to use more accurate variable names
As much as you can - avoid having multiple for loops happening at the same time
Have a look at list comprehension it would help a lot in this case
Think about whether a variable really belongs in a function or not like data
What you're asking for is not immediately clear but this code should do what you want - and implements the improvements as suggested above
import time
data = ["Lucas_Miguel", "João_Batista", "Rafael_Gomes", "Bruna_Santos", "Lucas_Denilson"]
def other():
name_input = input("Type the first name: ")
matches = [name for name in data if name_input in name]
if len(matches) == 0:
print ("No matches")
for name in matches:
print(name)
while True:
print("Yes " "or " "No")
confirm = input("Is the name you want in the options?: ")
if confirm == "Yes":
break
if confirm == "No":
print("Yes", " or", " No")
try_again = input("Do you want to write again?: ")
if try_again == "Yes":
return other()
else:
return
def start():
print("1" + " - Check Name")
print("2" + " - Register a New Name")
option = input("Choose an option: ")
if option == "1":
other()
else:
print("Option not available")
time.sleep(1)
return start()
start()
The first problem will be solved when you remove 8 spaces before while True:.
The second problem will be solved when you add return (without arguments) one line below return other() at the indentation level of if try_again == "Yes":
Everybody can see that you are just learning Python. You don't have to apologize if you think, your code is "ugly or weird". We all started with such small exercises.

Why will the While Loop not end when I ender the correct input?

I have had an issue where I can't get the While loop to terminate.
userinput = ("")
while userinput != ("Search" or "Add"):
userinput = input("Search or Add?")
if userinput == "Search":
Search()
elif userinput == "Add":
print("run add request")
else: print("please choose from the following two options.")
Edit: I am sorry the changes have worked. I think after I implemented the changes I had an issue with the Shell running the previous version. Sometimes I have no idea what is happening. Thank you all again.
Edit Edit: Placed the original code back in as I did not take into account that it would confuse anyone looking for their own solution. I am quite new in terms of usage of the site. Thanks again for the help
The issue is with your while test. A couple of things:
You can't use or like this. or needs two full conditions that resolve to true or false. Here you have one condition userinput != "Search" and a string "Add". So it's always going to return True since a non-zero value is always True.
As an example:
if "Add": print("true")
>>true
Instead:
userinput != "Search" or userinput != "Add"
or is not correct when testing two negations like !=. One of the two conditions will always return true. For instance if you input "Add" then the condition userinput != "Search" will be True and your while loop will continue since True or False = True. So on and so forth. Instead you want an and.
while userinput != "Search" and userinput != "Add":
As I suggested in my comment though, it's probably just easier to use the not in operator on a list:
while userinput not in ['Search','Add']:
This way as your list grows your test stays nice and small/condense.
Also, while this is just my opinion, I applaud your original pre-edit code where you supplied the condition for breaking your while loop in the while statement instead of doing while True:. Having had many years of bug hunting and feature adding and hotfixing, I know every time I see while True: I'm going to be hunting through hundreds of lines of codes looking for every break. while True: and break has its time and place (I imagine), but I feel like it should be an exception use-case, not the rule.
My solution looks like this:
userinput = ""
while userinput != "Exit":
userinput = input("Search, Add or Exit: ")
if userinput == "Search":
print("run search request")
elif userinput == "Add":
print("run add request")
elif userinput != "Exit":
print("please choose from Search, Add or Exit.")
Notes:
Variable userinput is initialised to "". It doesn't need to be a tuple, ("")
I introduced an 'Exit' option. We loop until we encounter Exit. No need for break or continue
I changed the prompt to a colon and a space, and also show the three options.
We compare the input to the three options. If nothing valid, print an error message
As an alternative, you can use the following, using continue in the else clause, and break at the end of the while block. This way, it is easier to add more elif clauses, without potentially forgetting a break statement.
(It also doesn't require setting a default value for userinput, since that is done as the first thing in the while loop.)
while True:
userinput = input("Search or Add?")
if userinput == "Search":
Search()
elif userinput == "Add":
print("run add request")
else:
print("please choose from the following two options.")
continue
break
Using the word break will break you out of a while loop, like this:
while True:
break
Place break where you want the while loop to end.
The problem is that once the input is received, and when the input meets the end condition of the while loop, and it isn't able to reach the code checking for the condition! Try this:
while True:
userinput = input("Search or Add?")
if userinput == "Search":
Search()
break
elif userinput == "Add":
print("run add request")
break
else: print("please choose from the following two options.")
The format was not correct in the while condition statement part, You can try out this...
userinput = ("")
while userinput not in ["Search", "Add"]:
userinput = input("Search or Add?")
if userinput == "Search":
Search()
elif userinput == "Add":
print("run add request")
else: print("please choose from the following two options.")

Control flow - Jump to another loop?

I did not find any duplicates of this question, i understand that Python has no "goto" functionality in itself and how i can make use of "continue" in a loop to get the same effect, but i'm not really sure if it's any recommended method of "jumping back" to another loop for eg? Let me show you an example below
while True:
print("Hey! Some text.. blablah")
x = input("You wanna continue? (yes/no) ")
if x == "yes":
continue
else:
print("End of loop")
break
while True:
print("Hey! Some more text, blablah even more")
x = input("You wanna continue? (yes/no): ")
if x == "yes":
continue
elif x == "no":
print("End of program")
break
else:
pass
# Here i would want to be able to send the user back to the 1st loop if user gives any other input than "yes" or "no"
The only thing i can think of right now that makes any sense (to not have to simply rewrite the whole thing again) is to simply set the first loop to a function and call that from the second loop to get the result i want, this works as i intend it to:
def firstloop():
while True:
print("Hey! Some text.. blablah")
x = input("You wanna continue? (yes/no) ")
if x == "yes":
continue
else:
print("End of loop")
break
firstloop()
while True:
print("Hey! Some more text, blablah even more")
x = input("You wanna continue? (yes/no): ")
if x == "yes":
continue
elif x == "no":
print("End of program")
break
else:
firstloop()
But somehow it feels like i'm over complicating something, or is this the "best" way i can go by with something like this? Thanks
You should put the second loop inside the first one (or inside an enclosing while for both). GOTOs are never needed, See here: https://en.wikipedia.org/wiki/Structured_programming

invalid syntax for "from import random"

when I try to run this module
from import random
def guessnum():
randomnum = random.randint(1,6)
awnser = input ("what do you think the number is? ")
if awnser==randomnum:
print ("good job. you are correct. ")
else:
print ("incorrect. better luck next time. ")
restart = input ("would you like to try again? ")
if restart = Yes or y:
guessnum()
else:
end()
I get invalid syntax highlighting the import.
what is the issue?
I have already tried import random but it doesn't seem to want to work
Your code is full of errors. I have fixed indentation and other syntax issues.
You don't need to use from, just use import random.
Here is the code
import random
def guessnum():
randomnum = random.randint(1,6)
awnser = input ("what do you think the number is? ")
if awnser==randomnum:
print ("good job. you are correct. ")
else:
print ("incorrect. better luck next time. ")
restart = input ("would you like to try again? ")
if restart == "Yes" or "y":
guessnum()
else:
end()
Fixed your indentation, spelling, capitalization, insertion of unnecessary spaces and comparing between a string and int which would always be false.
Also added str.title to allow for all types of capitalization for restart
import random
import sys
def guessnum():
random_num = random.randint(1,6)
answer = int(input("What do you think the number is? "))
if answer == random_num:
print("Good job. you are correct!")
else:
print("Incorrect. Better luck next time. The number was %d" % random_num)
restart = input("Would you like to try again? ")
if restart.title() in ["Yes", "Y"]:
guessnum()
else:
end()
def end():
print("Goodbye!")
sys.exit(0)
guessnum()

Ending an infinite loop issue (Python)

I am attempting to create a loop which a user can stop at the end of the program. I've tried various solutions, none of which have worked, all I have managed to do is create the loop but I can't seem to end it. I only recently started learning Python and I would be grateful if someone could enlighten me on this issue.
def main():
while True:
NoChild = int(0)
NoAdult = int(0)
NoDays = int(0)
AdultCost = int(0)
ChildCost = int(0)
FinalCost = int(0)
print ("Welcome to Superslides!")
print ("The theme park with the biggest water slide in Europe.")
NoAdult = int(raw_input("How many adults are there?"))
NoChild = int(raw_input("How many children are there?"))
NoDays = int(raw_input("How many days will you be at the theme park?"))
WeekDay = (raw_input("Will you be attending the park on a weekday? (Yes/No)"))
if WeekDay == "Yes":
AdultCost = NoAdult * 5
elif WeekDay == "No":
AdultCost = NoAdult * 10
ChildCost = NoChild * 5
FinalCost = (AdultCost + ChildCost)*NoDays
print ("Order Summary")
print("Number of Adults: ",NoAdult,"Cost: ",AdultCost)
print("Number of Children: ",NoChild,"Cost: ",ChildCost)
print("Your final total is:",FinalCost)
print("Have a nice day at SuperSlides!")
again = raw_input("Would you like to process another customer? (Yes/No)")
if again =="No":
print("Goodbye!")
return
elif again =="Yes":
print("Next Customer.")
else:
print("You should enter either Yes or No.")
if __name__=="__main__":
main()
You can change the return to break and it will exit the while loop
if again =="No":
print("Goodbye!")
break
Instead of this:
while True:
You should use this:
again = True
while again:
...
usrIn = raw_input("Would you like to process another customer? y/n")
if usrIn == 'y':
again = True
else
again = False
I just made it default to False, but you can always just make it ask the user for a new input if they don't enter y or n.
I checked your code with python 3.5 and it worked after I changed the raw_input to input, since input in 3.5 is the raw_input of 2.7. Since you're using print() as a function, you should have an import of the print function from future package in your import section. I can't see no import section in your script.
What exactly doesn't work?
Additionally: It's a good habit to end a command line application by exiting with an exit code instead of breaking and ending. So you would have to
import sys
in the import section of your python script and when checking for ending the program by the user, do a
if again == "No":
print("Good Bye")
sys.exit(0)
This gives you the opportunity in case of an error to exit with a different exit code.
Change this code snippet
if again =="No":
print("Goodbye!")
exit() #this will close the program
elif again =="Yes":
print("Next Customer.")
exit()#this will close the program
else:
print("You should enter either Yes or No.")

Categories