While loop 2 int values [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I am trying to write a function to get 2 int values from a user until their sum is 21, Simple!!
The aim is to keep prompting the user to pass 2 int values until the condition is met. I am not sure where the code breaks as it stops when either conditions is met, both if true or false.
def check_for_21(n1,n2):
result = 0
while True:
while result != 21:
try:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
except:
if n1+n2 == 21:
print("You got it! ")
else:
break
break

This is what you are looking for you had multiple logical errors! However, the idea was there but wrongly formatted. In this program, it runs continuously until you enter two numbers and their sum is 21
def check_for_21():
while True:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
break
check_for_21()

Try this. This will meet your requirment.
a = 5
while (a<6):
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 == 21:
print("You got it ")
break
else:
print("You did not get to 21! ")

Take the input, check for result, if you get 21, break the loop.
def check_for_21(n1,n2):
result = 0
while True:
try:
n1 = int(input("Enter first number >> "))
n2 = int(input("Enter second number >> "))
if n1+n2 != 21:
print("You did not get to 21! ")
else:
print("You got it! ")
break
except:
pass

Below is the test result of the code that worked for me:

Related

how to add an error message when an integer is input instead of a string

I am trying to add an error when a string is entered instead of an integer. I've looked at other similar posts but when I try and implement it into my code it keeps spitting errors out. I have a number guessing game between 1 and 50 here. Can't for the life of me figure out what's wrong.
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") )
break
except ValueError:
print("Please input a number.")**
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
Note that you're asking three times for the exact same input. There is really no need for that and no need for two loops at all. Just set the guess to a default value that will never be equal to the number (None) and use one single input, wrapped with try/except:
import random
number = random.randrange(1, 50)
guess = None
while guess != number:
try:
guess = int(input("Guess a number between 1 and 50: "))
except ValueError:
print("Please input a number.")
else:
if guess < number:
print("You need to guess higher. Try again.")
elif guess > number:
print("You need to guess lower. Try again.")
print("You guessed the number correctly!")
You could try running a while loop for the input statements. Checking if the input(in string format) is numeric and then casting it to int.
Sample code:
a = input()
while not a.isnumeric():
a = input('Enter a valid integer')
a = int(a)
The code executes until the value of a is an int
your code did not work because the indentation is not right
import random
number = random.randrange(1, 50)
while True:
try:
guess = int ( input("Guess a number between 1 and 50: ") ) # here
break # here
except ValueError: # here
print("Please input a number.")
while guess != number:
if guess < number:
print ("You need to guess higher. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: ") )
else:
print ("You need to guess lower. Try again.")
guess = int ( input("\nGuess a number between 1 and 50: "))
print ("You guessed the number correctly!")
Output
Guess a number between 1 and 50: aa
Please input a number.
Guess a number between 1 and 50: 4
You need to guess higher. Try again.

how can i loop my simple python code back to top - also filling space here because it will not take my title [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
If value is 1-100 it stops program
If value <1 or >100 i need to print (try again) and loop back to top.
This what i got atm
n1 = 0
n1 = int(input("Enter number between 1-100: "));
print ("your number is: ", n1);
while n1 > 100 or n1 < 0:
print("Try again");
This is now how python works
First of all no need to initiate n1 and then assign input value to it
You should have used if instead of while
while True :
try :
n1 = int(input ())
except :
print ("enter numerical value")
if n1<1 or n1>100 :
print ("try again")
else :
break
Mind indentation
Try this,
while True:
n1 = 0
n1 = int(input("Enter number between 1-100: "));
if n1 < 100 and n1 > 0:
break
else:
continue
and please don't use ; end of your code.

Python: Continue if variable is an 'int' and has length >= 5

I have a piece of code that does some calculations with a user input number. I need a way to check if user entry is an integer and that entered number length is equal or more than 5 digits. If either one of conditions are False, return to entry. Here is what i got so far and its not working:
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "
If anyone has a solution, I'd appreciate it.
Thanks
This would be my solution
while True:
stringset = raw_input("Enter a number: ")
try:
number = int(stringset)
except ValueError:
print("Not a number")
else:
if len(stringset) >= 5:
break
else:
print("Re-enter number")
something like this would work
while True:
number = input('enter your number: ')
if len(number) >= 5 and number.isdigit():
break
else:
print('re-enter number')
Use this instead of your code
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5:
try:
val = int(userInput)
break
except ValueError:
print "Re-enter number:
else:
print "Re-enter number:
Do not use isdigit function if you want negative numbers too.
By default raw_input take string input and input take integer input.In order to get length of input number you can convert the number into string and then get length of it.
while True:
stringset = input("Enter number: ")
if len(str(stringset))>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "

If-Else Statement-Positive and Negative Integers

I am just starting my first computer science class and have a question! Here are the exact questions from my class:
"Write a complete python program that allows the user to input 3 integers and outputs yes if all three of the integers are positive and otherwise outputs no. For example inputs of 1,-1,5. Would output no."
"Write a complete python program that allows the user to input 3 integers and outputs yes if any of three of the integers is positive and otherwise outputs no. For example inputs of 1,-1,5. Would output yes."
I started using the if-else statement(hopefully I am on the right track with that), but I am having issues with my output.
num = int(input("Enter a number: "))
num = int(input("Enter a number: "))
num = int(input("Enter a number: "))
if num > 0:
print("YES")
else:
print("NO")
I have this, but I am not sure where to go with this to get the desired answers. I do not know if I need to add an elif or if I need to tweak something else.
You probably want to create three separate variables like this:
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
num3 = int(input("Enter number 3: "))
In your code you only keep the value of the last number, as you are always writing to the same variable name :)
From here using an if else statement is the correct idea! You should give it a try :) If you get stuck try looking up and and or keywords in python.
On the first 3 lines, you collect a number, but always into the same variable (num). Since you don't look at the value of num in between, the first two collected values are discarded.
You should look into using a loop, e.g. for n in range(3):
for n in range(3):
num = int(input("Enter a number: "))
if num > 0:
print("YES")
else:
print("NO")
Use the properties of the numbers...
num1 = int(input("Enter number 1: "))
num2 = int(input("Enter number 2: "))
num3 = int(input("Enter number 3: "))
Try Something like this
if num1< 0 or num2 <0 or num3 < 0:
print ('no')
elif num1 > 0 or num2 > 0 or num3 > 0:
print ('yes')

How do i have my python program restart to a certain line?

print ("Enter the object you are tyring to find.")
print ("1 = Radius")
print ("2 = Arch Length")
print ("3 = Degree")
print ("4 = Area")
x = int(input("(1,2,3,4):"))
if x == 1:
print ("You are finding the Radius.")
ra = int(input("Enter the arch length: "))
rd = int(input("Enter the degree: "))
rr = ra/math.radians(rd)
print ("The Radius is:",rr)
if x == 2:
print ("You are finding the Arch Length.")
sr = int(input("Enter the radius: "))
sd = int(input("Enter the degree: "))
ss = math.radians(sd)*sr
print ("The Arch Length is:",ss)
I am making a basic math program but i want it to repeat infinitely. This is not the complete code but i want to do the same thing for the rest of the "if" statements. i want it to end after each function is completed and repeat back to the first line. thanks!
Put a
while True:
at the spot you want to restart from; indent all following lines four spaces each.
At every point in which you want to restart from just after the while, add the statement:
continue
properly indented also, of course.
If you also want to offer the user a chance to end the program cleanly (e.g with yet another choice besides the 4 you're now offering), then at that spot have a conditional statement (again properly indented):
if whateverexitcondition:
break
You will need to add a way to let the user quit and break the loop but a while True will loop as long as you want.
while True:
# let user decide if they want to continue or quit
x = input("Pick a number from (1,2,3,4) or enter 'q' to quit:")
if x == "q":
print("Goodbye")
break
x = int(x)
if x == 1:
print ("You are finding the Radius.")
ra = int(input("Enter the arch length: "))
rd = int(input("Enter the degree: "))
rr = ra/math.radians(rd)
print ("The Radius is:",rr)
elif x == 2: # use elif, x cannot be 1 and 2
print ("You are finding the Arch Length.")
sr = int(input("Enter the radius: "))
sd = int(input("Enter the degree: "))
ss = math.radians(sd)*sr
print ("The Arch Length is:",ss)
elif x == 3:
.....
elif x == 4:
.....
If you are going to use a loop you can also verify that the user inputs only valid input using a try/except:
while True:
try:
x = int(input("(1,2,3,4):"))
except ValueError:
print("not a number")
continue

Categories

Resources