I want the print statement to print the number in the range between the low and upper.
I keep getting the error code:
Traceback (most recent call last):File "python", line 5, in <module> ValueError: non-integer arg 1 for randrange()
From the program:
from random import*
lowRange = input('What is the lower range number?')
hiRange = input('What is the higher range nunmber?')
ran = randrange (lowRange,hiRange)
print (ran)
The input() function always returns a string. If you want to use integers, as in this case, you have to convert those strings to integers using int(). However, if the user enters something that cannot be converted to an integer (e.g. 'hi', or just hitting return), you will get an error when trying to convert. To deal with that, you will want to look into try and except statements. Hope that helps!
Try this:
In here until you enter a number it wouldn't stop. Inputs other than int will take as an invalid input.
What's wrong in your code is everything reads from input is taken as a string.
from random import*
while True:
try:
lowRange = int(input('What is the lower range number?'))
break
except:
print("That's not a valid input!")
while True:
try:
hiRange = int(input('What is the higher range nunmber?'))
break
except:
print("That's not a valid input!")
ran = randrange (lowRange,hiRange)
print (ran)
Related
I am very new to python and programming as a whole. I recently took up a python beginners course and got an assignment that I am having difficulties with, the assignment will be posted below.
"Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below."
I am currently trying to convert a string input to an int so I can compare it with a none type, when I do this I get a name error. Both the code and the error will be posted below
I am aware that there is a multitude of issues in this code and if you spot something feel free to let me know. Here is my code, please go easy on me.
Code:
Largest = None
smallest = None
while True:
try:
Numbers = int(input("Enter A number: "))
if Numbers == ('done'):
break
except:
print ('invalid number')
for Numbers in [Numbers]:
if Largest is None:
Largest = Numbers
elif Numbers > Largest:
Largest = Numbers
if smallest is None:
smallest = Numbers
elif Numbers < smallest:
smallest = Numbers
print (Largest)
print (smallest)
Error:
C:\Users\Noah\Desktop\py4e>throw_away.py
Enter A number: f
invalid number
Traceback (most recent call last):
File "C:\Users\Noah\Desktop\py4e\throw_away.py", line 10, in <module>
for Numbers in [Numbers]:
NameError: name 'Numbers' is not defined
This happens because, when you have an error, you go into your except clause, but you then move right on into processing your numbers. Because there was an error, the Numbers variable was not created.
You need a continue in your except clause.
By the way, for Numbers in [Numbers]: is wrong in several ways. First, you should not have the loop variable be the same as the thing you are iterating. Next, Numbers is not a list -- it's a single number. So, you don't need a for loop at all. Just delete that line.
You need to rewrite your script to make it work:
# In order to keep track of all numbers typed by the user,
# we will use this list. It needs to be allocated just once
# before the main loop begins.
Numbers = []
# Start the main loop
while True:
try:
# Ask for the user input
num = input("Enter A number: ")
# Before converting it to an integer, check if the input
# is the string 'done'
if num == ('done'):
# If it is, break the loop.
break
# Otherwise, try to convert it to a number
else:
num = int(num)
# In any case, if int(num) fails, this exception will be
# catched and this block will execute instead
except:
print ('invalid number')
# If no exceptions were raised, then it means everything is
# normal.
#
# Append the user input converted to a number to the list.
else:
Numbers.append(num)
# When outside of the loop, check if the list is empty.
if (len(Numbers) == 0):
print('No numbers were recorded. List is empty.')
# If its not empty, find the minimum and maximum number, and
# print them on the screen.
else:
print ('MAX: ', max(Numbers))
print ('MIN: ', min(Numbers))
NOTE: There are other ways to write this script and get the same output. This is one of many ways to solve your problem. There are ways to make this script even faster by taking out the min and max functions and using the smallest and Largest variables from your script. That's an exercise for you if you're curious about it.
I have to create a fortune teller for school. I want the user to input a number between 1-9. But i also want to give an error message if they put in a different number. I'm using a set containing my numbers, but I can't call it in my if statements.
fortune_num = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
user_num = input(f'Pick a number and find your fortune! Choose a number from 1 to 9 and hit enter: ')
print()
if user_num == fortune_num:
print(user_num)
else:
print('Error')
Use the keyword in to check set membership, also cast input into int:
fortune_num = set([1, 2, 3, 4, 5, 6, 7, 8, 9])
user_num = input(f'Pick a number and find your fortune!
\nChoose a number from 1 to 9 and hit enter: ')
print()
if int(user_num) in fortune_num: #this would throw an error if input is not int
print(user_num)
else:
print('Error')
You can use this code,
fortune_num = list(range(1,10))
user_num = input(f'Pick a number and find your fortune!\nChoose a number from 1 to 9 and hit enter: ')
if int(user_num) in fortune_num:
print(user_num)
else:
raise ValueError("You entered a wrong input!")
This would raise an actual Python error if the input is wrong.
If you want to give the user another chances to enter a correct input use this,
fortune_num = list(range(1,10))
while True:
try:
user_num = int(input(f'Pick a number and find your fortune!\nChoose a number from 1 to 9 and hit enter: '))
if user_num in fortune_num:
print(user_num)
break
else:
raise ValueError
except:
print("\nYou entered a wrong input. Please enter a valid number!")
Change the code as per your needs but this would do work as the perfect foundation.
First of all, input takes user input as a string. So even if they enter 1, that won't match your set, because your set is of int, and their input is the string '1', not the integer 1. Also, there's no need to use a set. A range object is easier to generate, and since it contains multiple numbers, the variable name should be plural. You also don't have your indentation correct. I don't see what the f in the input function is doing, and if you want a multi-line string, you need triple quotes. Also, if you have a carriage return in your string, putting \n in the string gives you two line breaks; I'm not sure that's intended. So one way of doing this is:
fortune_nums = [str(num) for num in range(1,10)]
user_num = input('''Pick a number and find your fortune!
Choose a number from 1 to 9 and hit enter: \n''')
print()
if user_num in fortune_nums:
print(user_num)
else:
print('Error')
If you want to get fancier, you can keep your fortune_nums as int, then do a try-except on converting the input to int, catching the invalid literal error:
fortune_nums = range(1,10)
user_num = input('''Pick a number and find your fortune!
Choose a number from 1 to 9 and hit enter: \n''')
print()
try:
if(int(user_num) in fortune_nums):
print(user_num)
except ValueError:
print("That's not a valid integer!")
if user_num == fortune_num: // instead of this; you can use keyword in int(user_num) in fortune_num:,
Also your print statement must be indented, otherwise you might get indentation error.
In the second line, I am trying to make it not crash if a string is entered but can't find a way to use an exception or something similar. In the while loop it works normally as the exception deals with this case.
number = 0 #this to be removed
number = (float(input('pick a number'))) #I want to make this not crash if a string is entered.
while number not in [100, 200, 3232]:
try:
print('wrong number ')
number = (float(input('pick a number;'))) #Here it does not crash if a string is entered which is fine
except ValueError:
print("retry")
while followed by a variable condition often ends up with bugs/repeating code => bad maintenability.
Use a while True condition to avoid repeating your code, then break out the loop when it's valid.
while True:
try:
number = float(input('pick a number;'))
if number in [100, 200, 3232]:
break
print("wrong number")
except ValueError:
print("illegal number, retry")
note: be careful with float equality in the general case (see also strange output in comparison of float with float literal, Is floating point math broken?)
Maybe create a function to take input:
def get_input():
while True:
a = input("Pick a number: ")
try:
return float(a)
except:
pass
I was writing a code to get a student grade point average but I got an error.
here is the piece of my code getting error :
scoreinput=input("Score lesson: ")
while True:
if scoreinput.isnumeric():
scoreinput=int(scoreinput)
if scoreinput > 20:
scoreinput = int(input("This number is too big. Try again: "))
elif scoreinput < 0:
scoreinput = int(input("This number is too low. Try again: "))
else:
print("please write number correctly...")
This is the output of this code which has got an error :
Score lesson: 5
Traceback (most recent call last):
File "e:\TEST PYTHON\test3.py", line 3, in <module>
if scoreinput.isnumeric():
AttributeError: 'int' object has no attribute 'isnumeric
please help me. thanks
If the input is a positive number below 20, which is what you want to have, after scoreinput=int(scoreinput)
you have the number, but instead of doing something, you continue to the next iteration of the while loop. On the next iteration, scoreinput is an int and not str this is why you get an error. If scoreinput is in the correct range, you should use break to stop the loop.
Another problem occurs when the input is wrong. If the input is not a number, you are not getting a new input and will be stuck in an infinite loop. If the input is a number, but not between 0 to 20, you get new input and imminently cast it to int. If the input is not a number you will get an exception. If it is a number, it will fail as soon as you reach the next iteration since scoreinput should be str at the beginning of the iteration, but it will be int.
I would suggest you will use the following code:
while True:
scoreinput=input("Score lesson: ") # using input only one time at the beggining of the loop instead of input command for each case of bad input
if scoreinput.isnumeric():
scoreinput=int(scoreinput)
if scoreinput > 20:
print("This number is too big. Try again.")
elif scoreinput < 0:
print("This number is too low. Try again.")
else:
break # input is valid
else:
print("please write number correctly...")
If you write on the top: scoreinput = int(input('Score lesson: ')) you won't have to verify if scoreinput is numeric or alphabetic.
in part of one program i wanted to ensure that user inputs only
so i used:
num=int(raw_input())
while type(num)!= int:
num=int(raw_input('You must enter number only'))
print num
But by doing this , if the user inputted some non-integer like strings or anything else the whole code is displayed error.
so how can i make user re-enter the value until they input an integer.
the output was like:
input your number
hdhe
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-2-4b5e9a275ca4> in <module>()
1 print'input your number'
----> 2 num=int(raw_input())
3 while type(num)!= int:
4 num=int(raw_input('You must enter number only'))
5 print num
ValueError: invalid literal for int() with base 10: 'hdhe'
while True:
try:
n = int(input('input your number : '))
break
except ValueError:
print('You entered a non integer value, try again.')
continue
print('yay!! you gave the correct value as int')
Now you can do any cosmetic changes as you please.
Happy coding.
Your num = int(raw_input()) has already ensured it must be an int and would raise ValueError if not int. So your while loop never gets to execute because it'll never get a non-int variable for num. Instead remove int() from the num variable and your good to go!
You can use isinstance to check whether the input is intor not.
if input is not int loop until the user enters int.
For instance:
num = input("Enter an integer:")
if not isinstance(num, int):
while not isinstance(num, int):
try:
num = int(input('You must enter integer only'))
except ValueError as ve:
pass
Out:
Enter an integer:e
You must enter integer onlyr
You must enter integer onlye
You must enter integer only4
Process finished with exit code 0
You cast the input from the user directly to int on line 2. If this is not an integer a ValueError exception is thrown. We can modify your implementation and catch the exception when this happens, only exiting the loop when no exception occurs and num is an integer.
while True:
num=raw_input()
try:
num=int(num)
break
except ValueError:
print "Input is not an integer!"
print num
You might also be able to use a regular expression to check if the input value is an integer, or some other library function that checks whether the string from raw_input() is an integer.