User types an integer number (smaller than 100, bigger than 0)
If user types 0, the program ends. In case of numbers that are 100 or bigger, or that are -1 or smaller, it shows INVALID, and prompts user to keep entering number.
a = int(input('Enter a number: '))
total =0
keep = True
while keep:
if a ==0:
print('Thanks for playing.. goodbye')
break;
else:
while a>99 or a <0:
print('INVALID')
a = int(input('Enter a number: '))
total = total + a
print(total)
a = int(input('Enter a number: '))
Just putting normal numbers and getting the sum, I enter 0, then it stops, but when I enter 100, INVALID shows up, then I enter 0, the program doesn't end and it keeps showing me INVALID.
Any suggestions will be appreciated. Thanks!
I think this is a more pythonic approach
total =0
while True:
a = int(input('Enter a number: '))
if a == 0:
break
if a>99 or a <0:
print('INVALID')
else:
total = total + a
print(total)
print('Thanks for playing.. goodbye')
When using your code, the result is :
Enter a number: 100
INVALID
Enter a number: 0
0
Enter a number: 0
Thanks for playing.. goodbye
And I think your code may should be:
a = int(input('Enter a number: '))
total =0
keep = True
while keep:
if a ==0:
print('Thanks for playing.. goodbye')
break;
else:
while a>99 or a <0:
print('INVALID')
a = int(input('Enter a number: '))
if a ==0:
print('Thanks for playing.. goodbye')
break;
total = total + a
print(total)
a = int(input('Enter a number: '))
You may procide your requirement more detail.
At your code, the else never breaks the loop so it only sums the total after it has exitted that 2nd loop, but that 2nd one doesn't have a behaviour for 0. You should try to keep it simple with just one loop.
total =0
while True:
a = int(input('Enter a number: '))
if a == 0:
print('Thanks for playing.. goodbye')
break
else:
if a > 99 or a < 0: # You don't need a second while, just an if.
print('INVALID')
else:
total = total + a
print(total)
Identation is key at python, be careful with it.
Also cleaned a bit your code. As example: Since you get into a loop with the while there is no need to use 2-3 different inputs in and out of the loop, just add it once at the beginning inside of the loop.
You are in while loop of else conditional since you entered 100 at first and you can't get out of there unless you enter a number satisfies 0 <= a <= 99. You can make another if statement for a == 0 to exit the while loop just below a = int(input('Enter a number')) of else conditional.
I think it is good to check where you are in while loop using just one print(a). For example, just before if-else conditional or just before while of else conditional. Then, you can check where it gets wrong.
a = int(input('Enter a number: '))
total = 0
keep = True
while keep:
\\ print(a) here to make sure if you are passing here or not.
if a == 0:
print('Thanks for playing.. goodbye')
break;
else:
\\ print(a) here to make sure if you are passing here or not.
while a > 99 or a < 0: \\You are in while loop since you entered 100 at first and you can't get out from here unless you enter a: 0 <= a <= 99.
print('INVALID')
a = int(input('Enter a number: '))
if a == 0:
print('Thanks for playing.. goodbye')
break;
total = total + a
print(total)
a = int(input('Enter a number: '))
Related
New to this so please bear with me. I'm trying to run a loop that asks the user to input a number between 1 and 100. I want to make it to where if they enter a number outside of 100 it asks again. I was able to do so but I can't figure out if I'm using the correct loop. Also whenever I do get inbetween 1 and 100 the loop continues.
code below:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
else:
while user_input > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
I think the clearest way to do this is to start with a loop that you break out of when you finally get the right answer. Be sure to handle a bad input like "fubar" that isn't an integer
while True:
try:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
break
print("Not between 1 and 100, try again")
except ValueError:
print("Not a number, try again")
In python 3 you can use range to do bounds checking. If you do
if user_input in range(1, 101)
range will calculate the result without actually generating all of the numbers.
When your code is run, it will continue to ask for an input, even if the input given is less than 100. One way to fix this would be to do this:
try_again = 1000
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
elif user_input > 100:
while try_again > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
This code first tests if the user's input is more than 100, then runs a while statement in which the base value is more than 100. When the user inputs another value, if it is over 100, it continues, otherwise it does not.
Below is an example of a program that gets you the output that you are seeking:
attempts = 0
while True:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input > 100 or user_input < 1:
print('Please try again')
attempts += 1
continue
elif attempts >= 1 and user_input <= 100 and user_input >= 1:
print('There you go!')
break
else:
print('Nice!')
break
Start by putting your prompt for the user within the loop so that the user can be asked the same prompt if the fail to enter a number between 1 and 100 the first time. If the user input is greater than 100 or less than 1, we will tell the user to try again, we will add 1 to attempts and we will add a continue statement which starts the code again at the top of the while loop. Next we add an elif statement. If they've already attempted the prompt and failed (attempts >= 1) and if the new input is less than or equal to 100 AND the user input is also greater than or equal to 1, then the user will get the 'There you go' message that you assigned to them. Then we will break out of the loop with a break statement in order to avoid an infinite loop. Lastly we add an else statement. If the user satisfies the prior conditions on the first attempt, we will print 'Nice' and simply break out of the loop.
So the code before behaved properly before my "while type(number) is not int:" loop, but now when the user presses 0, instead of generating the sum of the list, it just keeps looping.
Would really appreciate some help with this! Thank you!
List = []
pro = 1
while(pro is not 0):
number = False
while type(number) is not int:
try:
number = int(input("Please enter a number: "))
List.append(number)
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
ans = 0
print(Sum)
Actually, this should keep looping forever for all numbers the user may input, not just zero.
To fix this, you can just add this break condition after (or before, it doesnt really matter) appending:
number = int(input("Please enter a number: "))
List.append(number)
if number == 0:
break
So I got it to work, when written like this:
List = []
pro = 1
while(pro is not 0):
while True:
try:
number = int(input("Please enter a number: "))
List.append(number)
break
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
pro = 0
print(Sum)
But I don't really understand how this is making it only take int values, any clarification would be really helpful, and otherwise thank you all for your help!
I'm guessing that you want to end while loop when user inputs 0.
List = []
pro = 1
while pro is not 0:
try:
number = int(input("Please enter a number: "))
List.append(number)
# This breaks while loop when number == 0
pro = number
except ValueError:
print("Please only enter integer values.")
Sum = 0
for i in List:
Sum += i
print(Sum)
EDIT: I have also cleaned the unnecessary code.
Put if number == 0: inside while type(number) is not int: loop like this:
List = []
while True:
try:
number = int(input("Please enter a number: "))
if number == 0:
Sum = 0
for i in List:
Sum = i + Sum
print(Sum)
break
List.append(number)
except ValueError:
print("Please only enter integer values.")
I'm learning how to program in Python and I found 2 tasks that should be pretty simple, but the second one is very hard for me.
Basically, I need to make a program where computer guesses my number. So I enter a number and then the computer tries to guess it. Everytime it picks a number I need to enter Lower or Higher. I don't know how to do this. Could anyone advise me on how to do it?
For example (number is 5):
computer asks 10?
I write Lower
computer asks 4?
I write Higher
Program:
I already made a program which automatically says Higher or Lower but I want to input Lower or Higher as a user.
from random import randit
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
You may want to put in a case for if it doesn't match you input, also I think you need a case for when the guess finally equals the number, you may want to allow an input for "Found it!" or something like that.
from random import randint
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
answer = str(input("Higher/Lower? "))
if answer == 'Higher':
min = guess
elif answer == 'Lower':
max = guess
attempts += 1
print("I needed", attempts, "attempts")
from random import randit
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
number = int(input("Number? "))
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
problem is your using a loop but inputting value once at start of app . just bring input inside the while statement hope this help
from random import randint
print('choos a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla computer wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break
from random import *
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
attemps =0
guess = randint(min,max)
while guess != number:
userInput=input(str(guess)+"?")
if userInput.lower()=="lower":
max=guess
elif userInput.lower()=="higher":
min=guess
attemps += 1
guess = randint(min,max)
print("I needed", attemps, "attempts to guess ur number ="+str(guess))
output:
Number? 5
66?lower
63?lower
24?lower
19?lower
18?lower
10?lower
4?higher
9?lower
6?lower
4?higher
I needed 10 attempts to guess ur number =5
I am struggling with some simple algorithm which should make python guess the given number in as few guesses as possible. It seems to be running but it is extremely slow. What am I doing wrong. I have read several topics already concerning this problem, but can't find a solution. I am a beginner programmer, so any tips are welcome.
min = 1
max = 50
number = int(input(("please choose a number between 1 and 50: ")))
total = 0
guessed = 0
while guessed != 1:
guess = int((min+max)/2)
total += 1
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
min = guess + 1
elif guess < number:
max = guess - 1
Thanks
ps. I am aware the program does not check for wrong input ;)
Your logic is backwards. You want to lower the max when you guess too high and raise the min when you guess too low. Try this:
if guess == number:
print("The number has been found in ",total," guesses!")
guessed = 1
elif guess > number:
max = guess - 1
elif guess < number:
min = guess + 1
Apart from having the logic backwards, you should not be using min and max as variable names. They are python functions. You can also use while True and break as soon as the number is guessed.
while True:
guess = (mn + mx) // 2
total += 1
if guess == number:
print("The number has been found in {} guesses!".format(total))
break
elif guess < number:
mn = guess
elif guess > number:
mx = guess
You will also see by not adding or subtracting 1 from guess this will find the number in less steps.
from random import randint
print('choose a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla python wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break
So I am very new to python as I spend most of my time using HTML and CSS. I am creating a small project to help me practice which is a number guessing game:
guess_number = (800)
guess = int(input('Please enter the correct number in order to win: '))
if guess != guess_number:
print('Incorrect number, you have 2 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print('Incorrect number, you have 1 more attempts..')
guess2 = int(input('Please enter the correct number in order to win: '))
if guess2 != guess_number:
print()
print('Sorry you reached the maximum number of tries, please try again...')
else:
print('That is correct...')
elif guess == guess_number:
print('That is correct...')
So my code currently works, when run, but I would prefer it if it looped instead of me having to put multiple if and else statements which makes the coding big chunky. I know there are about a million other questions and examples that are similar but I need a solution that follows my coding below.
Thanks.
Have a counter that holds the number of additionally allowed answers:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + str(tries_left if tries_left > 0 else 'no') + ' more attempts..')
If you don't know how many times you need to loop beforehand, use a while loop.
correct_guess = False
while not correct_guess:
# get user input, set correct_guess as appropriate
If you do know how many times (or have an upper bound), use a for loop.
n_guesses = 3
correct_guess = False
for guess_num in range(n_guesses):
# set correct_guess as appropriate
if correct_guess:
# terminate the loop
print("You win!")
break
else:
# if the for loop does not break, the else block will run
print("Out of guesses!")
You will get an error, TypeError: Can't convert 'int' object to str implicitly if you go with the answer you have selected. Add str() to convert the tries left to a string. See below:
guess_number = 800
tries_left = 3
while tries_left > 0:
tries_left -= 1
guess = int(input('Please enter the correct number in order to win: '))
if guess == guess_number:
print('That is correct...')
break
else:
print('Incorrect number, you have ' + (str(tries_left) if tries_left > 0 else 'no') + ' more attempts..')