how to make if/elif/else more efficient [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
i'm stuck and need a little help.
how can i make this more efficient and reduce the number of if/elif/else.
i thought to make a function that check the range of an input let's say between 1 to 5 and then return the value to print out what i need.
i would love to hear your thoughts on it:
there some code:
while True:
difficulty = input("Please choose difficulty from 1 to 3: ")
if not difficulty.isdigit():
print("Please enter a valid number: ")
else:
break
while True:
if difficulty == "1":
print("Level of difficulty is very easy.")
break
elif difficulty == "2":
print("Level of difficulty is easy.")
break
elif difficulty == "3":
print("Level of difficulty is normal.")
break
else:
difficulty = input("You chose an invalid number, choose between 1 - 3. Try again:")

Ideally, you check the range of the number in the first loop
Other than that, use a list
descriptions = [
"very easy, ok you are scared to loose but let's play.",
"easy, ok let's play."
]
while True:
i = int(difficulty) - 1
if i not in range(5):
# invalid input, get it again
difficulty = input("must be between 1 and 5: ")
continue
lines()
print("Level of difficulty is " + descriptions[i])
break

Related

How do I open another file in python? (not .txt file) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
Ok so I want to make a very very very very very simple coin flipping program and I want to make it so the player can choose if to close after the coin flipped or if to flip again. This is the code I used, the person can type either 1 or 2, and choose if to flip again or if to close the program, I tried using open("Coinflip.py) but it didn't do anything. What should I do?
import random
import time
flip = random.randint(1, 2)
if flip == 1:
print("The coin landed heads")
if flip == 2:
print("The coin landed tails")
print('')
print("")
time.sleep(1)
choice = int(input("Type 1 to exit or 2 to flip again and press enter "))
if choice == 1:
exit()
elif choice == 2:
open("Coinflip.py")
input()
You can use a function and a while loop to continuously ask for coin flips:
import random
import time
def coin_flip():
flip = random.randint(1, 2)
if flip == 1:
print("The coin landed heads")
if flip == 2:
print("The coin landed tails")
time.sleep(1)
def main():
while True:
choice = int(input("Type 1 to exit or 2 to flip again"))
if choice == 1:
break
elif choice == 2:
coin_flip()
if __name__ == "__main__":
main()
technically you don't need a function, but lets use one anyway

Three Problems that I can not resolve in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So I am creating a new simple game to practice my python programming, it is a point/score system that I wanted to implement. I also wanted to make it so it's intelligent by asking the user if it wants to play. So I have three problems at the moment, when I ask the user if it wants to play I wasn't sure what to do if they said no or "n" if they didn't want to play, instead what happens is that it just continues playing then crashes saying "n" is not defined. The second problem that I have is when the user puts the right answer for the random function I put print("You guessed it right!") but it just prints a bunch of them. My third and final problem is the point system, I wasn't sure if it executed after the million printed statements, but I'll see after I fix it.
Here is my game
import random
total_tries = 4
score = 0
print("Welcome to Guess the number game!")
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))
guess = int(input("I am thinking of a number between 1 and 20: "))
while n!= guess:
if guess < n:
total_tries - 1
print("That is too low!")
guess = int(input("Enter a number again: "))
elif guess > n:
print("That is too high")
total_tries - 1
guess = int(input("Enter a number again: "))
else:
break
while n == guess:
score = +1
print("You guessed it right!")
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
print("Mark:", str(mark) + ""%"")
print("Goodbye")
Error when putting no for playing:
while n!= guess:
NameError: name 'n' is not defined
For question 1 you want the system to exit when the user says no. I would do this by using sys.exit to kill the code.
import sys
...
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))**strong text**
else:
sys.exit('User does not want to play, exiting')
For problem 2 you are getting your print statement a million times because you're failing to exit. In the code below n is always equal to guess because you never change n. You don't need a while statement here because you already know you only left the above section when n started to equal guess. Another issue to think about. How will you make it stop when the number of turns runs out?
while n == guess:
score = +1
print("You guessed it right!")
For the third question, think about what will happen here if the number of turns reaches 0.
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
In particular, what would happen when you try to calculate mark?
This condition will only trigger when answer is "y"
if answer == "y":
n = (random.randrange(1, 10))
Remove this and the code will run or modify it as such
if answer == "y":
n = (random.randrange(1, 10))
elif answer == "n"
# set n to some other value

Number guessing Guessing Game [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I made a simple number guessing Game and it works perfectly fine, but I want to add something that says "The Number you have entered is too high/ low", because when I type in 100 as my upper bound it is much too difficult to guess the number.
import random
while True:
flag = True
while flag:
num = input('Enter an upper bound: ')
if num.isdigit():
print("Let's Play!")
num = int(num)
flag = False
else:
print('Invalid input! Try again!')
secret = random.randint(1,num)
guess = None
count = 1
while guess != secret:
guess = input('Please enter a number between 1 and ' + str(num) + ": " )
if guess.isdigit():
guess = int(guess)
if guess == secret:
print('Right! You have won!')
else:
print('Try again!')
count += 1
print('You needed', count, 'guess(es) ')
Alright, I'm not gonna solve it for you, but I'll give you a hint. This seems like a homework problem, so it would be unethical of me to provide you with a solution.
else:
print('Try again!')
count += 1
Look at this else statement here. What is the purpose of this else statement? To tell the user they got the guess wrong.
Think about how you can put an if/else condition inside this else condition, to tell the user if their input is too high, or too low.

How to make every 'beginner' shown at random during the run of the program [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Im currently in make of creating a math game that involves: addition, subtraction, multiplication and division. These parts with purple borders around them are the questions that i had created for the addition part when the user chooses to pick addition.
I dont know how to make these question be shown at random. When the user goes to select addition for addition questions everytime he does or goes back to do it again after he is done i want the questions not to be the same each time i want them to be in a different order. So its random each time.
#addition questions
def beginnerquestionsaddition():
os.system('clear')
score = 0
beginner1 = input("2 + 3 = ")
if beginner1 == ("5"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner2 = input("6 + 7 = ")
if beginner2 == ("13"):
print("Correct, Well Done!")
score += 1
time.sleep(1)
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
beginner3 = input("2 + 5 = ")
if beginner3 == ("7"):
print("Correct, Well Done!")
score += 1
os.system('clear')
time.sleep(1)
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
else:
print("Sorry you got it wrong :(")
time.sleep(1)
os.system('clear')
endquestadditionbeginner()
print("your score was: ")
print(score)
time.sleep(3)
introduction()
So this isn't exactly an answer for the specific way you decided to go about this program but this is a much simpler way:
from random import randrange
def beginner_addition():
A = randrange(1,11) # Increase range on harder questions
B = randrange(1,11) # Ex. for intermediate_addition(), randrange would be (10,21) maybe...
C = A + B
ans = input("What's the answer to " + str(A) + "+" + str(B) + "? ")
if ans == str(C):
print('Correct')
else:
print('Incorrect')
while True:
beginner_addition()
Of course, this is just example code. You could easily include your points system and perhaps move up in difficulty when the points hit a certain level. You could also randomize the operation. Sorry if this isn't what you want but I saw your code and I figured there is nothing wrong with simplifying your code...

Can't get my program to continue properly until true [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Since you are not liking my explanation of my program I have changed it purely to only a question now:
how do I allow the program to continue to check what the input was and apply a rule according until the output is mu
x = input("Enter your string: ")
while not set(x).issubset({'m', 'u', 'i'}):
print("false")
x = input("Enter your string")
print("Your String is " + x)
if x == ("mu"):
print("game complete")
quit()
#I understand that right now I am only checking if x is mu and then
#displaying the question input
#not sure how to bring the rules into the loop too
else:
while x !=("mu"):
Question = int(input("Which rule would you like to apply? enter numbers 1-4: ")
if Question is 1:
x = (x + "l")
print(x)
elif Question is 2:
print("2")
elif Question is 3:
print("3")
elif Question is 4:
print("4")
elif Question is not 1 or 2 or 3 or 4:
print("invalid rule try again")
You bring the rules into the while-loop by indenting them accordingly:
while x != "mu":
Question = int(input("Which rule would you like to apply? enter numbers 1-4: ")
if Question == 1:
x = (x + "l")
print(x)
elif Question == 2:
print("2")
elif Question == 3:
print("3")
elif Question == 4:
print("4")
else:
print("invalid rule try again")
By the way: don't us is to compare numbers. Your last elif-condition is wrong, should be Question not in (1, 2, 3, 4) or even better a simple else.

Categories

Resources