This question already has answers here:
Find maximum int value from list which contain both str and int python
(5 answers)
Python maximum and minimum
(2 answers)
Closed 3 years ago.
The code below is to find the largest and smallest numbers for the sequential input of [7, 2, bob, 10, 4] and after the inputs, I type 'done' and the loop is done and prints the max, min numbers. I checked whether this code actually works but what really bothers me is that the basic setting of this quiz started for the largest and smallest from None. But if I start the variables from none, somehow it returns invalid input, I guess there are problems somewhere in the try box.
How can I modify this code to use None at first?
largest = 0
smallest = 9999
while True:
num = input("Enter a number: ")
try:
fnum=float(num)
if fnum>largest :
largest=fnum
continue
if fnum<smallest :
smallest=fnum
continue
except :
if num == "done" : break
else :
print('invalid input')
continue
print("Maximum is", largest)
print("Minimum is", smallest)
Related
This question already has answers here:
Check if a number is odd or even in Python [duplicate]
(6 answers)
Closed 1 year ago.
number = int(input("Type your number to check even or odd :"))
for number in range (1,100):
if(number%2) == 0:
print("This is even number")
elif number > 100:
print("Enter the valid number from 1 to 100")
else:
print("This is ODD number")
i am a beginner in python language , I have written code to read the number as EVEN or ODD in for loop condition between (1,100). correct me if making any mistakes in my code .
Why are you using for loop, just check the condition like if number > 100;the number is invalid.Check this example
nos=int(input())
if(nos>100):
print("Enter the valid number from 1 to 100 ")
else:
if(nos % 2 ==0):
print("Number is Even")
else:
print("Number is Odd")
There are mistakes in your code.
1.Indentation error at the 2nd line.(Remove whitespace before for loop.)
2.The name of the input variable and the iterator name in for loop is same. So your intended logic would run on the numbers from 1 ,2, 3 ..... 99. It never runs on the user entered value. So change the name of any variable. Both cant be 'number'.
3.Although you change the name of the variable, you initialised for loop with 100 iterations so you see output 100 times.
so if you want to check the numbers between given range which are even or odd you can try this..
num = int(input(" Please Enter the Maximum Number : "))
for number in range(1, num+1):
if(number % 2 == 0):
print("{0} is Even".format(number))
print("{0} is Odd".format(number))
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I am creating code for a simple teachers grading system in which you input the numeric grade and it tells you if it is an A, B, C, etc.
I first wanted to put a limit on the numbers you can input, i.e. can't put less than zero or more than one hundred, but it is not working. Can anyone explain why?
import time
from time import sleep
grade = 0
maximum = 100
minimum = 0
grade = input("""Insert numeric grade:
""")
time.sleep(1)
if grade > maximum:
print ("Please enter a valid grade.")
Basically you should fix this line:
if int(grade) > maximum:
because the result of input is a string, not a number, so the wrong comparison is used.
Of course, you could (and should!) also properly check that user has entered an integer value, otherwise there will be a ValueError.
try:
if int(grade) > maximum:
print("enter a value less than maximum")
except ValueError:
print("enter an integer value")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am trying to make my program print(invalid input, try again) if the user types a string instead of an integer.
num_dice = 0
while True:
if num_dice < 3 or num_dice > 5 or num_dice:
num_dice = int(input("Enter the number of dice you would like to play with 3-5 : "))
print("")
print("Please enter a value between 3 and 5.")
print("")
continue
else:
break
You can simply use the isnumeric keyword to check if it is an absolute number or not.
Example:
string1="123"
string2="hd124*"
string3="helloworld"
if string1.isnumeric() is True:
#Proceed with your case.
inputs=string1
Documentation reference : https://www.w3schools.com/python/ref_string_isnumeric.asp
P.S. this will require you changing your input to string format, as isnumeric validates only string.
This below part I mean.
num_dice = str(input("Enter the number of dice you would like to play with 3-5 : "))
This question already has answers here:
Two values from one input in python? [duplicate]
(19 answers)
Closed 2 years ago.
I want to use one line to get multiple inputs, and if the user only gives one input, the algorithm would decide whether the input is a negative number. If it is, then the algorithm stops. Otherwise, the algorithm loops to get a correct input.
My code:
integer, string = input("Enter an integer and a word: ")
When I try the code, Python returns
ValueError: not enough values to unpack (expected 2, got 1)
I tried "try" and "except", but I couldn't get the "integer" input. How can I fix that?
In order to get two inputs at a time, you can use split(). Just like the following example :
x = 0
while int(x)>= 0 :
try :
x, y = input("Enter a two value: ").split()
except ValueError:
print("You missed one")
print("This is x : ", x)
print("This is y : ", y)
I believe the implementation below does what you want.
The program exits only if the user provides a single input which is a negative number of if the user provides one integer followed by a non-numeric string.
userinput = []
while True:
userinput = input("Enter an integer and a word: ").split()
# exit the program if the only input is a negative number
if len(userinput) == 1:
try:
if int(userinput[0]) < 0:
break
except:
pass
# exit the program if a correct input was provided (integer followed by a non-numeric string)
elif len(userinput) == 2:
if userinput[0].isnumeric() and (not userinput[1].isnumeric()):
break
Demo: https://repl.it/#glhr/55341028
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
smallest = None
largest = None
while True :
number = raw_input('Enter a number from -10 to 9: ')
if largest < number :
largest = number
if smallest is None :
smallest = number
elif number < smallest :
smallest = number
if number == 'done': break
print 'Largest number is: ',largest
print 'Smallest number is ',smallest
I have no idea why my "smallest" is alright while "largest" outcome is always done. I think that "break" is somehow affecting it. Could You point out my mistake?
The problem is that you are first updating smallest and largest even if the user entered done. So first of all, you should check whether the input is 'done' and abort immediately before updating any of your numbers.
That being said, there are multiple other issues with your code:
if largest < number – You are updating largest if the number is smaller than the previously stored one, making it have the same logic as smallest. Of course, you will not end up with the largest number that way.
raw_input() returns a string, not a number. So if the user types for example 5, then what raw_input() returns is the string '5'. So every comparison you make is a string comparison (e.g. '2' < '5'). Because string comparisons are based on character codes, this will incidentally work for single-digit numbers but you should really convert the strings into proper numbers first.
You mention an allowed range of -10 to 9 but you never actually enforce that.
Something like this will work:
smallest = None
largest = None
while True:
number = raw_input('Enter a number from -10 to 9: ')
if number == 'done':
break
# convert into a number
try:
num = int(number)
except ValueError:
print('That was not a valid number')
continue # restart the loop
# validate the number range
if num < -10 or num > 9:
print('The number is out of the allowed range')
continue
if largest is None or num > largest:
largest = num
if smallest is None or num < smallest:
smallest = num
print 'Largest number is:', largest
print 'Smallest number is:', smallest
If you encounter done, your loop should break immediately. But in your codes, you have put the break at the end. So before that, previous logic is being executed. And done as a string can be compared.
>>> None < 'done'
True
>>>
So your largest is set to done since largest < None in that case.
Quick Fix
We now moved the break on top, so this should fix the issue:
smallest = None
largest = None
while True :
number = raw_input('Enter a number from -10 to 9: ')
if number == 'done':
break
if largest < number :
largest = number
if smallest is None :
smallest = number
elif number < smallest :
smallest = number
print 'Largest number is: ',largest
print 'Smallest number is ',smallest
Handling Numbers
The raw_input returns string. But we want to compare numbers. So we should convert the inputs to int.
try:
num = int(number)
except ValueError:
print('Please enter a valid integer')
continue # skip the input and continue with the loop