Python code [Code loops] - python-3.x

Hello am very new to python and ive atempted my first code like this but something seems to be wrong and one of the steps keeps looping. I am very confused on what to do so could someone please help me out.
Thank you!
import os
import time
def main():
while True:
print("Welcome To Amazon")
search = input("Search.... ")
if 'search == registration':
reg()
if 'search == login':
login()
#Must Register to continue
def reg():
while True:
print("Display Name")
reg_user = input()
print("Password")
reg_pass = input()
def registered():
time.sleep(1)
print("Registration Successful!")
main()
#Must Login to continue
def login():
while True:
print("Enter Username: ")
username = input()
print("Enter Password: ")
password = input()
if 'username == reg_user' and 'password == reg_pass':
time.sleep(1)
print("Login Successful!")
logged()
else:
print("Try Again!")
def logged():
time.sleep(1)
print("Welcome To CityRP Gaming")
main()

The while loop loops for as long as the condition is true. You used While True, and True will always be True. This means the loop will continue forever. To break out of a loop you can use 'break'.

Related

Second loop, game not working and Sublime Text problems

I am working on a very simple 'game' where the player gets 5 guesses to guess a random number.
It's not done yet but I have run into a couple of problems.
This is the code that generates a random number and allows the player to guess
Relevant code:
def GuessLoopFunc(guess):
import random
import sys
import time
sum_guesses = 0
rand_num = random.randrange(1, 21)
print(rand_num)
#This is just for test purposes to know the correct number and see what happens when I guess the correct number
while True:
if guess == rand_num:
print("You got it right!")
else:
sum_guesses += 1
if sum_guesses == 4:
guess = input("That's incorrect...final guess: ")
continue
elif sum_guesses == 5:
print("Oh no! You lost!")
while True:
replay = input("Do you want to play again: ")
if replay == "yes" or replay == "Yes":
pass #Temporary while I figure out how to loop back to very start (new random number)
elif replay == "no" or replay == "No":
print("Goodbye")
break
else:
print("I do not understand what you mean...")
continue
else:
guess = input("You got it wrong, guess again: ")
continue
As you can see by the comments I made, I want the game the return to the very start of the program if the player indicates they want to play again (so they get a new random number.
Also, for some reason, the game doesn't register when the correct answer was given and keeps on telling the player that his answer was incorrect...this is the code of the game where the above module is called:
import sys
import random
import time
from GuessLoop import GuessLoopFunc
print("Hello! Welcome to the guess the number game!")
name_player = input("Please enter your name: ")
print("Hello " + str(name_player) + "!")
play = input("Are you ready to play? ")
if play == "Yes" or play == "yes":
print("Great! Let's get started...")
elif play == "No" or play == "no":
print("Too bad...")
sys.exit()
else:
print("I do not understand your response...")
quit1 = input("Do you want to quit? ")
if quit1 == "yes" or quit1 == "Yes":
sys.exit()
elif quit1 == "no" or quit1 == "No":
print("Great! Let's get started!")
else:
print("I do not understand your response...quitting.")
sys.exit()
print("I am going to think of think of a number between 1 and 20...")
print("You will get 5 guesses to guess the number...")
time.sleep(1)
print("Okay, I have a number in mind")
guess = input("What is your guess? ")
GuessLoopFunc(guess)
time.sleep(1)
sys.exit()
Finally, when I try to run the program in Sublime Text it doesn't run further than the "Please enter your name: " part. If I fill in my name and press enter, nothing happens...but no error message displays either. So I have resorted to testing the program in the Python IDLE every time, but it's a bit tedious...anyone know what's up.
Your main problem is that you compare your userinput (a string) with a random number (integer) - they will never be the same as string != int.
Solution:
You need to convert the user input to a number via the int(text) function.
def getInt(text):
while True:
try:
n = input(text)
return int(n)
except ValueError: # if the input is not a number try again
print(f"{n} is not a number! Input a number")
....
guess = getInt("What is your guess?") # now that is an int
....
You have lots of duplicate "yes/no" codeparts that you can streamline:
def YesNo(text):
'''Ask 'test', returns True if 'yes' was answerd else False'''
while True:
answer = input(text).strip().lower()
if answer not in {"yes","no"}:
print("Please answer 'yes' or 'no'")
continue # loop until yes or no was answered
return answer == "yes"
This reduces
quit1 = input("Do you want to quit? ")
if quit1 == "yes" or quit1 == "Yes":
sys.exit()
elif quit1 == "no" or quit1 == "No":
print("Great! Let's get started!")
to
if YesNo("Do you want to quit? "):
sys.exit()
else:
pass # do somthing
and use that in all yes/no questions.
To play again I would move the "Do you want to play again" question out of the game loop:
# do your name questioning and greeting here
# and then enter an endless loop that you break from if not playing again
while True:
GuessLoopFunc() # move the guess input inside the GuessLoopFunk as it has
# to be done 5 times anyhow. If you spend 5 guesses or
# guessed correctly, print some message and return to here
if YesNo("Play again? "):
continue
else:
break # or sys.exit()
To fix the sublime problem: Issue with Sublime Text 3's build system - can't get input from running program

Try / Except, back to try

I have this code
def ID():
ID = input("Enter ID: ")
try:
int(ID)
print("Good ID")
except ValueError:
print("Not a string")
ID()
how can I do to try again to input the ID without restarting the code?
You could use a while loop. There are several ways. Here is one:
def ID():
goodID = False
while not goodID:
ID = input("Enter ID: ")
try:
int(ID)
print("Good ID")
goodID = True
except ValueError:
print("Not a string") # do you mean int??
ID()
I would suggest to read also this.

Python3 with Loop function / password exit?

I'm new to Python and need a little help. I came across this code on here which I kind of understand and want to expand on it... but I don't know how to get out of the loop!
When you run the code and enter the specified username and password, it runs the defined function logged()... but then loops back to asking for the username again because it run the main() function again!... how can I get past this. When the correct username & password is entered, I would like to be at a point where I can add new code! Does this make sense?
import os
import time
#Must Access this to continue.
def main():
while True:
UserName = input ("Enter Username: ")
PassWord = input ("Enter Password: ")
if UserName == 'Bob' and PassWord == 'rainbow123':
time.sleep(1)
print ("Login successful!")
logged()
else:
print ("Password did not match!")
def logged():
time.sleep(1)
print ("Welcome to ----")
main()
When all matches, break out of loop and call logged outside the loop. Or else once the logged is over, you return back to the infinite loop again.
def main():
while True:
UserName = input ("Enter Username: ")
PassWord = input ("Enter Password: ")
if UserName == 'Bob' and PassWord == 'rainbow123':
time.sleep(1)
print ("Login successful!")
break
else:
print ("Password did not match!")
logged()

Why doesnt the password work when I enter it?

import sys
import string
import time
password = "1234"
guess = " "
count = 0
def bank():
print("TKS Bank")
print("Enter your pin below to access your TKS Bank account")
print()
def password():
global password
global guess
global count
while count != 3 and guess != password:
guess = input("Please enter your 4 digit pin: ")
count += 1
if guess == password:
menu()
elif count == 3:
print("Number of tries maxed.")
countdown()
count = 0
else:
print("Your pin is denied, Try again")
def menu():
print("Your pin has been approved")
print("_" * 80)
print("Welcome to the TKS Bank")
print("_" * 80)
print("1. Type 1 to check your account balance")
print("2. Type 2 to to deposit a chosen amount")
print("3. Type 3 to withdraw a chosen amount")
print("4. Type 4 to check your simple interest")
print("5. Type 5 to exit the menu")
print("_" * 80)
def balance():
balance = (random.randint(1,1000))
print("$", balance)
#'sys' imports the system library from the python library
def quit():
os.exit(0)
def countdown():
print("You have been locked out for 3 minutes. Please come back later
and try again")
time.sleep(3)
bank()
password()
When I have the countdown function the password does not work and just continually loops. Does anyone have a fix?
To expand with the countdown function when I input the correct password it says that it is incorrect and goes to the countdown after three tries. I really don't know what the solution is so anyone help would be appreciated.
Inside your def password(): function, there's an ambiguous name usage between password the variable and password the function.

Issue With Function Continuation in Python

I know this is probably a very simple fix, but I cannot seem to make the code work. Here is the problematic excerpt:
def main_menu():
print("Welcome! Please Choose An Option to Proceed")
print("1. New: Input Letters Into A New Excel Document")
print("2. Add: Add New Letters To An Existing Excel Document")
while True:
choice = input("Enter Option Number: ")
if choice.lower() in ['1','2']:
return choice.lower()
else:
print("Invalid Number Choice")
continue
def menu_choice(main_menu):
while True:
choice = main_menu()
if choice == "1":
newsession()
elif choice == "2":
addsession()
else:
break
def newsession():
while True:
try:
txtfilenameinput = input("1. Enter 'Txt' Input File Name: ")
inputfilename = txtfilenameinput.replace(".txt" , "")
inputfile = codecs.open(inputfilename + ".txt" , "r" , encoding = "utf-8" , errors = "ignore")
print("File Found" + "\n")
break
except FileNotFoundError:
print("File Not Found: Make Sure The File Is Spelled Correctly And That Both The Program and File Is On The Desktop Screen" + "\n")
if __name__ == '__main__':
main_menu()
closeprogram = input("Press Enter Key To Close Program")
My objective is, for example, when an input of "1" is inserted in main_menu(), the script would then start to run the newsession() function. Yet for some reason, the program does nothing but jumps to the end of the script (a "press key to close program" command) without engaging the newsession() function. This holds true for an input of "2" for the addsession() function as well. What am I doing wrong? I have tried everything but nothing allows my input choice of 1 or 2 to continue the progress in my script. Thank you for your help!
Try the code below. It allows to exit from the program and it returns again and again for more user input:
def main_menu():
print("Welcome! Please Choose An Option to Proceed")
print("1. New: Input Letters Into A New Excel Document")
print("2. Add: Add New Letters To An Existing Excel Document")
print(" QUIT with 'q'")
while True:
choice = input("Enter Option Number: ")
if choice.lower() in ['1','2','q']:
return choice.lower()
else:
print("Invalid Number Choice")
continue
def menu_choice(main_menu):
while True:
choice = main_menu()
if choice == "1":
newsession()
elif choice == "2":
addsession()
else:
break
The problem with your code was that you were "trapped" in a while True: loop with no escape. So after ONE single user choice newsession() or addsession() were started again and again with no further progress in the script and no way to change anything about it except to kill the program. Remember: each while True loop should have at least one line containing brake or return, else it is a never ending story ...
The problem with not reaching the newsession() is HERE:
if __name__ == '__main__':
main_menu()
where it should be:
if __name__ == '__main__':
menu_choice()

Resources