optionone = 0 #DEFINING BOTH VARIABLES
optiontwo = 0
class first_day_morning: #WORKING
optionone = input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")
def first_choice(optionone): #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
if optionone == 1:
time.sleep(1)
print('')
print("You have chosen to get out of the house for once")
elif optionone == 2:
time.sleep(1)
print('')
print("DO LATER")
else:
time.sleep(1)
print('')
print("please choose a valid option")
first_choice(int(input()))
I am trying to make it so that the user input decides the outcome of the if statement, if user inputs 1, then something happens, if user inputs 2 then something else happens, if user inputs anything else, than the if statement runs again as only 1 or 2 are valid inputs. However, the problem is that no matter what the user inputs, the if statement does not run, and no error is shown either. I tried a try/except in case an error just isn't showing for some reason (try except ValueError:) and nothing seemed to work I have also tried to specify the input as str, int, float, no specification, raw_input etc. and nothing really works, can someone help?
ps. I am using Visual Studio Code
As you can see, the if statement does not run as no error is shown even after user input.
When the program runs, the class body will be evaluated, meaning the input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ") will prompt for input. That value will then be kept in first_day_morning.optionone, however first_choice's optionone is different. It is equal to the parameter supplied on the final line, int(input()), which will silently prompt for another input, and then convert it to an integer. From what I think you're trying to achieve, I'd recommend you remove the class and change the final line to:
first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))
def first_choice():
print('')
print("You have chosen to get out of the house for once")
def second_choice():
print('')
print("DO LATER")
def third_choice():
print('')
print("please choose a valid option")
while True:
print("""Select a choice""")
c = int(input('enter your choice:'))
if c == 1:
first_choice()
elif c == 2:
second_choice()
elif c == 3:
third_choice()
elif c == 4:
break
i dont really understand what u r trying to acomplish here, but the code works for me, some tips from a beginer:
-you define optiontwo and never use it
-you you are filling optionone with input inside a class, dont know why, cause is never used
not sure what do u want, but try this:
import time
def first_choice(optionone): #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
if optionone == 1:
time.sleep(1)
print('')
print("You have chosen to get out of the house for once")
elif optionone == 2:
time.sleep(1)
print('')
print("DO LATER")
else:
time.sleep(1)
print('')
print("please choose a valid option")
first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))
although, test it in console, not sure about vscode but running inside sublime does not ask for input
Related
Im a middle school student, and im starting to learn coding in python. I have been watching video tutorials, but i cant seem to figure out how to make the game quit if you type q. here what i have..
print('How old do you thing Fred the Chicken is?')
number = 17
Quit = q
run = 17
while run:
guess = int(input('Enter What You Think His Age Is....'))
print('How old do you thing Fred the Chicken is?')
number = 17
Quit = 'q'
run = 17
while run:
guess = int(input('Enter What You Think His Age Is....'))
if guess == number:
print('Yes :D That is his age...')
run = False
elif guess < number:
print('No, Guess a little higher...')
elif guess > number:
print('No, Guess a little lower....')
print('Game Over')
print('Press Q to Quit')
if run == False:
choice = input('Press Q to Quit')
if choice == 'q'
import sys
exit(0)
Getting Q as input
Quit = int(input('Press Q to Quit')
You're asking for Q as the input, but only accepting an int. So take off the int part:
Quit = input('Press Q to Quit')
Now Quit will be whatever the user typed in, so let's check for "Q" instead of True:
if Quit == "Q":
Instead of sys.exit(0), you can probably just end your while look with break or just return if you're in a function.
Also, I don't recommend the name "Quit" for a variable that just stores user input, since it will end up confusing.
And remember that indentation is important in Python, so it needs to be:
if run == False:
choice = input('Press Q to Quit')
if choice == "Q":
# break or return or..
import sys
sys.exit(0)
That may just be a copy/paste error though.
Indentation and Syntax
I fixed the indentation and removed some extraneous code (since you duplicate the outer loop and some of the print statements) and got this:
print('How old do you thing Fred the Chicken is?')
number = 17
run = True
while run:
guess = int(input('Enter What You Think His Age Is....t'))
if guess == number:
print('Yes :D That is his age...')
run = False
elif guess < number:
print('No, Guess a little higher...')
elif guess > number:
print('No, Guess a little lower....')
if run == False:
print('Game Over')
choice = input('Press Q to Quit')
if choice == 'q'
break
This gave me a syntax error:
blong#ubuntu:~$ python3 chicken.py
File "chicken.py", line 23
if choice == 'q'
^
SyntaxError: invalid syntax
So Python is saying there's something wrong after the if statement. If you look at the other if statements, you'll notice that this one is missing the : at the end, so change it to:
if choice == 'q':
So with that change the program runs, and seems to do what you want.
Some suggestions
Your instructions say "Press Q to Quit", but you actually only accept "q" to quit. You may want to accept both. Python has an operator called or, which takes two truth values (True or False) and returns True if either of them is True (it actually does more than this with values besides True and False, see the documentation if you're interested).
Examples:
>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False
So we can ask for Q or q with if choice == "Q" or choice == "q":.
Another option is to convert the string to lower case and only check for q, using if choice.lower() == "q":. If choice was Q, it would first convert it to q (with the .lower()), then do the comparison.
Your number is always 17. Python has a function called random.randint() that will give you a random number, which might make the game more fun. For example, this would make the chicken's age between 5 and 20 (inclusive):
number = random.randint(5, 20)
There are many ways to exit certain things. For loops, it is using break, and for functions you can use return. However, for programs, if you wish to exit your program before interpretation finishes (end of the script) there are two different types of exit() functions. There is sys.exit() which is part of the sys module, and there is exit() and quit() which is a built-in. However, sys.exit() is intended for programs not in IDLE (python interactive), while the built-in exit() and quit() functions are intended for use in IDLE.
You can use the break statement to break out of a while loop:
while True:
guess = int(input("...")
# ...rest of your game's logic...
# Allow breaking out of the loop
choice = input("Enter Q to quit, or press return to continue")
if choice.lower() == "q":
break
That means the interpreter exits the while loop, continues looking for more commands to run, but reaches the end of the file! Python will then exit automatically - there's no need to call sys.exit
(as an aside, you should rarely use sys.exit, it's really just used to set non-zero exit-status, not for controlling how your program works, like escaping from a while loop)
Finally, the main problem with the code you posted is indentation - you need to put the appropriate number of spaces at the start of each line - where you have something like:
if run == False:
choice = input('Press Q to Quit')
It must be like this:
if run == False:
choice = input('Press Q to Quit')
Same with anything like while, for, if and so on.
Hello fellow programmers! I am a beginner to python and a couple months ago, I decided to start my own little project to help my understanding of the whole development process in Python. I briefly know all the basic syntax but I was wondering how I could make something inside a function call the end of the while loop.
I am creating a simple terminal number guessing game, and it works by the player having several tries of guessing a number between 1 and 10 (I currently made it to be just 1 to test some things in the code).
If a player gets the number correct, the level should end and the player will then progress to the next level of the game. I tried to make a variable and make a true false statement but I can't manipulate variables in function inside of a while loop.
I am wondering how I can make it so that the game just ends when the player gets the correct number, I will include my code down here so you guys will have more context:
import random
import numpy
import time
def get_name(time):
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
# The Variable 'tries' is the indication of how many tries you have left
tries = 1
while tries < 6:
def try_again(get_number, random, time):
# This is to ask the player to try again
answer = (input(" Do you want to try again?"))
time.sleep(2)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
else:
print("Thank you for playing the game, I hope you have better luck next time")
def find_rand_num(get_number, random, time):
num_list = [1,1]
number = random.choice(num_list)
# Asks the player for the number
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
try_again(get_number, random, time)
def get_number(random, try_again, find_rand_num, time):
# This chooses the number that the player will have to guess
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
find_rand_num(get_number, random, time)
if tries < 2:
get_name(time)
tries += 1
get_number(random, try_again, find_rand_num, time)
else:
tries += 1
get_number(random, try_again, find_rand_num, time)
if tries > 5:
break
I apologize for some of the formatting in the code, I tried my best to look as accurate as it is in my IDE. My dad would usually help me with those types of questions but it appears I know more python than my dad at this point since he works with front end web development. So, back to my original question, how do I make so that if this statement:
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
is true, the while loop ends? Also, how does my code look? I put some time into making it look neat and I am interested from an expert's point of view. I once read that in programming, less is more, so I am trying to accomplish more with less with my code.
Thank you for taking the time to read this, and I would be very grateful if some of you have any solutions to my problem. Have a great day!
There were too many bugs in your code. First of all, you never used the parameters you passed in your functions, so I don't see a reason for them to stay there. Then you need to return something out of your functions to use them for breaking conditions (for example True/False). Lastly, I guess calling functions separately is much more convenient in your case since you need to do some checking before proceeding (Not inside each other). So, this is the code I ended up with:
import random
import time
def get_name():
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
def try_again():
answer = (input("Do you want to try again? "))
time.sleep(2)
# Added return True/False to check whether user wants to play again or not
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
return False
# Joined get_number and find_random_number since get_number was doing nothing than calling find_rand_num
def find_rand_num():
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
num_list = [1,1]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
# Added return to check if correct answer is found or not
return "Found"
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
tries = 1
while tries < 6:
if tries < 2:
get_name()
res = find_rand_num()
if res == "Found":
break
checker = try_again()
if checker is False:
break
# Removed redundant if/break since while will do it itself
tries += 1
I have a code here that uses functions to draw outputs. I keep getting "prompt" is not defined but isn't it already stated in the function filterer?
[enter image description here][1]
def menu():
print ("[1] Compute Area of a Circle")
print ("[2] Compute Perimeter of a Rectangle")
print ("[3] Compute Volume of a Cone")
print ("[4] Compute Slope of a Straight Line")
print ("[5] Exit")
#Determining the input of the user
choice = filterer("Choose from the menu:")
#function for the filter
def filterer(prompt):
while True:
choice = float(input(prompt))
if choice > 5 or choice < 1:
print ("Must input integer between 1 and 5. Input again")
elif choice.is_integer == False:
print ("Must put an integer. Input again.")
else:
return prompt
filterer(choice)
#Hamms and #stybl both answered this in the comments, however, just to be clear, you need to change
filterer(prompt)
into
filterer("do some amazing thing or something")
Except with the quote you want to use as a prompt instead of "do some amazing thing or something."
The key to this is to think about the scope of the code. filterer(prompt) assumes prompt is defined by the time it's called. But you're calling it without ever defining a prompt. You could define the prompt if you wanted to, for example,
prompt = "do something super groovy"
filterer(prompt)
Others have pointed out the main issue, which is that you're trying to reference a variable (prompt) which doesn't exist in that scope.
That said, I don't think you want to call filterer twice, and I don't think you want it to return the prompt, but rather the choice made. Also, your integer testing wasn't right.
Here's full working code:
def filterer(prompt):
while True:
try:
choice = int(input(prompt))
except ValueError:
# Value couldn't be parsed as an integer
print("You must enter an integer. Try again.")
else:
# Value was successfully parsed
if choice > 5 or choice < 1:
print("Must input integer between 1 and 5. Input again")
else:
return choice # <-- changed from prompt
def menu():
print("[1] Compute Area of a Circle")
print("[2] Compute Perimeter of a Rectangle")
print("[3] Compute Volume of a Cone")
print("[4] Compute Slope of a Straight Line")
print("[5] Exit")
# Determining the input of the user
choice = filterer("Choose from the menu: ")
print("You chose: {}".format(choice))
menu()
prompt is defined within the scope of the function filterer, so it cannot be accessed outside the function. The line:
filterer(prompt)
Should be changed to something like:
foo=filterer(bar)
The variable bar has to be defined before doing this.
this is kinda my homework and I'm stuck on making the code becoming a follow up question, like this code here, I've tried inserting an if statement after that but it gave me an unexpected incent error.
Here are my codes so far:
Choice = input("Hello! Do you want to buy or sell snakes? Please enter (b) or (s) :")
if Choice == "b":
buySnake = input ("What snake do you want to buy? We are selling python, kingsnake, rattlesnake, deathadder, cobra, mamba, viper and gartersnake. Please choose one : ")
if buySnake == "python":
return (to be added)
elif Choice == "s":
sellFsnakes(snakeList,name,amount)
else:
print("Please try again.")
buyWsnakes(snakeList,name,amount)
You have an extra indent. Just remove the extra level of indentation:
Choice = input("Hello! Do you want to buy or sell snakes? Please enter (b) or (s) :")
if Choice == "b":
buySnake = input ("What snake do you want to buy? We are selling python, kingsnake, rattlesnake, deathadder, cobra, mamba, viper and gartersnake. Please choose one : ")
if buySnake == "python":
return (to be added)
elif Choice == "s":
sellFsnakes(snakeList,name,amount)
else:
print("Please try again.")
buyWsnakes(snakeList,name,amount)
Indentation is the way to create code blocks in Python. Your error says exactly what you did wrong.
if condition:
# executes if condition is met
if internalCondition:
# executes if both condition and internalCondition is met
elif otherCondition:
# executes if first statement didn't and otherCondition is met
else:
# executes if nothing else executed
You indented if internalCondition: with excess whitespaces.
I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.