what I want is to validate user input in python 3.9 under these conditions:
1-No numbers bigger than 100 allowed.
2-No strings allowed.
3-No floats allowed.
The code seems to work well only with string detection.
Thanks in advance.
import random
name = input("Type in your name, sir.\n")
print("Hi", name, "!")
print(
"\n\n\n##This is a guessing game, where you guess a number that is between zero and the top number that you choose.##")
print("\n\nEnter a top number, and don't exaggerate babe.")
n = input()
verifier = 5
while True:
try:
verifier = int(n)
except ValueError or int(n) > 100:
print("Nope, neither floats nor strings are allowed buddy...Also don't pick a big'ol num like a 100.")
n = input()
continue
Your max check isn't working since int(n) > 100 only runs if it wasn't able to convert the string into an integer.
Move the condition after verifier = int(n) and it should work.
Your code should look something like this:
while True:
try:
verifier = int(n)
if int(n) > 100:
raise ValueError() # Brings us to the except statement
break
except ValueError:
print("Nope, neither floats nor strings are allowed buddy...Also don't pick a big'ol num like a 100.")
n = input()
continue
By the way, you can probably just remove the verifier = int(n) line, assuming you don't use it for anything else.
Related
I want to take input of how many inputs the user is going to give next and collect those inputs in a single line. For eg. if user enters '3' next he has to give 3 inputs like '4' '5' '6' on the same line.
N = int(input())
result = 0
randomlist = []
for number in range(N):
K = int(input())
for number2 in range(K):
a = int(input())
if number2 != K - 1:#Ignore these on below
result += a - 1
else:
result += a
randomlist.append(result)
result = 0
break
for num in range(N):
b = randomlist[num]
print(b)
Now I want the input for K and a (also looped inputs of a) to be on the same line. I have enclosed the whole code for the program here. Please give me a solution on how to get input in the same line with a space in between instead of hitting enter and giving inputs
Based on what I read from your question, you are trying to request input from the user and the desired format of the input is a series of numbers (both integers and floats) separated by spaces.
I see a couple of ways to accomplish this:
Use a single input statement to request the series of numbers including the count,
Just ask the user for a list of numbers separated by spaces and infer the count.
To perform these operations you can do one of the following:
#Request User to provide a count followed by the numbers
def getInputwithCount():
# Return a list Numbers entered by User
while True:
resp = input("Enter a count followed by a series of numbers: ").split(' ')
if len(resp) != int(resp[0]) + 1:
print("Your Input is incorrect, try again")
else:
break
rslt = []
for v in resp[1:]:
try:
rslt.append(int(v))
except:
rslt.append(float(v))
return rslt
or for the simpler solution just ask for the numbers as follows:
def getInput():
# Return the list of numbers entered by the user
resp = input("Enter a series of numbers: ").split(' ')
rslt = []
for v in resp:
try:
rslt.append(int(v))
except:
rslt.append(float(v))
return rslt
I am trying to create a function that would take a user inputted number and determine if the number is an integer or a floating-point depending on what the mode is set to. I am very new to python and learning the language and I am getting an invalid syntax error and I don't know what to do. So far I am making the integer tester first. Here is the code:
def getNumber(IntF, FloatA, Msg, rsp):
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
Rsp = int(input("What number would like to test as an interger?"))
A = rsp
if rsp == "A":
while True:
try:
userInput = int(input("What number would like to test as an interger"))
except ValueError as ve:
print("Not an integer! Try again.")
continue
else:
return userInput
break
The problem with the code you shared is :
The syntax error you mentioned is probably because the except clause has to be at the same indentation level as try, and same for if and else of the same if/else clause. All the code in the function should be indented 1 level too. Python requires all this to identify blocks of code.
You don't need to give 4 arguments to the getNumber() function if you're not using them. This isn't really a problem, but you'll have to pass it some 4 values each time you call it (for example getNumber(1,2,3,4) etc...) to avoid missing argument errors; and these won't matter because you're not doing anything with the given values inside the function - so it's a little wasted effort. I rewrote it in the example below so that you aren't dealing with more variables than you need - it makes the code clearer/simpler.
You also don't need break after a return statement because the return will exit the enitre function block, including the loop.
Try this and see if it makes sense - I've changed a lot of the code :
def getNumber():
while True:
try:
userInput = int(input("What number would like to test as an integer ? "))
return userInput
except ValueError as ve:
print("Not an integer! Try again.")
continue
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
chosen_option = input()
if chosen_option == 'A':
integer_received = getNumber()
print(integer_received, "was an int !")
else:
print("You did not choose 'A' or 'B'")
To determine whether a number is a float or integer, you can use this approach
float is nothing but the integer with floating-point(.).
to determine this we first need to convert it to string and find does it contain a point or not.
number = input("Enter a numbeer\n")
if number.find(".") == -1:
# find will return -1 when the value is not in string
print("it is integer")
else:
print("it is float")
while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
I've had a hard time understanding exactley what u want to do with this code, please use a proper code block next time, with proper indentation. My guess is that u want to get a input number like 345 and add 3+4+5 as a output. If the input is not a int it should break the loop. Ive come up with 2 diffrent solutions, depending on what you need.
This code will simply take the input and check if it is "done", if it is not "done" it will try to add. This is a easy to understand solution but it will produce a error if the input is any diffrent string than "done".
while True:
numbers = input(">")
if numbers == "done":
break
else:
total = 0
for number in numbers:
total += int(number)
print(total)
This approach will test for the "done" string again, but afterwards will also check if the input can be converted into a int. if not the error is captured and it will return "invalid input". If u want the programm to terminate at any string u can just put break in the except section.
while True:
numbers = input(">")
if numbers == "done":
break
else:
try:
testing = int(numbers)
total = 0
for number in numbers:
total += int(number)
except:
total = "invalid input"
print(total)
im a Beginner myself and if a experiencend person can show me a better way to do this i would be very interested
while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
Assuming this as your code:
Here's a solution to your problem-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
total=0
for number in numbers:
total = total + int(number)
print(total)
By default everything gets accepted as string so we convert it to integer to find total.
Also we use list to store all the values we accept.
Another Solution is-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
p=map(int,numbers)
print(sum(p))
Hope you understand the solution :-)
total = 0
average = 0
count = 0
while True:
numbers = input('> ')
if numbers == 'done': break
try:
total = int(numbers) + total
count = count + 1
except:
print('nope')
try:
average = total / count
except:
print('error')
print(total)
print(average)
print(count)
Try this:
total = 0
number_of_inputs = 0
while True:
number_string = input('Enter a number: ')
try:
total += float(number_string)
number_of_inputs += 1
except ValueError:
break # we weren't given a number, so exit the loop
# Now that we're outside of the loop, print out the total:
print('The total is:', total)
if number_of_inputs > 0:
average = total / number_of_inputs
print('The average is:', average)
else:
print('The average cannot be calculated, as no inputs were given.')
Do you see what's happening? The while loop keeps ask for and adding integers to total until a non-integer (like "done") is given. Once it gets that non-integer, the int() function will fail, and the exception it throws will get caught, and the code will immediately break out of the while loop.
And once out of the loop, the total and the average are printed out.
A few things you should be aware of:
If the user gave no inputs (which is possible here), the total will correctly print out as 0, but if you try to calculate the average, you will error, due to diving by number_of_inputs (which is also 0). That is why I check that number_of_inputs is greater than zero before I even attempt to calculate the average.
Originally I used int() to convert the string to a number, but I changed it to use float() instead. I figure that since you want to calculate an average, averages are not necessarily integers (even if all the inputs are), so there's no point in enforcing integer input. That is why I changed the int() to float(), but whether or not you want to use it is up to you.
ValueError isn't a function; it's an Exception. At this point you probably don't know what Exceptions are, so just know that they are special cases that can happen, and they're often used for catching errors, such as bad input values.
In the code I posted above, the loop is always expecting numerical input. But as soon as we have input that can't be converted to a number, the program then says, "Hey, I have an exception to what we're expecting! The exception is that there's an error in the value!" Then the program, instead of continuing to the next line of code (which is number_of_inputs += 1) will then execute the block of code under the except ValueError: section. And in the code above, all it does is call break, which exits the loop.
Once out of the loop, the code prints out the total and the average.
If it weren't for the try: and except ValueError: lines in the code, then the program would abruptly end (with a lengthy error message) once someone gave a non-numerical input. That happens because the call to float() wouldn't know how to convert a value like "done" to a number, so it does nothing more than just quitting.
However, by using try: and except ValueError:, we are anticipating that someone might give non-numerical input. When that happens (which it will, when the user is finished giving inputs) -- instead of quitting -- we want an alternate action to take. And we specify that alternate action to be a simple break out of the loop -- which will allow the program to continue with whatever is after the loop.
I hope this makes sense. If it doesn't, it will make more sense once you start learning about Exceptions in Python.
Apologies if similar questions have been asked but I wasn't able to find anything to fix my issue. I've written a simple piece of code for the Collatz Sequence in Python which seems to work fine for even numbers but gets stuck in an infinite loop when an odd number is enter.
I've not been able to figure out why this is or a way of breaking out of this loop so any help would be greatly appreciate.
print ('Enter a positive integer')
number = (int(input()))
def collatz(number):
while number !=1:
if number % 2 == 0:
number = number/2
print (number)
collatz(number)
elif number % 2 == 1:
number = 3*number+1
print (number)
collatz(number)
collatz(number)
Your function lacks any return statements, so by default it returns None. You might possibly wish to define the function so it returns how many steps away from 1 the input number is. You might even choose to cache such results.
You seem to want to make a recursive call, yet you also use a while loop. Pick one or the other.
When recursing, you don't have to reassign a variable, you could choose to put the expression into the call, like this:
if number % 2 == 0:
collatz(number / 2)
elif ...
This brings us the crux of the matter. In the course of recursing, you have created many stack frames, each having its own private variable named number and containing distinct values. You are confusing yourself by changing number in the current stack frame, and copying it to the next level frame when you make a recursive call. In the even case this works out for your termination clause, but not in the odd case. You would have been better off with just a while loop and no recursion at all.
You may find that http://pythontutor.com/ helps you understand what is happening.
A power-of-two input will terminate, but you'll see it takes pretty long to pop those extra frames from the stack.
I have simplified the code required to find how many steps it takes for a number to get to zero following the Collatz Conjecture Theory.
def collatz():
steps = 0
sample = int(input('Enter number: '))
y = sample
while sample != 1:
if sample % 2 == 0:
sample = sample // 2
steps += 1
else:
sample = (sample*3)+1
steps += 1
print('\n')
print('Took '+ str(steps)+' steps to get '+ str(y)+' down to 1.')
collatz()
Hope this helps!
Hereafter is my code snippet and it worked perfectly
#!/usr/bin/python
def collatz(i):
if i % 2 == 0:
n = i // 2
print n
if n != 1:
collatz(n)
elif i % 2 == 1:
n = 3 * i + 1
print n
if n != 1:
collatz(n)
try:
i = int(raw_input("Enter number:\n"))
collatz(i)
except ValueError:
print "Error: You Must enter integer"
Here is my interpretation of the assignment, this handles negative numbers and repeated non-integer inputs use cases as well. Without nesting your code in a while True loop, the code will fail on repeated non-integer use-cases.
def collatz(number):
if number % 2 == 0:
print(number // 2)
return(number // 2)
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return(result)
# Program starts here.
while True:
try:
# Ask for input
n = input('Please enter a number: ')
# If number is negative or 0, asks for positive and starts over.
if int(n) < 1:
print('Please enter a positive INTEGER!')
continue
#If number is applicable, goes through collatz function.
while n != 1:
n = collatz(int(n))
# If input is a non-integer, asks for a valid integer and starts over.
except ValueError:
print('Please enter a valid INTEGER!')
# General catch all for any other error.
else:
continue
I am very new to programming, please advise me if my code is correct.
I am trying to 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.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)
user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))