Infinite while loop - python

Why is this while loop not ending when the proper input is entered (a number between 0 and 100)
grade = 110
invalid_input = 1
while grade< 0 or grade> 100:
if invalid_input >=2:
print "This is an invalid entry"
print "Please enter a number between 0 and 100"
grade= raw_input("Please enter your marks for Maths : ")
invalid_input +=1
what ever i put in be it a number or text the (this is an invalid entry , Please enter a number between 0 and 100
does anyone one know what is wrong?

your grade should be cast to an int. Otherwise, since it's a string, the while condition will always remain satisfied.
Also, you can just as easily (and perhaps more cleanly) use a boolean for invalid_input:
invalid_input = True
while invalid_input:
grade = int(raw_input("enter data"))
if grade >= 0 and grade <= 100:
invalid_input = False
else:
print "Please try again"

in grade=raw_input("Please enter your marks for Maths : "), grade is a string, not number. try
grade = int(raw_input("Please enter your marks for Maths : "))
In order to prevent the program from being terminated if the user makes a wrong input, you will need to use a exceptions, like this
grade = 110
invalid_input = 1
while grade< 0 or grade> 100:
if invalid_input >=2:
print "This is an invalid entry"
print "Please enter a number between 0 and 100"
try:
grade= int(raw_input("Please enter your marks for Maths : "))
except ValueError:
grade = -1 # just to enter another iteration
invalid_input +=1

Related

i want to let the user input a number 3 times at most

import random
attempt =0
while attempt <=3:
rand = random.randint(1,18)
age = int(input(“please input your age:”))
if(int(age) == rand):
print(“great”)
elif age< rand:
print (“smaller than the true value”)
elif age > rand):
print (“larger than the true value”)
Generate a random age (1~18), let the user input the age for at most 3 times, if the input is the same as the random number, output 'Great', if it is smaller, output 'Smaller than the true value', if it is larger, output 'Larger than the true value'
my code works but it keep repeating even if it is already more than 3
You have to make sure you increase the value of attempt everytime you get an answer. Also, fix some indentation error:
import random
attempt = 0
while attempt < 3:
rand = random.randint(1,18)
age = int(input("Please enter your age"))
if(int(age) == rand):
print("Great")
elif age< rand:
print ("smaller than the true value")
elif age > rand:
print ("larger than the true value")
attempt += 1
Hope this helps!

How can i Go back to line 1 if condition is false Python

How can i go back to Line 1 if Condition is false.
while True:
food = int(input("food bill: "))
if food <= 10:
print("please write more than 10")
#If i put break statement here it does not go forward
else:
carbill = int(input("carbill: "))
print("Total Montlhy expenditure is : " , grandtotal)
This is what you want-
while True:
food = int(input("food bill: "))
if food <= 10:
print("please write more than 10")
continue
carbill = int(input("carbill: "))
print("Total Montlhy expenditure is : " , food+carbill)
Use continue, it will go back to the loop instruction (works for for well).

Issue with validation function

I've created a program requiring a validation component to make sure score numbers entered are between 1 and 10, and this function will be used later on to append a list. So far I've written this:
def validation(goodNum,score):
goodNum = False
while goodNum == False:
score = raw_input("Please enter a valid score between 1 and 10 ")
try:
score = int(score)
except:
score = raw_input("Please enter a valid score between 1 and 10 ")
if score > 1 and score < 11:
goodNum == True
else:
print "Invalid input"
return score
When I run the program it continuously loops, constantly asking me to input the score as if the false variable isn't turning to true, when it should stop after validating the score. How should I go about correcting this problem?
You are not actually changing the value of goodNum:
goodNum == True
just compares goodNum to True. What you meant was:
goodNum = True
However there are other issues: When you enter a wrong score the first time that cannot be converted to an int, you come into your except block and ask for input again. At that point the result of raw_input is not turned into an int, so the following if will not work. I would suggest you change your logic to:
def validation(goodNum,score):
goodNum = False
while goodNum == False:
score = raw_input("Please enter a valid score between 1 and 10 ")
try:
score = int(score)
except:
print "Invalid input could not convert to integer"
continue # Just start over
if score > 1 and score < 11:
goodNum = True
else:
print "Invalid input, score must be between 1 and 10"
return score
Note: I don't know what your setup or experience level is, but I would recommend for you to use an IDE that automatically recognizes statements like this (statements with no effect) and let you easily debug your script by placing break points

How to use two != breaks in program in Python?

The problem statement, all variables and given/known data
I need a program, which would break and show results once a 0 is entered in input name and input grade.
I figured how to do that in name, but how do I add another break? Like grade !="0"?
The program I have so far:
students = []
grades = []
while True:
name = input ("Enter a name: ")
if name.isalpha() == True and name != "0":
while True:
grade = input("Enter a grade: ")
if grade.isdigit()== True:
grade = int(grade)
if grade >= 1 and grade <= 10:
if name in students:
index = students.index(name)
grades[index].append(grade)
break
else:
students.append(name)
grades.append([grade])
break
else:
print("Grade is not valid. Try to enter it again!")
elif name == "0":
print("A zero is entered!")
break
else:
print ("Grade is not valid. Try to enter it again!")
for i in range(0,len(students)):
print("NAME: ", students[i])
print("GRADES: ", grades[i])
print("AVERAGE: ", round(sum(grades[i])/len(grades[i]),1), "\n")
Also is there any way that I can make Python ignore spaces in input function?
Example: I enter a grade that has "________8" in it (_ are spaces) and the program does not want to ignore it, how do I make it ignore the spaces and just accept the number as it is?
strip() method
Use strip() method of string to strip the white spaces.
Demo:
>>> a = " Go "
>>> a.strip()
'Go'
>>> a.rstrip()
' Go'
>>> a.lstrip()
'Go '
>>>
Your code will work fine. Produce correct output.
Use dictionary to save Student records.
Demo:
import collections
student_record = collections.defaultdict(list)
while True:
name = raw_input("Enter a name: ").strip()
if name=="0":
print "A zero is entered!"
break
if not name.isalpha():
print "Name is no valid. Try again. Enter alpha value only."
continue
while True:
grade = raw_input("Enter a grade: ").strip()
if grade.isdigit():
grade = int(grade)
if 1<=grade <= 10:
student_record[name].append(grade)
break
else:
print "Grade is not valid. Try again. Enter digit values between 1 and 10."
else:
print "Grade is not valid. Try again. Enter digit values."
for i, j in student_record.items():
print "\nNAME: ", i
print "GRADES: ", j
print "AVERAGE: ", round(sum(j)/len(j),1)
Output:
$ python test1.py
Enter a name: ABC
Enter a grade: 2
Enter a name: XYZ
Enter a grade: 5
Enter a name: ABC
Enter a grade: 6
Enter a name: 0
A zero is entered!
NAME: XYZ
GRADES: [5]
AVERAGE: 5.0
NAME: ABC
GRADES: [2, 6]
AVERAGE: 4.0
Note:
Use raw_input() for Python 2.x
Use input() for Python 3.x

Limiting the amount of numbers in a user input

I'm making a 4 digit password guesser in python 3. I want to make sure that you can only put in 4 digit passwords and not 5 or 6 digit passwords. Here is the code I have so far.
print('your password will not be used or saved for later use you do not have to put in your real password')
real_password = int(input("please enter your four digit phone password here:"))
computer_guess = 0000
guess_counter = 0
yes = 'yes'
no = 'no'
print ("guessing your password...")
while computer_guess < real_password:
computer_guess = computer_guess + 1
guess_counter = guess_counter + 1
print("guess number", guess_counter)
print ("your password is", computer_guess)
Before you cast the input to an int, cast it to a str instead, then you can call the len() builtin method to check the length of the entered string. Check the documentation for details on this method. If it is greater than 4, then you should recall your input call. Something like the following should work:
>>> real_password = input("please enter your four digit phone password here: ")
please enter your four digit phone password here: 1234
>>> while len(str(real_password)) != 4:
... real_password = input("please enter your four digit phone password here: ")
In this condition the loop would not be ran, however if the entered string was not equal to 4, the loop would run until that condition was satisfied.
print('your password will not be used or saved for later use you do not have to put in your real password')
def get_password():
real_password = int(input("please enter your four digit phone password here:"))
if len(str(real_password)) != 4: # condition is not met if your variable
get_password() # is not 4, easily changed if you
else: # want
return real_password
#define a method and ask it to call itself until a condition is met
#
real_password = get_password() # here the method is called and the return
computer_guess = 0 # value is saved as 'real_password'
guess_counter = 0
yes = 'yes' # these are not used in your code
no = 'no' # but I'm am sure you knew that
print ("guessing your password...")
while computer_guess != real_password: # your loop should break when the
computer_guess += 1 # is found, not some other implied
guess_counter += 1 # the '+=' operator is handy
print("guess number", guess_counter)
print ("your password is", str(computer_guess)) # explicitly define the int
# as a string
I hope that helped...

Categories