While loops and input functions are not working in python - python

I've been trying to work on practice modules in the python crash course book. I'm working on while loops and input functions. I tried running the below code in the terminal but only the second line of code prints.
What rental car would you like?
The full code is below:
while True:
car = input("What rental car would you like?")
print(f'Let me see if I can find you a {car.title()}.')
car += input('Subaru')
break
while True:
table = input("How many people are in your party?")
table = int(table)
if table > 8:
print('My apologies, you will have to wait for a table.')
else:
print('Your table is ready!')
break
I tried breaking the loops apart to get the rest to print in the terminal but I'm not sure where I'm messing up. I don't get any errors, it just only prints one line of code out of the entire thing.

It is waiting for your input. After you write something and hit enter it will proceed.

I did not quite understand the first while loop, but for the second one the problem is with the indentation of the break statement

Related

Why does using loop-only functions in a def section not work, even when in a loop?

I am making a small text-based game in Python. It involves many inputs and so to avoid bugs, there are a few things I have to check every time an input exists. Naturally, to speed up the process I wanted to put the code into a def in order to simplify the writing process. When I put the code in the def, it red underlines the continue and break commands (meaning they are incorrect), and if you run the code using the def name, a Traceback occurs. I have tried putting the def section at the beginning of the program, after the while True: (The program is supposed to run infinitely until a certain action is taken that breaks the loop) I have also made sure to try putting it under any variables referenced and in the loop so that no part of it is not defined and so that everything would work if I were to just put the code in there.
Here is the code I am trying to put into a def.
def input_bugs():
if letter_one.lower() == "done" and total_count == 0:
print("You have to play at least one game!")
continue
elif letter_one.lower() == "done":
break
elif len(letter_one) > 1:
print("Sorry, you gotta pick a single letter, no more. Otherwise, type 'done' to end the game and see your stats.")
continue
Here is the Traceback I get every time I try to run it.
line 20
continue
^^^^^^^^
SyntaxError: 'continue' not properly in loop
At this point, I don't even care if I have to write it out every time, I can just copy and paste. I am simply curious as to why it doesn't work so that I know in the future. In case you could not tell, I am pretty new to programming so I want to learn from any mistake I make. Also sorry if I referred to some things in the wrong way. Hopefully, you understood what I meant.

Issue with running input and if/else code in a single code

Please don't hate me if something like this has been asked, I couldn't find a similar problem.
I'm learning python, and I'm trying to get a small piece of code to work in IDLE shell 3.9.7 like this
>>> mark=int(input("enter mark"))
if mark>=90:
print("excellent")
elif mark<90 and mark>=75:
print("good")
elif mark<75 and mark>=40:
print("average")
else:
print("fail")
with the idea that you enter the mark, then it prints one of the statements without having to run the input code then the if/elif/else statements afterwards (I want to have all this code, press enter and then get the desired input/output without running the if/else statements separately.) However, when I run the code, I enter the mark and nothing happens. I've tried different indentation and putting the input bit at the end, but it just asks for the mark and then nothing happens. I'm not sure what I'm doing wrong, as the app that I'm using to learn has it parsed exactly like this. Appreciate any help.
Try this it should work just had to put it in a for loop
while True:
mark=int(input("enter mark: "))
if mark>=90:
print("excellent")
elif mark<90 and mark>=75:
print("good")
elif mark<75 and mark>=40:
print("average")
else:
print("fail")
(I want to have all this code, press enter and then get the desired input/output without running the if/else statements separately
Probably you want a function, like this:
def foo(mark: str) -> None:
if mark>=90:
print("excellent")
elif mark<90 and mark>=75:
print("good")
elif mark<75 and mark>=40:
print("average")
else:
print("fail")
that you can call this way in the shell:
>>> foo(int(input("Enter your mark: ")))
10
fail

How to make a Dungeons and Dragons-esque skill check in Python?

I am trying to make a small text-based adventure game in Python IDLE, but I am running into some issues with having the game give a different response if the player rolls above or below the DC of a DND style preception check. I am very new to this so it's probably an easy fix. Here's the code.
I have no idea how to input the code into the question correctly so here is a picture.
BTW I did import random at the beginning of the code its just too far back to include in the screencap.
Your problem is you are not specifying what numbers the random module to choose from, in the line if random.randint > 10:. To fix this, put the numbers you want it to choose between. For example, if you want it to choose a random number between 1 and 20, your line would become if random.randint(1,20) > 10:.
You will also want to do this for the other line, which reads if random.randint < 10:.
welcome to SO,
Please read the minimal reproducible example guide posted in the comments by D.L. First thing I would do is to post the actual code, because if the link expires, then others viewing this post with a similar issue cannot figure out what was the given example, and how it was solved.
With logistics out of the way, to fix the error you are specifically receiving is to put what is rolled in a variable.
Here are a few things I would change to make your code clear
# Some string that receives yes or no
room_2_input = ("...")
# if condition is yes
if room_2_input == 'yes':
# Put it in a variable
roll = random.randint(1,20)
# You do not have to format a string this way, but I think it makes it easier
print('You rolled {}'.format(roll)
# Put this condition within the first if, because you don't
# need to execute it if they do not choose to roll
# Neither of your original condition has inclusivity, so if 10 is rolled,
# your program will do nothing, because neither condition would be met
if roll >= 10:
'''do stuff'''
# I would only include elif < 10 if you are specifically looking for > 2
# outcomes, but your outcome appears to be binary, either above or below 10
else:
'''do stuff'''
The reason you would not do a random.randint(1,20) > 10: check in your second if statement is because you would be executing a different roll than your first one.

How to streamline while loops for infinite cycle with pyautogui

I've lurked on SO for a little while, but all of the existing posts I've seen haven't been able to help me. I'm currently teaching myself python, so I apologize if this is an easy fix I'm not seeing.
My objective with this piece of code is to cycle through tabs in a browser using pyautogui.hotkey. It takes user input for number of tabs to cycle through, and executes the pyautogui command.
My issue, however, is that I can't manage to create a looping for or while loop.
I've played around with should_restart variables, for i in range(x) etc etc, but I'm just not seeing my fix.
The code below is essentially what I want to streamline together.
My idealized flow is:
Take input -> increase tabcounter by 1 until it equals input -> reset tabcounter-> rinse & repeat.
numberofTabs = input('How many tabs do you have? \n')
tabcounter = 0
while int(tabcounter) < int(numberofTabs):
tabcounter = tabcounter+1
pyautogui.hotkey('alt', str(tabcounter))
break
while int(tabcounter) == int(numberofTabs):
tabcounter = 0
I want this code to loop until I interrupt it, or for a lengthy period of time.
Thank you in advance. I appreciate the help!
EDIT: After reworking it, and wrapping my code in a loop, I came up with this:
loopcount = input('How many times do you want this to loop?')
time.sleep(5)
count = 0
for i in range(int(loopcount)):
while count < int(numberofTabs):
count += 1
pyautogui.hotkey('alt', str(count))
time.sleep(1)
else:
count = 0```

Exiting a python application for 'GAME OVER'

I would like to know why this code does not work; it should exit at the "GAME OVER" point, but it continues to my next defined function.
I have tried other variations on exit() such as: sys.exit(), quit() and SystemExit.
run_attack = input("What do you do: Run/Attack\n")
run = ['run', 'Run', 'RUN']
attack = ['attack', 'Attack', 'ATTACK']
run_attack = 1
while run_attack < 10:
if run_attack == ("run") or ("Run") or ("RUN"):
print ("You turn to run from the wolf but he quickly pounces
you...")
time.sleep(2)
print("You are quickly ripped apart and just about get to see
yourself be eaten.")
print("GAME OVER")
break
exit() #This is where the game should exit, yet after input it
continues to the next function
elif run_attack == ("attack") or ("Attack") or ("ATTACK"):
print("You brace yourself for a bite and have no time to reach"
"for any kind of weapon form your backpack.")
time.sleep("2")
input("You clock the dog hard, twice on the muzzle.")
print("The dog recoils in pain and retreats back to the woods.")
print("You quickly start running as you assume there will be a den in the woods.")
break
else:
input("Type Run or Attack...")
You have several problems in your code; why did you write this much without testing it?
First, you read the user's input, immediately replace is with 1, and then try to test it (incorrectly) as if it were still a string. Your posted code has several syntax errors, so I have some trouble reproducing the problem. However, the immediately obvious problem is here:
break
exit() # This is where ...
You can't get to the exit statement, as you break from the loop just before you can get there.
I strongly recommend that you back up to a few lines and use incremental programming: write a few lines at a time, debug those, and don't continue until they do what you want.
Also look up how to test a variable against various values. Your if statement is incorrect. Instead, try the list inclusion you're trying to set up:
if run_attack in run:
...
elif run_attack in attack:
...
I took the liberty of rewriting your whole program to show you a few things wrong with it and a few tricks. I've done it without the loop, since you never use it anyway... you can add the while loop later once you've mastered it, but you should really go back to basics on some things here:
run_attack = input("What do you do: Run/Attack\n")
if run_attack.lower() == "run":
print("""some
stuff
with
multiple
lines and GAME OVER""")
exit()
elif run_attack in ("attack", "Attack", "ATTACK"):
print("""some
stuff
with
multiple
lines""")
else:
input("Type Run or Attack...")
Some notes:
Using """ for strings enables you to write multiple lines without multiple print statements
Using str.lower() on strings makes everything easy to compare because you only have to compare it to the lowercase version of each string. However for attack you can notice I used a different inclusion test, without multiple conditions. Either way works here.
Like the other answer here (and many comments), you should use only exit() to leave the program entirely, or only break to exit the loop and continue to other code that's beneath the entire loop.
When you rewrite your loop, with a condition like while number_of_turns < 10 don't forget to add 1 to the number of turns on each loop, otherwise that condition is always True and you'll have an infinite loop...
I'm actually quite surprised this code had any resemblance to the behavior you expected from it, my suggestion is to go back over to the basics of python, learn loops, string methods, basic commands. The rest is already said in the other answer here (which is better than mine, frankly) just wanted to add some ideas.

Categories

Resources