I have a code that allows a user to choose between 3 options
0- Beginner
1- Intermediate
2: Advanced
The code I have is:
if inp == 0:
out = "Beginner"
elif inp == 1:
out = "Intermediate"
elif inp == 2:
out = "Advanced"
else:
print("Invalid")
However, I'm wanting it so if a number greater than 3 was entered, it won't proceed to the second part.
The second part of the code I have is:
x=float(input("Choose a number between [0,90]"))
if x > 0 and x < 90:
print("Is Latitude in the North or South Hemisphere?")
else:
print ("Invalid")
Can someone provide some insight into how the condition is supposed to be?
Thank you!
You can do it with your code if you test for the existence of out before the second section.
You just need to initialise out before the if
out = ""
if inp == 0:
out = "Beginner"
elif inp == 1:
out = "Intermediate"
elif inp == 2:
out = "Advanced"
else:
print("Invalid")
Now, because out has become a global variable, you can test for whether or not out has been set. If out is not set, this next section is skipped.
if out:
x=float(input("Choose a number between [0,90]"))
if x > 0 and x < 90:
print("Is Latitude in the North or South Hemisphere?")
else:
print ("Invalid")
Realistically though, there's a ton of different ways you can do this. Personally, I'd probably use a function and then a return statement out of it to stop execution, but you can also break out and stop things that way or use some form of loop to wait for the variable you want.
The great thing and the frustrating thing about programming is there's normally more than one way to get it right.
Related
I'm trying to make a pokémon text based journey in python.
I listed the starter pokémon in a tuple to call the number that the user typed in the input to then store the chosen starter pokémon.
It all works but when the user would type a different integer then availabe in the tuple, for example: writing 5 while there are only 3 indexs in the tuple. The program just stops when this happens.
Is there a way for me to just tell the program to not go into debugging mode when this happens; and recalling the "ChoseStarter" function instead?
Here is the code:
if(ChosenPok == 1,ChosenPok == 2,ChosenPok == 3):
ChosenPokInt = int(ChosenPok)
StarterPok = Starter[ChosenPokInt-1] #Here is the problem
Sure = f"You chose {StarterPok} are you sure? (y/n)"
YORN = input(Sure)
if(YORN == "Y" or YORN == "y"):
Congrats = f"Congratulations!! You just got a {StarterPok}!!"
WriteFast(Congrats)
print(Starter[ChosenPokInt-1])
else:
WriteFast(ERROR)
ChoseStarter()
No idea what the question is about or what logic you want to implement. See if the below code helps though. Seems like the "if condition" is buggy in your case. The following code repeatedly asks for the correct input using a while loop. Replace the while loop with an if statement if you don't want that.
starter = ["x", "y", "z"]
chosen_pok = int(input("Select a pok: "))
while not (1 < chosen_pok < 4):
print("Invalid pok. try again...")
chosen_pok = int(input("Select a pok: "))
starter_pok = starter[chosen_pok - 1]
yorn = input(f"You chose {starter_pok} are you sure? (y/n)")
if (yorn in ["Y", "y"]):
print(starter[chosen_pok - 1])
else:
print("Error")
You should just check for the len and if ChosenPokInt is in it's boundaries:
pokemon_index = ChosenPokInt - 1
if 0 <= pokemon_index < len(Starter)-1:
# everything is fine
else:
# handle the problem case
Besides that I advice you to look into pep8 :). You can find an awesome guide here: https://pep8.org
You can add a while loop before the condition that checks first if the input is in the correct range:
ChosenPok = ChoseStarter()
pokRange = [1, 2, 3]
while not (ChosenPok in pokRange):
print("Wrong input, try again")
ChosenPok = ChoseStarter()
I'd like to create a function that add 2 to an integer as much as we want. It would look like that:
>>> n = 3
>>> add_two(n)
Would you like to add a two to n ? Yes
The new n is 5
Would you like to add a two to n ? Yes
the new n is 7
Would you like to add a two to n ? No
Can anyone help me please ? I don't how I can print the sentence without recalling the function.
The idea is to use a while loop within your function that continues to add two each time you tell it to. Otherwise, it exits.
Given that knowledge, I'd suggest trying it yourself first but I'll provide a solution below that you can compare yours against.
That solution could be as simple as:
while input("Would you like to add a two to n ?") == "Yes":
n += 2
print(f"the new n is {n}")
But, since I rarely miss an opportunity to improve on code, I'll provide a more sophisticated solution as well, with the following differences:
It prints the starting number before anything else;
It allows an arbitrary number to be added, defaulting to two if none provided;
The output text is slightly more human-friendly;
It requires a yes or no answer (actually anything starting with upper or lower-case y or n will do, everything else is ignored and the question is re-asked).
def add_two(number, delta = 2):
print(f"The initial number is {number}")
# Loop forever, relying on break to finish adding.
while True:
# Ensure responses are yes or no only (first letter, any case).
response = ""
while response not in ["y", "n"]:
response = input(f"Would you like to add {delta} to the number? ")[:1].lower()
# Finish up if 'no' selected.
if response == "n":
break
# Otherwise, add value, print it, and continue.
number += delta
print(f"The new number is {number}")
# Incredibly basic/deficient test harness :-)
add_two(2)
You can use looping in your add_two() function. So, your function can print the sentence without recalling the function.
The above answer describes in detail what to do and why, if you're looking for very simple beginner-type code that covers your requirements, try this:
n = 3
while True:
inp = input("Would you like to add 2 to n? Enter 'yes'/'no'. To exit, type 'end' ")
if inp == "yes":
n = n + 2
elif inp == "no":
None
elif inp == "end": # if the user wants to exit the loop
break
else:
print("Error in input") # simple input error handling
print("The new n is: ", n)
You can wrap it in a function. The function breaks once the yes condition is not met
def addd(n):
while n:
inp = input('would like to add 2 to n:' )
if inp.lower() == 'yes':
n = n + 2
print(f'The new n is {n}')
else:
return
addd(10)
When I run the code in PyCharm, I get exit code 0, so I know the file is compiling properly. What I don't understand is why it's not displaying anything.
I have it set up to take input and output an appropriate response based on that input, but neither CMD or PyCharm are displaying anything when I run the file. Debugging didn't throw an error, so as far as I can tell, the code itself is properly written.
Did I miss something? Am I not invoking the function properly?
def wthGen(weather):
# after generating, defines the weather states
for weather in range(0, 5):
x = 0
if weather == 0:
print("It's a beautiful day.")
if weather != 0:
x += 1
if x == 1:
print("There's a light rain; bring a coat! ")
elif x == 2:
print("The air is thick with fog. Perception debuffs apply.")
elif x == 3:
print("The rain beats down without remorse. Perception debuffs apply +1")
elif x == 4:
print("The snow nips at your fingers. Dexterity debuffs apply.")
elif x == 5:
print("The wind rages against you with all its fury. Strength debuffs apply.")
# calls wthGen to determine weather state
def main(wthGen):
w = int(input("Enter a number from 0 to 5 to determine appropriate debuffs based on weather conditions: "))
print(wthGen[0,5](w))
main()
This is an exercise from Introduction to CompSci and Programming in Python from OCW MIT. I modified it a little bit. The problem is I want to stop the program when I reached the max wrong answer but it stops if I try two times. Why two times ? How can I fix this ? As a new starter should I ask every question here ? Thanks to all
n = 0
max_guesses = 3
n = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
if n == "left" or "Left":
print("You're out of lost forest")
while n == "right" or n == "Right":
n = input("You are in the Lost Forest\n****************\n****** ***\n :(\n****************\n****************\nGo left or right? ")
n =+ 1
for n in range (max_guesses):
break
print("Game over! You ran out of your lives")
There are a few errors that contribute to your code not working properly
Your variable n is the same as the value you get from the value you input best to separate those into different values to make it easier to avoid hard to detect errors
You need to have a condition that checks if n >= max_guesses.
Welcome to the community, we try to discuss the issues here rather than looking for a whole solution.
I suggest you to first learn the very basics of programming like the decision making, control flows (i.e if statements and loops).
Also, try to attempt the question, multiple numbers of times with different logics and inputs at runtime. it will give you a better understanding of logical analysis.
Here's one of the ways you could have added the logic.
#Maximum allowed guesses
max_guesses = 3
def func1():
#Input string 'left' or 'right'
in_str = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
#Number of attempts made
n = 1
if in_str.lower() == "left":
print("You're out of lost forest")
while in_str.lower() == "right":
in_str = input("You are in the Lost Forest\n****************\n****** ***\n :(\n****************\n****************\nGo left or right? ")
n += 1
if in_str.lower() == "left":
print("You're out of lost forest")
break
if n >= max_guesses:
print("Game over!!!")
break
print("Total attempts made by user: ",n)
func1()
I have attempted to fix your code however, I have had to remove the for loop and change the variable names. Hopefully, it helps.
n = 1
max_guesses = 3
a = input("You are in the Lost Forest\n****************\n****************\n :)\n****************\n****************\nGo left or right? ")
if a.lower() == "left":
print("You're out of lost forest")
while a.lower() == "right":
if n == 3:
print("Game over! You ran out of your lives")
break
else:
a = input("You are in the Lost Forest\n****************\n****** ***\n :(\n****************\n****************\nGo left or right? ")
n += 1
I am currently writing a short program for my intro to computer science course, and my code is returning "none" even though I am pretty sure my definitions are clear. Don't mind the bulky naming for my functions and stuff, its a course requirement. The objective of the code is to be able to choose a shape and then directly input the required information without a written prompt, and then the program will RETURN the area of the chosen shape. I have been breaking my teeth over this for the past few hours, playing with it, but my code is returning none regardless of what I do. Any advice? Please refrain from blatantly giving me new code because I can get in trouble for that, just perhaps point me in the direction of my problem.
import math
# the following functions are built to calculate each shape
def circle_area(rad):
return math.pi*rad**2
def rectangle_area(side_one, side_two):
return side_one*side_two
def triangle_area(edge):
return (math.sqrt(3)/4)*(edge**2)
# the following function as assigned using the above functions
def shape_area():
shape_choice = input("Choose shape (1=circle, 2=rectangle, 3=triangle):")
if shape_choice == 1 or 3:
length_one = input("")
elif shape_choice == 2:
length_two, length_three = input("")
if shape_choice == 1:
circle_area(length_one)
elif shape_choice == 2:
rectangle_area(length_two, length_three)
elif shape_choice == 3:
triangle_area(length_one)
elif shape_choice != 1 or 2 or 3:
return None
I'm not sure why all my code isn't going into the specific code gray box, but I hope my code is more or less clear.
You are not returning the area values, just calculating them.
if shape_choice == 1:
return circle_area(length_one)
elif shape_choice == 2:
return rectangle_area(length_two, length_three)
elif shape_choice == 3:
return triangle_area(length_one)
Also, as #NomadMonad also mentions, the statement:
if shape_choice == 1 or 3:
is always true as 3 is a thing. Instead use if shape_choice == 1 or shape_choice == 3:
Your final elif can be an else as it is the final condition that can be returned. You could even remove it as python will return None if nothing is returned anyway.
This line
if shape_choice == 1 or 3
Always evaluates to True
You should change it to
if shape_choice == 1 or shape_choice == 3
Similarly
elif shape_choice != 1 or 2 or 3