I have been trying to solve this problem by using the following function. What should I do to store all the digits input value and print them only at the end of the program when the program finishes to loop.
def compare(a):
a=0
while True:
b=input("Enter an integer : ")
if b.isdigit():
k=n+1
a=a+int(b)
elif b.isalpha():
if b.upper()=="Q":
print("Digits\n",a,"\nTotal\n",a)
break
else:
print("Invalid Value. Enter again")
elif b.isalnum():
print("Value not recognized. Enter a valid value.")
else:
print("Unrecognized value is submitted. Enter again")
I assumed you want the Total to print the number of digits, and not the sum of the digits. A working version with comments about the changes compared to your code:
def compare(): # input value is not used
a=[] # changed a to a list instead of integer
n=0 # hold the number of digits that were entered
while True:
b=input("Enter an integer : ")
if b.isdigit():
n+=1 # add 1 to the number of digits that were entered, variable k is not used
a.append(int(b)) #append the entered digit to list a
elif b.isalpha():
if b.upper()=="Q":
print("Digits\n",*a,"\nTotal\n",n) # use print(*a) to print the list of numbers
break
else:
print("Invalid Value. Enter again")
elif b.isalnum():
print("Value not recognized. Enter a valid value.")
else:
print("Unrecognized value is submitted. Enter again")
Updating you code as per question
def compare(a):
a=0
all_digits = [] # Empty list
while True:
b=input("Enter an integer : ")
if b.isdigit():
all_inputs.append(b) # Append digit to list
k=n+1
a=a+int(b)
elif b.isalpha():
if b.upper()=="Q":
print("Digits\n",a,"\nTotal\n",a)
print("all digits: {}".format(all_digits))
break
else:
print("Invalid Value. Enter again")
elif b.isalnum():
print("Value not recognized. Enter a valid value.")
else:
print("Unrecognized value is submitted. Enter again")
But this would be better code:
def compare(): # no need to pass any argument
a = 0
all_digits = [] # Empty list
while True:
b = raw_input("Enter an integer: ")
if b.isdigit():
all_digits.append(b) # Append digit to list
a = a + int(b) # do not see 'k' being used anywhere
elif b.isalpha():
if b.upper() == "Q":
print("Digits: {}\nTotal: {}\nSum: {}".format(", ".join(all_digits), len(all_digits), a))
break
else:
print("Invalid Value. Enter again")
else: # no need of b.isalnum(). this will take care of both
print("Unrecognized value is submitted. Enter again")
Output
Enter an integer: 1
Enter an integer: 2
Enter an integer: 3
Enter an integer: 4
Enter an integer: 5
Enter an integer: Q
Digits: 1, 2, 3, 4, 5
Total: 5
Sum: 15
Related
I was working on a for loop and while loop for 2 separate programs asking for the same thing. My for loop is giving me syntax issues and won't come out as expected…
Expectations: A python program that takes a positive integer as input, adds up all of the integers from zero to the inputted number, and then prints the sum. If your user enters a negative number, it shows them a message reminding them to input only a positive number.
reality:
i1 = int(input("Please input a positive integer: "))
if i1 >= 0:
value = 0 # a default, starting value
for step in range(0, i1): # step just being the number we're currently at
value1 = value + step
print(value1)
else:
print(i1, "is negative")
And my While loop is printing "insert a number" infinitly…
Here is what my while loop looks like:
while True:
try:
print("Insert a number :")
n=int(input())
if(n<0):
print("Only positive numbers allowed")
else:
print ((n*(n+1))//2)
except ValueError:
print("Please insert an integer")
`Same expections as my for loop but as a while loop
Anyone know anyway I could fix this issue?
You have some indentation issues. This way works:
while True:
try:
print("Insert a number: ")
user_input = input()
if user_input == 'q':
exit()
n = int(user_input)
if n <= 0:
print("Only positive numbers allowed")
else:
print(n * (n+1) // 2)
except ValueError:
print("Please enter an integer")
Output sample:
Enter a number:
>>> 10
55
Enter a number:
>>> 1
1
Enter a number:
>>> -1
Only positive numbers allowed
Enter a number:
>>> asd
Please enter an integer
Enter a number:
See more about indentation in the docs.
I am trying to write a game that generates a random integer and the user has to guess it.
The problem is that if the user input is not a digit it crashes. So I tried to use isdigit, and it works at the beginning, but if the user decides to input not a number after the first input was a digit, it still crashes. I don't know how to make it check isdigit for every input.
import random
x =(random.randint(0,100))
print("The program draws a number from 0 to 100. Try to guess it!")
a = input("enter a number:")
while a.isdigit() == False :
print("It is not a digit")
a = input("enter a number:")
if a.isdigit() == True :
a = int(a)
while a != x :
if a <= x :
print("too less")
a = input("enter a number:")
elif a >= x :
print("too much")
a = input("enter a number")
if a == x :
print("good")
I would suggest doing the following:
completed = False
while not completed:
a = input("enter a number: ")
if a.isdigit():
a = int(a)
if a < x:
print("too little")
elif a > x:
print("too much")
else:
print("good")
completed = True
else:
print("It is not a digit")
If your code crashed because the user entered not a number, then either make sure the user enters a number, or handle an error while trying to compare it with a number.
You could go over all chars in the input and ensure that they are all digits.
Or you could use a try/except mechanism. That is, try to convert to the numerical type you wish the user to enter and handle any error throwen. Check this post:
How can I check if a string represents an int, without using try/except?
And also:
https://docs.python.org/3/tutorial/errors.html
The typical pythonic way to tackle that would be to "ask for forgiveness instead of looking before you leap". In concrete terms, try to parse the input as int, and catch any errors:
try:
a = int(input('Enter a number: '))
except ValueError:
print('Not a number')
Beyond that, the problem is obviously that you're doing the careful checking once at the start of the program, but not later on when asking for input again. Try to reduce the places where you ask for input and check it to one place, and write a loop to repeat it as often as necessary:
while True:
try:
a = int(input('Enter a number: '))
except ValueError: # goes here if int() raises an error
print('Not a number')
continue # try again by restarting the loop
if a == x:
break # end the loop
elif a < x:
print('Too low')
else:
print('Too high')
print('Congratulations')
# user vs randint
import random
computer = random.randint(0,100)
while True:
try:
user = int(input(" Enter a number : "))
except (ValueError,NameError):
print(" Please enter a valid number ")
else:
if user == computer:
print(" Wow .. You win the game ")
break
elif user > computer:
print(" Too High ")
else:
print(" Too low ")
I think this can solve the issues.
In your code you want to check whether the user has input no or string since your not using int() in your input it will take input as string and furthur in your code it wont be able to check for <= condition
for checking input no is string or no
code:-
a = input ("Enter no")
try:
val = int(a)
print("Yes input string is an Integer.")
print("Input number value is: ", a)
except ValueError:
print("It is not integer!")
print(" It's a string")
You probably will have to learn how to do functions and write your own input function.
def my_input(prompt):
val = input(prompt)
if val.isdigit():
return val
else:
print('not a number')
# return my_input(prompt)
hi there i'm learning python
i like to know if this script can be better or shorter
import sys
g = 1
def trying():
q = input('enter (y or yes) to retry')
if not q == 'y' or q == 'yes':
return 0
while g == True:
try:
t = int(input('please enter an integer:'))
r = t % 2
if r == 0:
print('your number is even')
if trying() == 0:
g = 0
else:
print('your number is odd')
if trying() == 0:
g = 0
except ValueError:
print('sorry you need to enter numbers only')
If you want in shorter, here is my version..
while True:
try:
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
if input('Enter (y or yes) to retry: ') not in ['y', 'yes']: break
except ValueError:
print('Sorry you need to enter numbers only')
What you want here is a do-while loop. You can easily implement it by adding a break statement to a infinite while-loop. More on this topic can be found here.
Next thing, you have to add a try-except statement as there is a string to integer conversion is happening.
print('Your number is %s' % ('even' if int(input('Please enter an integer: ')) % 2 == 0 else 'odd'))
This statement will return "Your number is even" if the input is even else it will return "Your number is odd". This method is called python ternary operator.
Then you can wrap it with a print-function to print the returned string. Look here.
input('Enter (y or yes) to retry: ') not in ['y', 'yes']
This check whether the user input is not there in the given list. So if user input is neither "y" or "yes", while-loop will break.
Here is an example of how the code can be made simpler. Remember that code should rarely be repeated. In most cases, if you have repeating lines of code it can be simplified.
while True:
try:
t = int(input('please enter an integer:'))
if t % 2 == 0: print('your number is even')
else: print('your number is odd')
q = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'): break
except ValueError:
print('sorry you need to enter numbers only')
def trying():
question = input('enter (y or yes) to retry')
if not (q == 'y' or q == 'yes'):
return 1
return 0
while True:
try:
num1 = int(input('please enter an integer:'))
num2 = t % 2
if not num2:
print('your number is even')
else:
print('your number is odd')
if trying():
break
except ValueError:
print('sorry you need to enter numbers only')
You don't have to import sys in your program as you didn't used it and you don't have to. You don't have to store anything in a variable for a while loop. Just assigning True and breaking out will do. If you're looking for anything that is True (this includes an unempty list, string, and dictionaries; and numbers not equal to 0). You should make if var:. If the variable evaluates to True. The conditional block will be executed. This is a clearer syntax so it is recommended. Name your variables with words, not with letters. This will not make your code longer and it will make your code better.
This is all I can do with your code. If there is more, please state them.
I have a piece of code that does some calculations with a user input number. I need a way to check if user entry is an integer and that entered number length is equal or more than 5 digits. If either one of conditions are False, return to entry. Here is what i got so far and its not working:
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "
If anyone has a solution, I'd appreciate it.
Thanks
This would be my solution
while True:
stringset = raw_input("Enter a number: ")
try:
number = int(stringset)
except ValueError:
print("Not a number")
else:
if len(stringset) >= 5:
break
else:
print("Re-enter number")
something like this would work
while True:
number = input('enter your number: ')
if len(number) >= 5 and number.isdigit():
break
else:
print('re-enter number')
Use this instead of your code
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5:
try:
val = int(userInput)
break
except ValueError:
print "Re-enter number:
else:
print "Re-enter number:
Do not use isdigit function if you want negative numbers too.
By default raw_input take string input and input take integer input.In order to get length of input number you can convert the number into string and then get length of it.
while True:
stringset = input("Enter number: ")
if len(str(stringset))>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "
numbers=[]
maximum=0
while True:
number =input("Enter a number:")
if number == "0":
break
else:
numbers.append(number)
print ("The largest number entered was:")
print (max(numbers))
This seems to work for numbers below 10 only when I enter these numbers:
Enter a number:10
Enter a number:9
Enter a number:3
Enter a number:4
Enter a number:23
Enter a number:0
The largest number entered was:
9
As you can see, the largest number is actually 23, but it printed 9, what have I done wrong?
You are appending strings, append integers instead:
numbers.append(int(number))
Or better:
while True:
number = int(input("Enter a number:"))
if not number:
break
else:
numbers.append(number)
EDIT: you can wrap the integer conversion with try-except block to make sure user enters only digits:
while True:
nb = input('Enter a number:')
try:
nb = int(nb)
if not nb:
break
else:
numbers.append(nb)
except ValueError:
print('Please Enter Valid Number')
print ("The largest number entered was:")
print (max(numbers))
You are returning the lexicographical maximum, which is 9. This is due to your building the numbers container from string types.
To return the numeric maximum, build your container with integers using append(int(number)).
You could append it as int or print max with map and int to your list:
print (max(map(int, numbers)))