Python guessing game -if/elif/else - python

I've just started learning Python and have constructed a little guessing game. It works but I would like to add a statement that if inputted number is out of range 1-10 there will be an error... Could you help or give me a hint? I suppose I should use nested if/else statement but not sure where:
import random as r
rand_num = r.randrange(1, 10)
odp = 0
i = 0
print("Guess the number from range 1-10")
while True:
i += 1
odp = int(input("Input number: "))
if (rand_num < odp):
print("Selected number is lower than you had inputted...")
elif (rand_num > odp):
print("Selected number is higher than you had inputted...")
elif (rand_num == odp):
break
print("Congrats! You have guessed the number after ", i, " tries")

You are on the right track there. You can use a nested if-elif block to check whether the number is in the range (1-10) and on error you could prompt a message saying that.
However, whenever you are using user inputs, you must use try except blocks.
You are assuming that the user would enter a stringified integer. What if the user enters an invalid character? What if the user enters a fraction?
You could keep on using if-elifs to check all the probable inputs. You probably can see how inefficient and verbose your code becomes.
If you are new to Python's error handling and haven't learnt try except finally use the nested if elifs.
However, this is how I would do the same problem
import random as r
rand_num = r.randrange(1, 10)
odp = 0
i = 0
print("Guess the number from range 1-10")
try:
while True:
i += 1
odp = int(input("Input number: "))
if odp > 10 or odp < 1:
raise ValueError("Out of bound error")
if (rand_num < odp):
print("Selected number is lower than you had inputted...")
elif (rand_num > odp):
print("Selected number is higher than you had inputted...")
elif (rand_num == odp):
break
except ValueError as e:
print(e)
You should also check for invalid types. Here's the official doc error handling

import random as r
rand_num = r.randrange(1, 10)
odp = 0
i = 0
print("Guess the number from range 1-10")
while True:
r.seed(r.random())
i += 1
input_user = int(input("Input number: "))
if abs(input_user) <= 10:
print(abs(input_user) <= 10)
if rand_num < input_user:
print("Selected number is lower than you had inputted...")
elif rand_num > input_user:
print("Selected number is higher than you had inputted...")
elif rand_num == input_user:
print("Selected number is correct!")
break
else:
print("Invalid number")
Put the else statement after all of the if/elif statements. Also, use a different seed each time to randomize the variable each time you run it.

You should definitely read how the control flow works and maybe try another good option like continue to skip the current iteration and run next one (without the use of large branching statements):
def game(minimum=1, maximum=10):
rand_num = r.randrange(minimum, maximum)
odp = 0
i = 0
print(f"Guess the number from range {minimum}-{maximum}")
while True:
i += 1
odp = int(input("Input number: "))
# Validate the input value.
if odp < minimum or odp > maximum:
print("Invalid input")
# To skip the following lines and start next cycle of while-loop
continue
if rand_num < odp:
print("Selected number is lower than you had inputted...")
continue
if rand_num > odp:
print("Selected number is higher than you had inputted...")
continue
if rand_num == odp:
if i == 1:
print("Cheater!")
else:
print("You win!")
break
game(2, 25)

Related

How to loop an input variable a fixed number of times based on what the input variable is

I am making a guessing game, and I want the option to input how many tries you have. The number that you put will be the amount of times you will have to guess the random number. Problem is, I do not know how to put this in the game. How do I implement this? I have tried for loops, but it seems to not reach it no matter where I put it. Nothing seems to work, and I don't want to end up breaking my code. Help!
from random import randint
from time import sleep as wait
while True:
while True:
try:
# Player chooses what the random numbers will be in between.
range_ = int(input("Enter the range that your numbers are going to be between. (ex. 50): "))
# Cannot put a 0, a 1, or a negative number.
if range_ == 0:
print("\nundefined cannot <0>\n")
continue
if range_ == 1:
print("\nundefined, cannot add 1 to the range.\n")
continue
if range_ < 0:
print("\nNo negatives!\n")
continue
# Player chooses how many tries they want.
tries = int(input("Enter the amount of tries you want: "))
# Cannot put a 0 or a negative number.
if tries == 0:
print("\nundefined, cannot <0> # tries::int 0\n")
continue
if tries < 0:
print("\nWhy would you want less than 0 tries?\n")
continue
break
except ValueError:
print("\nEnter a whole number please!\n")
continue
ai = randint(1, range_ + 1)
while True:
player = int(input("Enter number: "))
if player > range_:
print("Please put a number inside of the range.")
continue
if player < ai:
print("\nBigger!\n")
continue
if player > ai:
print("\nSmaller!\n")
continue
if player == ai:
print("You win!\n")
continue
if player != int:
print("Put a whole number!")
continue
if player == 0:
print("\n\nno\n\n")
wait(5)
break
if player == "":
continue
again = str(input("Do you want to play again? (yes/no): ")).lower()
if again != "yes":
print("Goodbye!")
wait(3)
break
else:
continue
You should check the state of the "again" condition at the beginning of your code:
again = "yes"
while again == "yes":
while True:
try:
# Player chooses what the random numbers will be in between.
range_ = int(input("Enter the range that your numbers are going to be between. (ex. 50): "))
# Cannot put a 0, a 1, or a negative number.
As well as keep track of the number of attempts that the user has made:
ai = randint(1, range_)
tries_count = 0
while again == "yes":
if tries_count <= tries:
Keeping track of attempts with something like:
if player > ai and player != 0:
print("\nSmaller!\n")
tries_count += 1
continue
Try using for loops -
n = int(input('How many times you want to run the code'))
for i in range(n):
# your code
You will need to add this at the start of your code after the import statements.

Python user input for Def functions, I need to ask for a number and then use that number to either count down or factor up

I now this isn't right, but I am I on the right path? I am super new to this. Any help is appreciated. The assignment is to create a script that allows the user to input a number. Then If 1 is entered, a countdown from that number to zero is printed.
If 2 is entered, the factorial of the number is printed.
num = int(input("Enter a number greater than 1: "))
if num<0:
print("please enter number greater than zero");
elif(num==0):
print("Please enter number greater than 0");
else:
select = int(input("Enter 1 to countdown from or enter 2 to get the factorial"))
select = true
def factorial():
factorial=1;
if num<0:
print("Factorial does not defined for negative integer");
elif(num==0):
print("The factorial of 0 is 1");
else:
while(num>0):
factorial=factorial*num
num=num-1
print("factorial of the given number is: ")
print(factorial)
def countdown():
countDown = num
while (countDown >= 0):
print(countDown)
countDown = countDown - 1
if countDown == 0:
print("Done!")
break
Yes, you are on the right path. Don't use ; at the end of statements, its not required in python. You can add this condition so as to call the functions based on the user input.
else:
select = int(input("Enter 1 to countdown from or enter 2 to get the factorial"))
if select==1:
countdown()
elif select==2:
factorial()
Also, to avoid
UnboundLocalError: local variable 'num' referenced before assignment
use global num at the begining of your factorial function. Good luck!
UPDATE: Here is how your entire code should look like
def factorial():
global num
factorial=1
if num<0:
print("Factorial does not defined for negative integer")
elif(num==0):
print("The factorial of 0 is 1")
else:
while(num>0):
factorial=factorial*num
num=num-1
print("factorial of the given number is: ")
print(factorial)
def countdown():
countDown = num
while (countDown >= 0):
print(countDown)
countDown = countDown - 1
if countDown == 0:
print("Done!")
break
num = int(input("Enter a number greater than 1: "))
if num<0:
print("please enter number greater than zero")
elif(num==0):
print("Please enter number greater than 0")
else:
select = int(input("Enter 1 to countdown from or enter 2 to get the factorial"))
if select==1:
countdown()
elif select==2:
factorial()
Figured it out with a lot of help. Thanks!! I appreciate the help.
Here is the final code:
def countdown(num):
countdown_num = num
print (countdown_num)
while (countdown_num >= 0):
print(countdown_num)
countdown_num = countdown_num - 1
if countdown_num == 0:
print("Done!")
break
def factiorial(num):
factorial_num = 1
while num>0:
factorial_num = factorial_num * num
num = num - 1
print(factorial_num)
def main():
num = int(input("Enter a number greater than 1: "))
if num<0:
print("please enter number greater than zero")
elif num==0:
print("Please enter number greater than zero, not zero")
else:
select = int(input("Enter 1 to countdown from or enter 2 to get the factorial"))
if select==1:
countdown(num)
if select==2:
factiorial(num)
main()

How to create a loop within this game successfully?

I'm fairly new to Python so I'm not sure how to go about this. I have created this random number guessing game, and I have it down except for the fact that the game is supposed to never end. Once the user guesses the number, the game should start over. Here is my code.
import random
num = random.randint(1, 100)
def main():
guess_num = 0
guess = int(input("Enter an integer from 1 to 100: "))
while num != guess:
if guess < num:
print("Too low, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
elif guess > num:
print("Too high, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
else:
print("Congratulations, that's correct!")
guess_num = guess_num+1
print("You guessed "+str(guess_num)+" times!")
break
main()
main()
while True:
main()
This makes your main method run until you stop it.
You put a break statement in your else. If you remove it it will work. But you also have to put your num statement inside your main.
This should do the job:
def main():
num = random.randint(1, 100)
guess_num = 0
guess = int(input("Enter an integer from 1 to 100: "))
while num != "guess":
if guess < num:
print("Too low, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
elif guess > num:
print("Too high, try again.")
guess = int(input("Enter an integer from 1 to 100: "))
guess_num+=1
else:
print("Congratulations, that's correct!")
guess_num = guess_num+1
print("You guessed "+str(guess_num)+" times!")
main()
main()
All lines down from def main(): must be indented four spaces. Maybe it's just a problem with the copy paste, but I find myself really uncomfortable looking at improperly indented Python code.
Remove the print statement right after while num != "guess": not sure what it does
Remove the quotes around guess as right now you're checking a number against a string
Now, to implement your functionality, you should move the num = random.randint(1, 100) line into the function to choose a new number. Then, call the function while true:
while True:
main()

Making a Calculator which take input from user until user enter 0 but not working correctly

I am a newbie in python and trying to make a calculator but no getting how to make it
I am making a Calculator which will take input from the user until the user enters 0 and then do the operations
but I am stuck here
if anyone can help me doing this work I will be very thankful to him/her.
num = None
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
options = int(input("Enter Your Choice: "))
# For Addition or Option 1
if options == 1:
total = 0
while(num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total + num
print("Your Calculated Number is: {} ".format(total))
# For Subtraction or Option 2
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
print("Your Calculated Value is: {}".format(total))
# Multiplication for Option 3
elif options == 3:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
# Division for Option 4
elif options == 4:
total = 1
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
# When User Wants to Exit
else:
print("Thank You for Using the Calculator")
Here is a better approach using itertools.reduce. Instead of repeating the same code for inputting a number multiple times, put it into a function. This will also help avoid the errors in your code and clarify the logic. A second generator function can be used to get the series of values until the user enters zero.
from functools import reduce
import operator
def input_number():
while True:
try:
return float(input("(Enter '0' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
def input_series():
while True:
n = input_number()
if n == 0:
return
yield n
operations = {
1: operator.add,
2: operator.sub,
3: operator.mul,
4: operator.truediv
}
# Asking Users for the Specific Operations
print(("1. For Addition \n 2. For Subtraction. \n 3. For Multiplication. \n 4. For Division \n 5.For Exit"))
option = int(input("Enter Your Choice: "))
# For Addition or Option 1
if option == 5:
print("Thank You for Using the Calculator")
else:
total = reduce(operations[option], input_series())
print("Your Calculated Value is: {}".format(total))
Instead of
elif options == 2:
total = 0
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num
use (the changes are only in the 2nd line and in the last one)
elif options == 2:
total = None
while (num != 0):
try:
num = float(input("(Enter \'0'\ When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total - num if total is not None else num
The same method you may use for the elif options == 4: branch.
The problem with subtraction is that the variable total is not initialized.
The problem with multiplication and division is that when the user inputs "0", the variable total is multiplied or divided by zero before it is checked in the while statement. what I would normally do is this:
elif options == 3:
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number ")) # No need to escape single quotes when your string uses double quotes
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total))
However, if you wanted a quick fix, you can have the user input 1 instead of 0 for multiplication and division:
elif options == 4:
total = 1
while (num != 1):
try:
num = float(input("(Enter '1' When Complete.) Enter Number "))
except:
print("Error, Enter Valid Number")
continue
total = total / num
print("Your Calculated Value is: {}".format(total))
Edit: If you want division to work the way you specified, you could do something like this:
elif options == 2:
total = 1
try:
first_number = float(input("(Enter '0' When Complete.) Enter Number "))
if first_number == 0:
print("Your Calculated Value is: 0")
exit()
except ValueError:
print("Error, Enter Valid Number")
continue
total = 1
while True:
try:
num = float(input("(Enter '0' When Complete.) Enter Number "))
if num == 0:
break
except ValueError:
print("Error, Enter Valid Number")
continue
total = total * num
print("Your Calculated Value is: {}".format(total + first_number))

Return not showing up when called

I'm trying to get the user guess the number the computer is producing randomly. When passing the return function nothing shows up.
user = 0
result = ""
import random
print ("Welcome to Guess My Number Game")
def main():
#user input
computer = random.randint(1,100)
print(computer)
user=int(input("Guess the number:"))
return (result)
def results(result):
computer = random.randint(1,100)
diff = 0
diff = user - computer
if diff < -10:
result = ("Too Low")
elif diff > 10:
result = ("Too High")
elif diff < 0:
result = ("Getting warmer, but still low")
elif diff > 0:
result = ("Getting warmer, but still high")
else:
guesses = str(guesses)
result = ('Good job, you guessed correctly in,',guesses,'guesses!')
There are couple of problems in your indentation however, if I can understand the logic correctly, you can do something similar to the below in order to keep user asking for a guess till getting a match;
import random
def results(val):
guesses = 0
while True:
user = int(input("Guess the number: "))
guesses = guesses + 1
diff = user - computer
if diff < -10:
print("Too Low")
elif diff > 10:
print("Too High")
elif diff < 0:
print("Getting warmer, but still low")
elif diff > 0:
print("Getting warmer, but still high")
else:
print('Good job, you guessed correctly in {} guesses!'.format(guesses))
break
return guesses
def main():
computer = random.randint(1, 100)
number_of_guesses = results(computer)
>>> results()
Guess the number: 2
Too Low
Guess the number: 10
Too Low
Guess the number: 50
Too High
Guess the number: 40
Too High
Guess the number: 30
Getting warmer, but still high
Guess the number: 25
Getting warmer, but still low
Guess the number: 26
Getting warmer, but still low
Guess the number: 28
Getting warmer, but still low
Guess the number: 29
Good job, you guessed correctly in 9 guesses!
9
I'm going to assume that you are trying to print the result variable from the results method
If my above statement is correct you have a misunderstanding about what return does. return is usually placed in a function to that will return some value. So you should make your code into this.
computer = random.randint(1,100)
print(computer) #if you print this guessing the number will be very easy
user=int(input("Guess the number:"))
print(results(computer, user))
def results(computer, user):
results = ""
# computer = random.randint(1,100) #you wont need this either
diff = 0
diff = user - computer
if diff < -10:
result = ("Too Low")
elif diff > 10:
result = ("Too High")
elif diff < 0:
result = ("Getting warmer, but still low")
elif diff > 0:
result = ("Getting warmer, but still high")
else:
guesses = str(guesses)
result = ('Good job, you guessed correctly in,',guesses,'guesses!')
return result

Categories

Resources