Task for invalid number in Python - python

I need to write a program where numbers 100 to 200 and 0 are declared as valid. Everything else is invalid. When you put a invalid number in, it should print invalid but if the number is valid the nothing should print nothing in the terminal.
I wrote something but then when i give 155 as input it still says that it's invalid when it shouldn't print anything. Any ideas how I can fix it?
number = int(input())
if number < 100 or number > 200 or number != 0:
print('invalid')
else:
print()

You need to change number==0 instead of number!=0
number = int(input())
if number == 0 or (number >= 100 and number <= 200):
print()
else:
print('invalid')

try
if number == 0 or (100 < number and number < 200):
#valid
else:
print("invalid")

Related

Reverse number in python - Recursion [duplicate]

I’m trying to create a Python program that can tell you how many digits there are in a number. For example, the input 2345 yields the output 4 digits. I tried making it a while loop but now it prints how many digits are in the number infinitely.
interger = int(input('please type an interger and the programme will tell you how many digits it has!: '))
while interger != 0:
if 0 < interger < 10:
print ('1 digit')
elif 9 < interger < 100:
print('there are 2 digits')
elif 99 < interger < 1000:
print('there are 3 digits')
elif 999 < interger < 10000:
print('there 4 digits')
elif 9999 < interger < 100000:
print('there are 5 digits')
elif 99999 < interger < 1000000:
print ('there are 6 digits')
elif 999999 < interger < 10000000:
print('there are 7 digits')
elif 9999999 < interger < 100000000:
print('there are 8 digits.')
break
elif interger == interger:
print('that is correct')
Your 'while' condition is the cause of the infinite printing, as the value of interger is never changed. If you would like it to simply execute the print once, change
while interger!=0:
to
if interger != 0:
My suggestion for your script:
run = None
while run != 'q':
integer = input("Enter number: ")
print(f'There are {len(integer)} digits')
run = input("Enter q to quit, enter any other key to do another")
If not helpful for you, I will suggest another way.
interger= int(input('please type an interger and the programme will tell you how many digits it has!: '))
dig = 0
while(interger != 0) :
interger /= 10
dig += 1
print("There are " + str(dig) + " digits.")
How about this?
Python code to tell number of digits in an input number and print answer only once
interger = int(input('please type an interger and the programme will tell you how many digits it has!: '))
#to print once
print(f"given input {interger} has {len(str(interger))} digits")
output
please type an interger and the programme will tell you how many digits it has!: 65
given input 65 has 2 digits
Leaving aside the fact that the algorithm is less than ideal, you just don't need a loop.
interger= int(input('please type an interger and the programme will tell you how many digits it has!: '))
if 0<=interger<10: # zero is also 1 digit
print ('1 digit')
elif 9<interger<100:
print('there are 2 digits')
#etc.

I get a syntaxt error when I try to run the program

I get a syntax error on the last else statement. This is supposed to be a grade calculator. If someone enters anything that isn't between 0 and 100, then the program should send a message, and then loop until a valid number is entered. Also I am new to programming, so if there is something else wrong with my code, please let me know!
number = int(input("Enter the numeric grade: "))
if number > 89:
letter = 'A'
elif number > 79:
letter = 'B'
elif number > 69:
letter = 'C'
else:
letter = 'F'
print("The letter grade is", letter)
number = int(input("Enter the numeric grade: "))
if number > 100:
print("Error: grade must be between 100 and O")
elif number < 0:
print("Error: grade must be between 100 and O")
else:
# The code to compute and print the result goes here
number = int(input("Enter the numeric grade: "))
if number > 100 or number < 0:
print("Error: grade must be between 100 and 0")
else:
# The code to compute and print the result goes here
number = int(input("Enter the numeric grade: "))
if number >= 0 and number <= 100:
else:
print("Error: grade must be between 100 and O")
Your issue is at the bottom, where you've got an empty if statement followed by an else statement, as well as incorrect indenting. From your code, I believe you are trying to use not.
I would suggest doing one of two things:
1.
if not (number >= 0 and number <= 100):
2.
if number < 0 or number > 100:
These two pieces of code will both produce the same result.
Also, it seems as though you are repeating the same code several times to try to ensure that the user inputs a number between 0 and 100. If so, this can be achieved with a while loop. I've put an example of this below:
number = int(input("Enter the numeric grade: "))
while number < 0 or number > 100:
print("Error: grade must be between 100 and O")
number = int(input("Enter the numeric grade: "))
In the last line.
if number >= 0 and number <= 100:
else:
print("Error: grade must be between 100 and O")
you didn't write anything after the if statement.
This code will run
if number >= 0 and number <= 100:
print('Write something here')
else:
print("Error: grade must be between 100 and O")
or you can just remove the last if statement its really of no use like try doing something else because there are a lot of if and else statements which don't look nice.
try this:
n = int(input())
first = 0
last = 100
while n < first or n > last:
print(n,'is not a valid input')
n = int(input())
From what I've understood, you're trying loop indefinitely until the user input is between 0 and 100.
My solution would be this:
Define a function that starts by requesting an input from the user.
Use a while loop that will check if the input is 'correct'. In case the input is not correct, the loop will print the error and call back the function again indefinitely till the user's input is between 0 and 100.
if the input is between that range, it will then evaluate the grade and return it.
def yfunc():
n = int(input('Enter the numeric grade: '))
while n < 0 or n > 100:
print("Error: grade must be between 100 and O")
return yfunc()
if n > 89:
letter = 'A'
elif n > 79:
letter = 'B'
elif n > 69:
letter = 'C'
else:
letter = 'F'
return letter
yfunc()
If you have any questions, feel free to ask.

What's wrong with my use of if / then in this script?

I'm learning if and then statements. I'm trying to write code that takes any decimal number input (like 2, 3, or even 5.5) and prints whether the input was even or odd (depending on whether the input is actually an integer.)
I get an error in line 8
#input integer / test if any decimal number is even or odd
inp2 = input("Please enter a number: ")
the_number = str(inp2)
if "." in the_number:
if int(the_number) % 1 == 0
if int(the_number) % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
else:
print("You dum-dum, that's not an integer.")
else:
the_number = int(inp2)
if the_number % 2 == 0:
print("Your number is even.")
else:
print("Your number is odd.")
I'm just starting with python so I appreciate any feedback.
You have to include a colon at the end of second if statement, like you did in your other conditional statements.
if int(the_number) % 1 == 0:
Next time, give a closer look at the error message. It'll give you enough hints to fix it yourself, and that's the best way to learn a language.
EOL.
You forgot a :. Line 8 should read if int(the_number) % 1 == 0:.
Try putting the : at the end of the if statement
if int(the_number) % 1 == 0:
You can test your input as following code snippet
num = input('Enter a number: ')
if num.isnumeric():
print('You have entered {}'.format(num))
num = int(num)
if num%2:
print('{} is odd number'.format(num))
else:
print('{} is even number'.format(num))
else:
print('Input is not integer number')

How do I omit strings and other characters within conditionals in Python 3?

I'm trying to create a small code that asks a user to enter a number between 1 and 100. However my Else statement will not output when entering a string. I want my Else statement to print a message if the user enters an input other than an integer or float. Here is my code.
def between():
print ("Please enter a number between 1 and 100.")
number = eval(input())
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
elif number > 100 or number < 1:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
else:
print ("ERROR! You have entered an invalid value. Please try again using numerical values only.")
between()
between()
The easiest method would be to use try and except
num = input()
try:
number = float(num)
# code to do if num is a number
except ValueError:
print("Not a number!")
# code to do if num isn't a number
If num isn't a number, then converting it to a float would raise ValueError going on to the except.
If num is a number, the coversion of it to a float would run fine, and continue on in the try.
Side note: I highly suggest not using eval(input()) but rather just input(), see this for why you shouldn't use eval. Also eval(input()) won't work with my example above.
Try this:
print "Please enter a number between 1 and 100"
in = input()
try:
num = int(in)
if 1 <= num <= 100:
print("Valid")
else:
print("Out of bounds")
except:
print("Invalid")
Try:
def between():
print ("Please enter a number between 1 and 100.")
number=0
try:
number = int(input())
except:
print ("ERROR! You have entered an invalid value. Please try again using numerical values only.")
exit(1)
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
else:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
between()
Note: why you use eval and input together? I don't think that's right, correct me if I'm wrong
There are a few logical issues with your code. First before using eval() you must be aware of the security risk associated with it. Consider going through this post for some insight. If you entered some arbitrary input in eval, it will most likely be a run time error.
Now, assuming that the variable actually has a value. To check if it is an integer or a float and is in the desired range or something else (possibly a string), you can not directly apply comparison operators with it because if the variable is not a number it will most likely give a TypeError during comparison with other integers.
Hence a correct approach would be to first check if the variable is of desired type by checking if type(r) is int or type(r) is float only then you should apply test for range. If the above type checking is false then you should print your "else" error message.
Try is too slow and should be avoided when not necessary
num = input("Please enter a number between 1 and 100: ")
if num.replace('.','').isdigit():
num = float(num)
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
else:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
else:
print('thats not a number!')

Need tips on writing function in python and return variables

Have the user guess a number but give hints when there wrong as shown below.
number = input('Enter your number here: ')
def guessTheNumber(number):
if number <= 10:
return str('Your number is to small')
else:
if number >= 10:
return str('Your number is to big')
else:
if number == 10:
return str('Your right!')
Need help fixing errors and actually having it output information as for is giving blanks and errors. Thanks.
Your else statements are unnecessary and don't know if you pasted your code wrong, but your spacing is all off. Also, you are returning a string but never printing it so that is why you are never seeing it. You want to put a print before calling your function. The following code works:
def guessTheNumber(number):
if number < 10:
return str('Your number is to small')
if number == 10:
return str('Your right!')
if number > 10:
return str('Your number is to big')
number = input('Enter your number here: ')
print(guessTheNumber(number))
Try these following codes:
number = int(input('Enter your number here: '))
def guessTheNumber(number):
if number <= 10:
return 'Your number is to small'
elif number >= 10:
return 'Your number is to big'
elif number == 10:
return 'Your right!'
print(guessTheNumber(number))
If you want to return some string, you don't need use str() function.
else can't be use like that. For more info
Python need indent right? :)
If you define a function, you should call it like guessTheNumber(number). For more info
Ok, I fixed a few things: Instead of using else: if [xxx,yyy] , try elif instead, as it's a lot less confusing.
And also, the indentation in the example you game was off, which made it all the more difficult to read. Try copying and pasting the code into the question box, then highlighting it, and pressing the {} button.
number = input('Enter your number here: ')
def guessTheNumber(number):
if number <= 10:
return str('Your number is to small')
elif number >= 10:
return str('Your number is to big')
elif number == 10:
return str('You're right!')
print guessTheNumber(number)
you forgot to catch and print the return string. Be very careful about indentation in python
number = input('Enter your number here: ')
def guessTheNumber(number):
if number <= 10:
return str('Your number is to small')
if number >= 10:
return str('Your number is to big')
if number == 10:
return str('Your right!')
str = guessTheNumber(number)
print str
To make your code more "pythonic" the function can be written as:
def guess_the_number(number):
return ('You are right.',
'Your number is too big.',
'Your number is too small.')[cmp(number, 10)]
cmp is a comparisaion function it returns -1, 0 or 1 depeding if the first argument is smaller, equal or bigger than the second.
This value can then be used as an index for the tuple. On 0 and 1 it will return the first or second item (indexes start at 0 not at 1).
Negative indexes are counted from the end backwards, so -1 is the last item. Using this you can just put in the return value for -1 as the last item.
Additionally I corrected your indentation (should be 4 spaces) and the functions name to fit the typical Python coding style.

Categories

Resources