Python Else won't work with Modules imported? - python

I've been testing stuff with modules specifically time module,
and I tried doing "Else", but I just get a syntax error over the "Else", I've looked over the internet a lot, and on here, and I can't find anything, so I decided to ask Myself, I'm probably going to sound like the stupidest person on earth because of this.
Here's my code,
import time
input ("Hello, would you like to sleep?")
if input == "Yes":
time.sleep(0.5)
print("Sleeping.")
print("Sleeping..")
print("Sleeping...")
print("You have awoken!")
else:
print("Alright.")

Your program should be like,
import time
inputString = input("Hello, would you like to sleep?")
if inputString.lower() == "yes":
time.sleep(0.5)
print("Sleeping.")
print("Sleeping..")
print("Sleeping...")
print("You have awoken!")
else:
print("Alright.")
input is a keyword in python, you can use that to refer something else, but it is highly discouraged. Also, input() returns string in python 3.x and eval(input()) in python 2.x
You know, indentation is very important in Python.

You may need to review your indentation for this. Remember, Python uses whitespace to denote code blocks. It may be that the editor has mangled your code, but it should look like:
import time
inputString = input("Hello, would you like to sleep?")
if input == "Yes":
print("Sleeping.")
print("Sleeping..")
print("Sleeping...")
time.sleep(0.5)
print("You have awoken!")
else:
print("Alright.")
Note that the if and the else are at the same level of indentation, and everything inside of there block is indented one level.

Related

Syntax Error When Making Python Chatbot Using Conditional

Error comes up here in line six:
import time
askingage=input("Are you over the age of 18? ").lower()
if askingage == "yes":
{
time.sleep(2)
print("Wow, you're a fully mature adult!")
Even if it's a very standard\simple code at least I suggest you to explore further way to prevent user inputs errors - such as: define a list of accepted answer (only "yes" seems a bit too restrictive), and prevent the routine goes bananas with a try\catch (my example is just vanilla but you can easily add further checks to prevent the user give undesidered answers).
Also, time.sleep(2) is affecting UX, I suggest to use lower (or zero) pauses for such basic questions. If you'd like to prompt until a right answer is given, explore while loops.
good luck with your implementation and keep struggling! it's the best way to learn
import time
accepted = ["yes", "y", "sure"]
askingage=input("Are you over the age of 18? ").lower()
try:
if askingage in accepted:
time.sleep(0.5)
print("Wow, you're a fully mature adult!")
else:
print("Sorry, you need to be 18 at least to proceed.")
except Exception as e:
print ("Sorry, something went wrong there. Can you Try again?")

Why is this script repeating itself?

I'm trying to teach myself python, I recently learned how to use raw input in an if statement (yes or no). However, when I answer yes, the program asks me the same if question.
Can anyone help? I'm not really good at programming but love doing it.
import time
name = raw_input("what is your name? ")
print "Hello " + name
#yes no statement with raw input
while True:
yesno = raw_input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
exit()
elif yesno.lower().startswith("y"):
print("cool, let me prep for e second")
time.sleep(5)
# this is where it goes wrong
# below is what is supposed to follow
word = "kaasblok"
guesses = ''
turns = 6
while turns > 0:
If you use a while true loop, your program will keep on running.
In Python, the tabs or whitespace tell the interpreter when a loop ends.
So what happens in your code is this:
While True is running,
It asks if you want to play
If you write no it works as intended
If you write yes, it sees that the loop is over so it restarts.
Also your code has several errors, like syntax from both Python 3 and Python 2 and a while loop that doesn't terminate.
I wrote some updates to make the code sort of work but it is not "good" code because I tried to keep it as similar as possible. Also I chose a syntax (python 3) so make sure to change that if you're using Python 2.
I recommend you modularize your code and look at other people's code, it'll make your code better. Avoid using a while True loop, at least at the beginning. The code I wrote sort of tries to address it, but it probably doesn't do such a great job.
Maybe try editing the code a bit and updating with an answer later? I think you meant to write input, not raw_input but it could be that's the way you do it in Python 2. You should really learn Python 3 if you're trying to pick up Python btw as Python 2 is at its end of life cycle.
Place your game in the loop and it'll run. Try something like this:
import time
name = input("what is your name? ")
word = "kaasblok"
turns = 6
print("Hello " + name)
#yes no statement with raw input
trueorfalse = True
while trueorfalse:
yesno = input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
#trueorfalse = False
break
elif yesno.lower().startswith("y"):
print("cool, let me prep...")
time.sleep(1)
# Place your code in the elif block
while turns > 0:
guess = input("what is the word")
if guess == word:
print('win')
#trueorfalse = False
break
else:
turns -=1
print("you have these many turns left", turns)
print("you lost")
break
All that's missing is a way to break out of the while loop. So, use the break command.
import time
name = raw_input("what is your name? ")
print "Hello " + name
#yes no statement with raw input
while True:
yesno = raw_input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
exit()
elif yesno.lower().startswith("y"):
print("cool, let me prep for e second")
time.sleep(5)
break # <-- break out of of the current loop
print "made it!"

how to fix "<function choice at 0x105303320>" in visual studio code?

I wanted to make an adventure game sort of thing and it consists mostly of print and time. sleep statements. but the only if statement with a def statement is messing it up, to a point that is. everything works perfectly fine until that end.
I have no clue what is causing this to happen. I mean with some certainty I can say that the if statement is the issue but I don't know how/why.
def choice():
input("so whats for breakfast, salad, eggs, or fish")
#many lines or print and sleep statements later
if str(choice) == "salad":
#insert if code
else:
print("try again")
expected - "hey what's for breakfast?" ans = salad. "then you have three options for salads
actual - < function choice at 0x10de89560 >
the above is what gets printed in the debug console and I have no idea why. there are no warnings or errors that VS code had told me about. I am too much of a beginner to already be getting these sorts of things, please help me.
It must be.. str(choice()).
choice is a function.
fixed code, choice is a function and requires a return
# Functions
def choice():
return input("so whats for breakfast, salad, eggs, or fish")
# Entry Point
decision = str(choice())
if decision == "salad":
#insert if code
pass
else:
print("try again")
screenshot of code running

Adding a while loop to my code to either re-run the program or terminate based on user input [Python 2.7]

I'm currently in the process of trying to add a while loop to my code that is shown below. The theory behind what I'm attempting to do is as follows:
As you can see at the very bottom of my code, I confirm the user's reservation and ask if he/she would like to create another. If the user enters 'yes", I would like the program to re-run. If no, then the program should terminate. I'm aware the best way to accomplish this is using a while loop, but I'm having a little difficulty executing this as my textbook is a little confusing on the subject.
I know it's supposed to look something like this (or something along the lines of it):
while True:
expression
break
Though I can't seem to get it to compile. Any suggestions? Below is my code:
user_continue = str(raw_input("Your reservation was submitted successfully. Would you like to do another?"))
if user_continue != 'yes':
print('Thank you for flying with Ramirez Airlines!')
Here's a simple example that shows how to use a while loop:
import time
while True:
print time.ctime()
print 'Doing stuff...'
response = raw_input('Would you like to do another? ')
if response != 'yes':
break
print 'Terminating'
Note that the code inside the while loop must be indented, unlike the code in your first code block. Indentation is very important in Python. Please always ensure that code in your questions (and answers) here is properly indented.
FWIW, the raw_input() input function returns a string, so str(raw_input()) is unnecessary clutter.
The end of your code should look something like:
user_continue = raw_input("Your reservation was submitted successfully. Would you like to do another?")
if user_continue != 'yes':
break
print('Thank you for flying with Ramirez Airlines!')
...
Your print statements are a bit funny. Since you're using Python 2.7 you don't need to do
print ('The total amount for your seats is: $'),user_people * 5180
you can just do
print 'The total amount for your seats is: $', user_people * 5180
or if you wish to use Python 3 style, put everything you're printing inside the parentheses, like this:
print ('The total amount for your seats is: $', user_people * 5180)
However, the output will look a bit messy since there will be a space between the $ and the amount. Please read the python docs to learn how to fix that.
...
Also, you have import time inside your loop. Don't do that. Generally, import statements should be at the top of your script before any other executable code.

Exit a program conditional on input (Python 2)

This is for a game. The game asks the user if s/he would like to play again. If not, the program should just exit. If yes, the entire game is repeated and asks to play again, and so on.
while True:
print "*game being played*"
# prompt to play again:
while True:
replay = raw_input("Play again? ")
print replay
if replay.lower == "yes" or "y":
break
elif replay.lower == "no" or "n":
sys.exit()
else:
print "Sorry, I didn't understand that."
However, when I actually execute this code it acts as if every answer input is a yes (even "aksj;fakdsf"), so it replays the game again.
.
When I changed the code to first consider no instead of yes:
if replay.lower == "no" or "n":
sys.exit()
I get the error
Traceback (most recent call last):
File "C:/Python27/Programs/replay game.py", line 18, in <module>
sys.exit()
NameError: name 'sys' is not defined
This might have something to do with the fact I don't actually know what sys.exit() does but just found it while googling "how to exit program python".
lower is a function in python.
Be sure to include the elipses (). It should look like string.lower()
Also, try putting it at the end of your input so you don't have to type it every time
replay = raw_input('Play again? ').lower()
As Jon Clements pointed out, something that I looked over and missed in your code, consider the following statement:
if replay.lower() == "yes" or "y":
#execute
To the human eye, this looks correct, but to the computer it sees:
if replay.lower() is equal to "yes" or if 'y' is True...execute
Your game will always replay because "y" is a string and always true. You must replace the code with something like this (my above advice included):
if replay == 'yes' or replay == 'y':
#execute
finally, import sys at the top of your program. This is where the error is occurring, because sys is a module that must be imported to the program.
Here is an article on operators that you might benefit reading from
You first need to import sys. Place this:
import sys
at the top of your code to import the sys module.
However, a much easier way to exit a script is to just do this:
raise SystemExit
The above code does the exact same thing as sys.exit.
Also, for your code to work properly, you will need to do two more things:
Reconstruct your if-statements to use the in keyword.
Invoke the .lower method by placing () after it.
Below is a fixed version of your script:
while True:
print "*game being played*"
# prompt to play again:
while True:
# I put .lower() up here so I didn't have to call it multiple times
replay = raw_input("Play again? ").lower()
print replay
if replay in ("yes", "y"):
break
elif replay in ("no", "n"):
raise SystemExit
else:
print "Sorry, I didn't understand that."
Now let me explain why you needed to remake your if-statements. As it currently stands, Python is reading your code like this:
if (replay.lower == "yes") or "y":
Furthermore, since "y" is a non-empty string (which always evaluate to True in Python), this if-statement, left as it is, will always pass as True. Using in however like I did above tests whether replay can be found in the tuple ("yes", "y").
At the beginning of the code you have to add:
import sys
then other code can follow
Firstly, sys is a standard lib package that needs to be imported to reference it. I recommend reading up a bit on importing in python.
put this at the top of your code:
import sys
That should take care of the sys namespace error
Secondly you need to understand how python evaluates if statements
if replay.lower == "no" or "n":
which can be broken up into two statements:
if ( (replay.lower == "no") or ("n") ):
the left side will evaluate to False, and the right side will evaluate to True. this is because "n" (or any non 0/non False object) evaluates to True.

Categories