My code isnt continueing after it breaks from a while loop - python-3.x

okay so im new to coding in general and during a practice activity i ran into a problem with using while loops, im trying to simulate a 8-ball that doesnt work unless you ask it a question, so far all im trying to do is to cause the code to re ask the question until it meets the peramiters of a none empty input but everytime now that the input isnt empty it just ends before printing out the 8-balls answer
question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: what is your question? ")
while len(question) == 0:
if len(question) == 0:
print("...")
question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: What is your question?")
continue
elif len(question) < 0:
break
ive been at this all day yesterday and today ive finally got the loop to end in general but now i dont know how to get it to continue to execute the code after my while loop without breaking the current loop i have in place ive tried using an else statement to break the loop and this elif statment to break the loop but now im not quite sure what to do

You can utilize walrus operator (:=) to assign and evaluate a variable and also reduce repeated code. So the while loop will keep continue until the value of the variable is not None or not empty:
while not (question := input("Isaiah's MagicAndTotallyNotSentient 8-Ball: what is your question? ")):
print("...")
# next code

I think it would be more practical if you just check if the input is empty, instead of enter a while loop right away.
Something like this:
question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: what is your
question? ")
if len(question) == 0:
while len(question) == 0:
print("...")
question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: What is your question?")
print("The answer to your question is...etc")
#(rest of the code)

You only need to enter the loop if the input is empty. And going if len(question) == 0: and while len(question) == 0: seems redundant.
I think I'd do it like this:
question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: What is your question?")
while len(question) == 0:
print("...")
question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: What is your question?")
print("The answer is:")

Related

Problem with logic in python script [closed]

This post was returned to Unix & Linux Stack Exchange. It is not currently accepting new answers or interactions. Learn more
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
#!/usr/bin/env python3
# tarchiver.py
# Purpose: Creates a tar archive of a directory
#
# USAGE: ./tarchiver.py
#
# Author:
# Date January 15th 2023
import os
correct_answer = 'yes'
correct_answer2 = 'no'
compression1 = 'gzip'
compression2 = 'bzip2'
compression3 = 'xzip'
print("Please enter the directory you would like to archive")
directory = input()
print("Please enter the name of the archive")
name = input()
print("Would you like your archive to be compressed?")
answer = input()
while correct_answer != answer or correct_answer2 != answer:
answer = input()
print('Please enter either yes or no')
if answer == correct_answer or answer == correct_answer2:
break
if answer == 'yes':
print("What kind of compression do you want?")
print("gzip, bzip2, or xzip?")
answer2 = input()
while compression1 != answer2 or compression2 != answer2 or compression3 != answer2:
print('Please enter a valid answer')
answer2 = input()
if answer2 == compression1 or answer == compression2 or answer == compression3:
break
if answer2 == "gzip":
os.system(f"tar -cvPzf {name} {directory}")
if answer2 == "bzip2":
os.system(f"tar -cvPjf {name} {directory}")
if answer2 == "xzip":
os.system(f"tar -cvPJf {name} {directory}")
I'm having trouble with the logic in the code. When it asks whether or not I would like compression and I type 'yes', I have to type it twice in order for the code to proceed to the next section. Also, when it asks for type and I input 'gzip', it tells me at first that it's an invalid input and that I need to correct my answer, but I just enter the same thing and then it proceeds to execute the rest of the code. This is for a school project and I'm new to python so excuse me if there is an obvious solution to this problem.

Python 3 How to Ask user for specific input and reject invalid inputs

I have a question on how to check a user's input and make sure they are returning a specific string. Currently, the function when called will ask the user for their input. However, if they choose a string that is not part of the function, the else statement will execute and continue the code. I am trying to figure out how to loop this function, until a user inputs one of the strings that the function is looking for. Can anyone help me with this? I am new to python and would appreciate any help.
def dwarf_class_definer(dwarf_class):
if dwarf_class == "Thane":
print("'Ahhh Nobility'")
elif dwarf_class == "Mekanik":
print("'Interesting a Mechanic'")
elif dwarf_class == "Ancestrite":
print("'A spiritualist. I see...'")
elif dwarf_class == "Prisoner":
print("'Never met a gen-u-ine 'Last chancer.'")
elif dwarf_class == "Civilian":
print("'ehhh a civilian? Wut you doing here?'")
else:
print("You aren't choosing a valid class.")
dwarf_class = input("Which Class will you choose?: ")
dwarf_class_definer(dwarf_class)
A while loop will keep going until you tell it not to anymore. You can see when an expected value is supplied, the break command will terminate the while loop. A dictionary can also make your code a lot cleaner and easier to maintain compared to a bunch of if statements.
dwarf_classes = {
"Thane": "'Ahhh Nobility'",
"Mekanik": "'Interesting a Mechanic'",
"Ancestrite": "'A spiritualist. I see...'",
"Prisoner": "'Never met a gen-u-ine 'Last chancer.'",
"Civilian": "'ehhh a civilian? Wut you doing here?'",
}
while True:
dwarf_class = input("Which Class will you choose?: ")
if dwarf_class in dwarf_classes.keys():
print(dwarf_classes[dwarf_class])
break
print("You aren't choosing a valid class.")
example:
$ python3 so.py
Which Class will you choose?: Python!
You aren't choosing a valid class.
Which Class will you choose?: Prisoner
'Never met a gen-u-ine 'Last chancer.'

Is there a way read the random printed?

I am trying to set up a fighting game where it prints a question and you have to answer the question correctly to win the fight. But I a finding that I can't find a way to get the code t read the random question to be read thus meaning I can't get it to read the answer as correct.
I've tried making the random be separated into multiple variables but that didn't work. I haven't had much time to try anything else either.
import random
fights=("I run but never walk, I have a bed but never sleep", "What time
of day is the same fowards as it is backwards?", "3+2")
FIGHTS=random.choice(fights)
print(FIGHTS)
ans1="river"
ans2="noon"
ans3="5"
que1=input("What shall you say?\n")
if ans1=="I run but never walk, I have a bed but never sleep":
print("You won!")
elif ans2=="What time of day is the same fowards as it is backwards?":
print("You won!")
elif ans3=="3+2":
print("You won!")
else:
print("You lost...")
If you answer correctly it displays "You won!" and if you answer wrongly it displays "You lost..." but it can't read what is printed so it always displays "You lost..."
A good approach would be to store the questions and answers in a dictionary and use good variable names.
import random
fights = {"I have a bed but never sleep": "river",
"What time of day is the same fowards as it is backwards?": "noon",
"3+2": "5"}
question = random.choice(tuple(fights.keys()))
print(question )
answer = input("What shall you say?\n")
if answer == fights[question]:
print("correct")
else:
print("wrong")
If you are not going to use this dictionary again, you can use fights.popitem() instead. Keep in mind that if using Python >= 3.7 popitem will always return the same key-value pair:
fights = {"I have a bed but never sleep": "river",
"What time of day is the same fowards as it is backwards?": "noon",
"3+2": "5"}
question, correct_answer = fights.popitem()
print(question)
user_answer = input("What shall you say?\n")
if user_answer == correct_answer:
print("correct")
else:
print("wrong")

text-based adventure help in python 3.x

I am a beginner programmer. I want to create a game where user input affects the course of the game. I am kind of stuck on the very beginning.
def displayIntro():
print("You wake up in your bed and realize today is the day your are going to your friends house.")
print("You realize you can go back to sleep still and make it ontime.")
def wakeUp():
sleepLimit = 0
choice = input("Do you 1: Go back to sleep or 2: Get up ")
for i in range(3):
if choice == '1':
sleepLimit += 1
print("sleep")
print(sleepLimit)
if sleepLimit == 3:
print("Now you are gonna be late, get up!")
print("After your shower you take the direct route to your friends house.")
elif choice == '2':
print("Woke")
whichWay()
else:
print("Invalid")
def whichWay():
print("After your shower, you decide to plan your route.")
print("Do you take 1: The scenic route or 2: The quick route")
choice = input()
if choice == 1:
print("scenic route")
if choice == 2:
print("quick route")
displayIntro()
wakeUp()
i have a few bugs and I've tried to work them out on my own but I'm struggling.
1) I only want the player to be able to go back to sleep 3 times and on the third i want a message to appear and another function to run (havent made yet).
2) if the player decides to wake up i want whichWay() to run and it does but instead of exiting that for loop it goes right back to that loop and asks if the player wants to wake up again i have no idea how to fix this.
3) is there a better way i can go about making a game like this?
Thank you for your time and hopefully your answers.
The code below should work.
1. I moved the line 'choice = input("Do you 1: Go back to sleep or 2: Get up ")' into the for loop.
2. I added a break statement at the end of the elif block.
def wakeUp():
sleepLimit = 0
for i in range(3):
choice = input("Do you 1: Go back to sleep or 2: Get up ")
if choice == '1':
sleepLimit += 1
print("sleep")
print(sleepLimit)
if sleepLimit == 3:
print("Now you are gonna be late, get up!")
print("After your shower you take the direct route to your friends house.")
elif choice == '2':
print("Woke")
whichWay()
break
else:
print("Invalid")

Python 3 - Repeat until correct answer with multiple answers

How can I have a multiple choice question with each answer a different response and a default answer for an answer that is not understandable?
I am trying to create a game where you use your imagination to complete the game.
I also need to somehow repeat until the correct answer is given.
Here is the code:
answer = input("start?")
while answer.lower() != "start":
answer = input("type start")
else:
print("starting")
answer = input("you find yourself in a car")
while answer != "["look", "get out"]:
print("I don't understand..")
answer = input("Try again")
else:
if answer == "look":
print ("looking")
elif answer == "get out":
print("got out of car")
print("finished")

Resources