Python Nested If Then statement not seen in while loop - python-3.x

I am developing a menu application (CLI) and when user selects a number choice from the menu then the app does something different for each choice. But first I want to make sure they enter a valid number then do something. If not a valid number, then loop through menu. If number 9 is selected, exit the application. The problem is it doesn't seem to recognize my nested if then condition statements. It just sees the first if then condition and then loops through menu again without "doing something". How do I get it to recognize the nested if thens?
import datetime
import os
import pyfiglet
def main():
Banner()
menu()
def menu():
choice =int('0')
while choice !=int('9'):
print("1. Show the banner again")
print("2. View just a selected date range")
print("3. Select a date range and show highest temperature")
print("4. Select a date range and show lowest temperature")
print("5. Select a data range and show the highest rainfall")
print("6. Make a silly noise")
print("7. See this menu again")
print("9. QUIT the program")
choice = input ("Please make a choice: ")
if choice.isdigit():
print(int(choice))
if choice == 1:
result = pyfiglet.figlet_format("P y t h o n R o c k s", font = "3-d" )
print(result)
elif choice == 2:
getWeather()
choice == 0
elif choice == 3:
print("Do Something 3")
elif choice == 4:
print("Do Something 4")
elif choice == 5:
print("Do Something 5")
elif choice == 6:
os.system( "say burp burp burp burpeeeeee. I love love love this menu application")
elif choice == 7:
print("Do Something 7")
elif choice == 8:
print("Do Something 8")
elif choice == 9:
print("***********************************************************************")
print("Goodbye! Program exiting.....")
print("***********************************************************************")
exit()
else:
print("Your choice is not an integer. Please try again")
print("")
continue
def Banner():
result = pyfiglet.figlet_format("P y t h o n R o c k s", font = "3-d" )
print(result)
def getWeather():
weatherdata1 = print(input("What date would you like to start your weather data query with? Please enter the date in this format YYYYMMDD"))
weatherdata2 = print(input("What date would you like to end your weather data query with? Please enter the date in this format YYYYMMDD"))
print(weatherdata1)
print(weatherdata2)
main()

You have to convert your input to int like so:
choice = int(input ("Please make a choice: "))
or, you need to convert the choice to int when comparing. Like so:
if int(choice) == 1:
result = pyfiglet.figlet_format("P y t h o n R o c k s", font = "3-d" )
print(result)
elif int(choice) == 2:
getWeather()
choice == 0
...

Related

python simple help (NameError: name is not defined)

Whenever I run this is get:
Traceback (most recent call last):
File "main.py", line 130, in <module>
while is_playing_cg:
NameError: name 'is_playing_cg' is not defined
I want the user to be able to press 1 or 2 to select which game mode to use and then once pressed it starts. I don't know why it's doing this. Whenever it's fixed it should run through just fine.
New edit
Now it just loops and says 1 or 2 over and over again.
import random
is_playing_cg = False
is_playing_hg = False
def game_select_screen():
#Game Select Screen
print("""
._________________________________.
| |
| ~ Welcome To Guess-A-Number ~ |
| ~~~ |
| ~ Press 1 OR Press 2 ~ |
| You ^ Guess | PC ^ Guess |
|_________________________________|""")
selecting = True
while selecting:
print()
game_mode = input("1 OR 2: ")
try:
int(game_mode)
except ValueError:
print("This is not a Number.")
else:
game_mode = int(game_mode)
if game_mode == 1:
is_playing_hg = True
elif game_mode == 2:
is_playing_cg = True
#Defining Random Number for human guess
def play_human_guess():
num = random.randint (1,10)
print()
print("Im Thinking of a Number 1 Through 10.")
print("You Have 3 Chances.")
chances = 3
game_fisnished = False
#Game is playing (Human Guesses)
while not game_fisnished:
guess = input("> Take A Guess: ")
#Accept only numbers
try:
int(guess)
except ValueError:
print("This is not a Number.")
else:
guess = int(guess)
if guess < num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too Low. ("+str(chances)+") Chance(s) Remaining.")
elif guess > num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too High. ("+str(chances)+") Chance(s) Remaining.")
else:
print()
print("Congradulations, You Won!")
game_fisnished = True
#Game Ended
def end():
print()
print("Thanks For Playing!")
#Setting up for computer guess
def play_computer_guess():
print()
print("Pick a Number 1 Through 10")
print("I Have 3 Chances to Guess Your Number.")
chances = 3
game_fisnished = False
#Game is playing (Computer Guess)
while not game_fisnished:
guess1 = input("Is your number 5?")
#Show Game Select Screen
game_select_screen()
while is_playing_cg:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while is_playing_hg:
#Start Game
selecting = False
play_human_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_hg = False
end()
The variable is_playing_cg is only available in the "block" that creates it.
Block is function / loop / if statement / etc.
In your program you need to initialize the variable globally so you can call them in multiple functions.
Good luck!
You are defining is_playing_cg inside of a conditional statement at the top of your code. So if that option is not selected, then when you get to the latter conditional statement, it has never heard of that variable.... and it is not defined in the namespace. So you could either define it at the top and give it a default (False) or more better, because you only have 2 options, just use one variable to control the computer / human.
Here is a toy example:
selection = int(input('enter 1 for human, 2 for computer: '))
if selection == 1:
human_play = True
elif selection == 2:
human_play = False
else:
# make some loop that asks for input again or such...
pass
# later on...
if human_play:
# ask human for input...
else:
# have AI make turn
#if needed, you can also handle special cases like this:
if not human_play:
# do something unique to computer turn ...
Additional info...
So you got bit by the scope of the variables in your update. You are defining these variables inside of a function and when you put the defaults outside of the function, they are not in the same scope, so whatever you do inside the function is lost. So, you need to change your function into something that returns the mode you want, and catch that in the function call like such:
def ... :
# input ...
if game_mode == 1:
human_playing = True
selecting = False
elif game_mode == 2:
human_playing = False
selecting = False
return human_playing # this will return T/F back to the function call
And then later:
#Show Game Select Screen
human_playing = game_select_screen()
while not human_playing:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while human_playing:
#Start Game
This (above) works for me, but there are still other logic errors popping up! :) Have fun
This particular error is probably there because you have not defined is_playing_cg as global before using it in your function game_select_screen. Simply put global is_playing_cg at the start of your game_select_screen function to tell python you want to use the global variable instead of creating a scoped variable.

Problem with my small dictionary quiz. can someone explain this error please

d = {'Red': 1, 'Green': 2, 'Blue': 3}
for color_key, value in d.items():
userinput == (input(color_key))
if userinput == (d[color_key]):
print("correct")
else:
print("wrong")
Hi everyone, i am trying to simulate a quiz with this dictionary. I want to iterate through the dictionary and prompt the user for the questions (which is the key) (i.e what is the number for the colour: color_key). I then want the user to put the value for the key that corresponds to the right colour.
I am getting this error:
userinput == input(color_key)
NameError: name 'userinput' is not defined
Can anyone help me please.
Based on assumptions that you want to make kind of "memory" game with colors and integers, code proposal for your game would be something like this:
import random
d = {'Red': 1, 'Green': 2, 'Blue': 3}
while 1==1:
rand1 = random.choice(list(d))
user_input = input("Please guess the code of "+rand1+" color:\n")
try:
int(user_input)
if(int(user_input) == d[rand1]):
print("Color code is correct!")
else:
print("Color code is incorrect!")
except ValueError:
if(user_input.lower() == "quit"):
print("Program will terminate now")
else:
print("Invalid input provided.")
Take in consideration few things important for these kind of exercises:
Despite python is not strictly typizied language, you have to take
care of exceptions in the user input
"While 1==1" generates something
called "dead loop". Make sure you always have exit condition for this
one - In our case out here, that is keyword "quit" on the input.
In case of keyword "quit" on the input, it has to be validated for both
upper and lowercase
EDIT:
According to your newest update, I am providing you the example of simple 3-operations based game:
import random
def detect_string_operation(elem1, elem2, operator):
result = ""
if(operator == "+"):
result = str(elem1 + elem2)
elif(operator == "-"):
result = str(elem1 - elem2)
elif(operator == "*"):
result = str(elem1 * elem2)
elif(operator == "/"):
result = str(elem1/elem2)
return result
operators_list = ["+", "-", "*"]
while 1==1:
elem1 = random.randint(0, 10)
elem2 = random.randint(0, 10)
operator_index = random.randint(0, len(operators_list)-1)
result_operation = detect_string_operation(elem1, elem2, operators_list[operator_index])
user_input = input("Please calculate following: "+str(elem1)+str(operators_list[operator_index])+str(elem2)+"=")
try:
int(user_input)
if(user_input == result_operation):
print("Result is correct!")
else:
print("Result is incorrect!")
except ValueError:
if(user_input.lower() == "quit"):
print("Program will terminate now")
break
else:
print("Invalid input provided.")
Note that I didn't implement division for a reason: for division totally random choice of values is not an option, since we need an integer as a result of division. Algorithm for generating divisor and divider pair is quite simple to be implemented in iterative way, but it is out of scope of your initial question.

How do I clear the screen in Python 3?

Here is my code (for hangman game):
import random, os
def main():
print("******THIS IS HANGMAN******")
print("1. Play Game ")
print("2. Quit Game ")
choice = input("Please enter option 1 or 2")
if choice == "1":
words = ["school", "holiday", "computer", "books"]
word = random.choice(words)
guess = ['_'] * len(word)
guesses = 7
while '_' in guess and guesses > 0:
print(' '.join(guess))
character = input('Enter character: ')
if len(character) > 1:
print('Only enter one character.')
continue
if character not in word:
guesses -= 1
for i, x in enumerate(word):
if x == character:
guess[i] = character
if guesses == 0:
print('You LOST!')
break
else:
print('You have only', guesses, 'chances left to win.')
else:
print('You won')
elif choice == "2":
os.system("cls")
main()
else:
print("that is not a valid option")
main()
I have tried os.system("clear") but it doesn't clear the screen, I want it to clear the entire screen but instead (cls) makes it print my menu again and (clear) does nothing except clear the 2. If I'm missing something obvious it's probably because I'm new to python.
It prints the menu again because you call main() again instead of just stopping there. :-)
elif choice == "2":
os.system("cls")
main() # <--- this is the line that causes issues
Now for the clearing itself, os.system("cls") works on Windows and os.system("clear") works on Linux / OS X as answered here.
Also, your program currently tells the user if their choice is not supported but does not offer a second chance. You could have something like this:
def main():
...
while True:
choice = input("Please enter option 1 or 2")
if choice not in ("1", "2"):
print("that is not a valid option")
else:
break
if choice == "1":
...
elif choice == "2":
...
main()

python3 -- nested while loop driven user input menu decision tree

I have been stumped on this one for too long and I need some help. I am trying to create a user input menu decision tree that will lead the user to the appropriate function call. I just cant seem to get the path to function correctly. I keep getting stuck in the second loop. I have tried many different logics and conditions but nothing has made it work. I created some simple code that I think clearly shows what I am trying to achieve...
def menu():
print("1. Selection 1")
print("2. Selection 2")
print("3. Quit")
def menu1():
print("1.Selection Function 1")
print("2.Selection Function 2")
print("3.Quit")
def menu2():
print("1.Selection Function 3")
print("2.Selection Funtion 4")
print("3.Quit")
def func_1():
print("Funtion_1")
def func_2():
print("Funtion_2")
def func_3():
print("Funtion_3")
def func_4():
print("Funtion_4")
if __name__ == '__main__':
menu()
selection=int
selection1=int
selection2=int
while (selection != 3):
selection==int(input("Please Select a Menu Option: "))
if selection == 1:
menu1()
while ((selection1 != 3)):
selection1==int(input("What Type of funtion Would You Like To execute: "))
if selection1 == 1:
func_1()
if selection1 == 2:
func_2()
if selection1 == 3:
sys.exit()
elif selection == 2:
menu2()
while ((selection2==int(input("What Other Type of Function Would You Like To execute: ")) != 3)):
if selection2 == 1:
func_3()
if selection2 == 2:
func_4()
if selection2 == 3:
sys.exit()
elif selection == 6:
sys.exit()
Looks like you need to break out of the while loop instead of doing sys.exit() in the inner loops. If you do sys.exit() on inner loops it will exit and won't come back to the outer menu option.
your this line selection==int(input("Please Select a Menu Option: ")) should be selection=int(input("Please Select a Menu Option: ")). == is used for comparison not for assignment. for assignment we use =
Here, is modified code which works as expected.
def menu():
print("1. Selection 1")
print("2. Selection 2")
print("3. Quit")
def menu1():
print("1.Selection Function 1")
print("2.Selection Function 2")
print("3.Quit")
def menu2():
print("1.Selection Function 3")
print("2.Selection Funtion 4")
print("3.Quit")
def func_1():
print("Funtion_1")
def func_2():
print("Funtion_2")
def func_3():
print("Funtion_3")
def func_4():
print("Funtion_4")
if __name__ == '__main__':
menu()
selection=int
selection1=int
selection2=int
while (selection != 3):
selection=int(input("Please Select a Menu Option: "))
if selection == 1:
menu1()
while ((selection1 != 3)):
selection1=int(input("What Type of funtion Would You Like To execute: "))
if selection1 == 1:
func_1()
if selection1 == 2:
func_2()
if selection1 == 3:
break
elif selection == 2:
menu2()
while (selection2 != 3):
selection2=int(input("What Other Type of Function Would You Like To execute: "))
if selection2 == 1:
func_3()
if selection2 == 2:
func_4()
if selection2 == 3:
break
elif selection == 6:
sys.exit()
You are comparing selection with integer. Where selection has datatype, it will false forever. Instead do this selection == type(3) and this won't solve your problem.
One more thing is, first line in while loop
selection==int(input("Please Select a Menu Option: "))
here you are comparing(==), not assigning value(=).
selection=int(input("Please Select a Menu Option: "))
use single equals to symbol.
You can't compare the numbers, so you won't get required results, loops will be same for all numbers. For that you need to store numbers in selection variable.
Ask for further queries.

Closing program with while loop

I'm new to Python v3 and am using a while loop at the end of my program to determine if the user wants to restart/retry the program or finish.
If I select yes and I repeat the program more than once and then select no, I keep returning the "Would you like to search again: (Y/N) > " option for the number of times I re-tried the program e.g. 3 attempts and I have to enter n three times before break takes effect.
Code used is below.
while True:
finish_input = input("Would you like to search again: (Y/N) > ")
if finish_input.lower() == ("y"):
my_project()#restarts the program from the start
continue
elif finish_input.lower() == "n":
print()
print("Thank you for using this service.")
break
else:
print()
print("Invalid entry. Please enter Y or N")
I want the option to restart but only have to input n once to close/break the program and exit. Help would be really appreciated.
What you want is:
def my_project():
#Your other code here
my_project()
#The code that you posted
But you are doing:
def my_project():
#Your other code here
#The code that you posted
The difference is that in the last one, you are looping inside the program: each y is another call to the whole function that later and for each one of those you'll have to put n.
The code would look like this:
def my_project():
#Your other code here
my_project()
while True:
finish_input = input("Would you like to search again: (Y/N) > ")
if finish_input.lower() == "y": my_project()
elif finish_input.lower() == "n":
print("\nThank you for using this service.")
break
else: print("\nInvalid entry. Please enter Y or N")
I think its a bad way to implement this. How about doing something like this.
#program starts
run_prog = True
while run_prog:
#Your original code
finish_input = "a"
while True:
finish_input = input("Would you like to search again: (Y/N) > ")
if finish_input.lower() == ("y"):
run_prog = True
break
elif finish_input.lower() == "n":
run_prog = False
print()
print("Thank you for using this service.")
break
else:
print()
print("Invalid entry. Please enter Y or N")

Resources