Verifying if user input is in multiple zero values - python

How can we check if a user enters the value 0 multiple times in a row?
I have tried below code- here I have tried to define multiple value in list, but if the user enters 000000000 or more, I have to define till 000000000 in list is there any other way to achieve this
list = [0,00,000,0000]
num = int(input("Enter a number: "))
if num in list:
print("Zero")
elif :
print(" None ")

You need to take the input as a string. And you can check if the user has entered a string that will have all zeros in it as follows
def all_zeros(string):
return all(ch == '0' for ch in string)

This worked for me
num = input("Enter: ")
if num.count('0') > 0 and num.startswith('0'):
print("0")
else:
print("none")

Since you asked in this way
How can we check if a user enters the value 0 multiple times in a row?
But, other answers were checking whether more than one 0's are present in the string or not. I assume you want to check continuous zero's only,
num = input("Enter Number: ") # returns string
if "00" in num: #checking substring
print("Found continuous zeros")
else:
print("Entered no continous zeros!")
value = int(num) # convert it to int if needed
It doesn't matter how many zeros in the string, all these [00,000,0000,00000...] belong to the same category.
Output:
>>> num = input("Enter Number: ")
Enter Number: 0008
>>> num
'0008'
>>> "00" in num
True
>>>

num = input("Enter: ")
if num.count("0") > 1 and int(num) == 0:
print("0")
else:
print("none")
don't change num to int it will remove all the trailing zeroes

Related

How to loop a function def in python until I write the number 0

I'm trying to do a def function and have it add the digits of any number entered and stop when I type the number "0", for example:
Enter the number: 25
Sum of digits: 7
Enter the number: 38
Sum of digits: 11
Enter the number: 0
loop finished
I have created the code for the sum of digits of the entered number, but when the program finishes adding, the cycle is over, but what I am looking for is to ask again for another number until finally when I enter the number "0" the cycle ends :(
This is my code:
def sum_dig():
s=0
num = int(input("Enter a number: "))
while num != 0 and num>0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
if num>0:
return num
sum_dig()
Use list() to break the input number (as a string) into a list of digits, and sum them using a list comprehension. Use while True to make an infinite loop, and exit it using return. Print the sum of digits using f-strings or formatted string literals:
def sum_dig():
while True:
num = input("Enter a number: ")
if int(num) <= 0:
return
s = sum([int(d) for d in list(num)])
print(f'The sum of the digits is: {s}')
sum_dig()
In order to get continuous input, you can use while True and add your condition of break which is if num == 0 in this case.
def sum_dig():
while True:
s = 0
num = int(input("Enter a number: "))
# Break condition
if num == 0:
print('loop finished')
break
while num > 0:
r=num%10
s=s+r
num=num//10
print("The sum of the digits is:",s)
sum_dig()
A better approach would be to have sum_dig take in the number for which you want to sum the digits as a parameter, and then have a while loop that takes care of getting the user input, converting it to a number, and calling the sum_digit function.
def sum_dig(num): # takes in the number as a parameter (assumed to be non-zero)
s=0
while num > 0: # equivalent to num != 0 and num > 0
r = num % 10
s = s + r
num = num // 10
return s
while True:
num = int(input("Enter a number: "))
if num == 0:
break
print("The sum of the digits is: " + sum_dig(num))
This enables your code to adhere to the Single-Responsibility Principle, wherein each unit of code has a single responsibility. Here, the function is responsible for taking an input number and returning the sum of its digits (as indicated by its name), and the loop is responsible for continuously reading in user input, casting it, checking that it is not the exit value (0), and then calling the processing function on the input and printing its output.
Rustam Garayev's answer surely solves the problem but as an alternative (since I thought that you were also trying to create it in a recursive way), consider this very similar (recursive) version:
def sum_dig():
s=0
num = int(input("Enter a number: "))
if not num: # == 0
return num
while num>0:
r= num %10
s= s+r
num= num//10
print("The sum of the digits is:",s)
sum_dig()

Need help understanding while-loops and what it is doing

I am learning Python, and currently I am learning about sentinel loops. I have this piece of code that I need help understanding. What exactly is the while-loop doing? I did some research and I know it is looping through the if-statement (correct me if I am wrong); but is it looping through a specific equation until the user stops inputting their integers? Thank you in advanced.
(Please no hate comments I am still learning as a developer. & this is my first post Thanks)
even = 0 odd = 0
string_value = input("Please enter an int. value: ")
while string_value !="":
int_value = int(string_value)
if int_value % 2 == 0:
even += 1
else:
odd += 1
string_value = input("Please enter an int. value: ")
if even + odd == 0:
print("No values were found. Try again...") else:
print("Number of evens is: ", str(even)+".")
print("Number of odd is: ", str(odd)+".")
---Updated Code:
def main():
print("Process a series of ints enter at console \n")
count_even = 0
count_odd = 0
num_str = input("Please enter an int. value or press <Enter> to stop: ")
#Process with loop
while num_str !="":
num_int = int(num_str)
if num_int % 2 == 0:
count_even += 1
else:
count_odd += 1
num_str = input("Please enter an int. value: ")
if count_even + count_odd == 0:
print("No values were found. Try again...")
else:
print("Number of evens is: ", str(count_even)+".")
print("Number of odd is: ", str(count_odd)+".")
main()
First thing the while loop does is check if the user input is emptywhile string_value !="", if it is not empty than it will start the loop. The != means not equals and the "" is empty so not equals empty. Next it sets the variable int_value as the integer of the user input(will error if user inputs anything other than whole number). Next it checks if the variable int_value % 2(remainder of division by 2) is 0, so pretty much it checks if the number is divisible by 2, if it is divisible by two it will add 1 to the even variable. Otherwise it will add 1 to the odd variable
It will be very helpful if you go through python doc https://docs.python.org/3/tutorial/index.html
even = 0 odd = 0
The above line even and odd are variables keeping count of even number and odd number.
string_value = input("Please enter an int. value: ")
The above line prompt the user to input an integer
while string_value !="":
int_value = int(string_value)
if int_value % 2 == 0:
even += 1
else:
odd += 1
string_value = input("Please enter an int. value: ")
The above while loop check firstly, if the input is not empty, int() Return an integer object constructed from a number or string x, or return 0 if no arguments are given https://docs.python.org/3/library/functions.html#int. The if statement takes the modulus of the integer value, and then increases the counter for either odd or even.
Finally, the count of odd and even are printed.
the input() function waits until the user enters a string so unless the user enters an empty string the while loop will keep asking the user for strings in this line:
string_value = input("Please enter an int. value: ")
and check if its an empty string in this line:
while string_value !="":

Why doesn't the max() function run as it is expected?

numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(first_input)
while first_input:
input_numb = input("Write next number")
if input_numb == int():
numbers.append(input_numb)
elif input_numb == "done":
print("The largest number is "+max(numbers))
print("The smallest number is "+min(numbers))
break
Can someone look at this code and tell me what I did wrong please? After I put the input numbers I want to print the biggest and smallest number from the list numbers but I don't know why the max function does not return the biggest number, instead it returns the smallest one (just like the min function. Why?
numbers = []
first_input = input('Write any number.When you are done just write "done":')
numbers.append(int(first_input))
while first_input:
input_numb = input("Write next number")
try:
numbers.append(int(input_numb))
except:
if input_numb == "done":
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))
break
else:
print('invalid input!')
out:
Write any number.When you are done just write "done":1
Write next numbera
invalid input!
Write next number2
Write next number3
Write next number6
Write next numberdone
The largest number is 6
The smallest number is 1
int() will return 0:
class int(x, base=10)
Return an integer object constructed from a number or string x, or
return 0 if no arguments are given.If x is a number, return x.__int__(). For floating point numbers, this truncates towards
zero.
In [7]: int() == 0 == False
Out[7]: True
you should use max in a list of number not a list of string, convert string to int before you append it to list
"The largest number is " + max(numbers)
return :
TypeError: Can't convert 'int' object to str implicitly, just use , to concate the string and int.
you should convert your inputs to integers using int(my_input) then add them to the list my_list.append(int(my_input)) and use the max or min functions max(my_list) after getting all the inputs from the user
numbers = []
user_input = input('Write any number.When you are done just write "done": ')
while user_input != "done":
try:
numbers.append(int(user_input))
user_input = input("Write next number : ")
except ValueError:
user_input = input("please enter a valid number : ")
print("The largest number is ", max(numbers))
print("The smallest number is ", min(numbers))

Python function using appends with lists not very efficient

Trying to write a function which takes input of 4 digit numbers and compares them, output of Ys and Ns to try and check if they are the same. EG 1234 and 1235 would output YYYN. At the minute it's very inefficient to keep using all these append commands. How could I simplify that?
def func():
results=[]
firstn= str(input("Please enter a 4 digit number: "))
secondn= str(input("Please enter a 4 digit number: "))
listone= list(firstn)
listtwo= list(secondn)
if listone[0]==listtwo[0]:
results.append("Y")
else:
results.append("N")
if listone[1]==listtwo[1]:
results.append("Y")
else:
results.append("N")
if listone[2]==listtwo[2]:
results.append("Y")
else:
results.append("N")
if listone[3]==listtwo[3]:
results.append("Y")
else:
results.append("N")
print(results)
Furthermore, how can I validate this to just 4 digits for length and type IE. Nothing more or less than a length of four / only numerical input? I have been researching into the len function but don't know how I can apply this to validate the input itself?
For the validation, you can write a function that will ask repeatedly for a number until it gets one that has len 4 and is all digits (using the isdigit() string method).
The actual comparison can be done in one line using a list comprehension.
def get_number(digits):
while True:
a = input('Please enter a {} digit number: '.format(digits))
if len(a) == digits and a.isdigit():
return a
print('That was not a {} digit number. Please try again.'.format(digits))
def compare_numbers(a, b):
return ['Y' if digit_a == digit_b else 'N' for digit_a, digit_b in zip(a, b)]
first = get_number(4)
second = get_number(4)
print(compare_numbers(first, second))
I think this should work.
def compare(a,b):
a,b = str(a),str(b)
truthvalue = {True:"Y",False:"N"}
return "".join([truthvalue[a[idx]==b[idx]] for idx,digit in enumerate(a)])
print(compare(311,321)) #Returns YNY
print(compare(321312,725322)) #Returns NYNYNY
def two_fourDigits():
results = []
firstn = input("Please enter the first 4 digit number: ")
while firstn.isnumeric() == False and len(firstn) != 4:
firstn= input("Please enter the second 4 digit number: ")
secondn = input("Please enter a 4 digit number: ")
while secondn.isnumeric() == False and len(secondn) != 4:
secondn= input("Please enter a 4 digit number: ")
for i in range(0, len(firstn)):
if firstn[i] == secondn[i]:
results.append("Y")
else:
results.append("N")
print(results)
You don't need to convert the input to a string, the input() function automatically takes in the values as a string.
Second, I added in input validation for firstn and secondn to check that they were numeric, and to check if they are the correct length (4). Also, there is no need to change the input to a list, because you can search through the strings.
I tried to do your function like this. Basically, the function uses the length of the first string to iterate through all the values of each list, and return Y if they are the same and N if they are not.
Because you don't make it a global variable which can be used from out of the function. Here is an example:
my_list = []
def my_func():
global my_list
my_list.append(0)
return "Something..."
my_list.append(1)
print my_list

How to count how many tries are used in a loop

For a python assignment I need to ask users to input numbers until they enter a negative number. So far I have:
print("Enter a negative number to end.")
number = input("Enter a number: ")
number = int(number)
import math
while number >= 0:
numberagain = input("Enter a number: ")
numberagain = int(numberagain)
while numberagain < 0:
break
how do I add up the number of times the user entered a value
i = 0
while True:
i += 1
n = input('Enter a number: ')
if n[1:].isdigit() and n[0] == '-':
break
print(i)
The str.isdigit() function is very useful for checking if an input is a number. This can prevent errors occurring from attempting to convert, say 'foo' into an int.
import itertools
print('Enter a negative number to end.')
for i in itertools.count():
text = input('Enter a number: ')
try:
n = int(text)
except ValueError:
continue
if n < 0:
print('Negative number {} entered after {} previous attempts'.format(n, i))
break
The solution above should be robust to weird inputs such as trailing whitespace and non-numeric stuff.
Here's a quick demo:
wim#wim-desktop:~$ python /tmp/spam.py
Enter a negative number to end.
Enter a number: 1
Enter a number: 2
Enter a number: foo123
Enter a number: i am a potato
Enter a number: -7
Negative number -7 entered after 4 previous attempts
wim#wim-desktop:~$

Categories

Resources