I have to write a program using Python, which should ask the user to enter integer numbers to compose a list of numbers. Then I have to check whether at least one number in this list is 3 digits long. How can I do that? I should use 'for' statement. I started this way:
numbers_list = []
while True:
try:
n = int(input("Enter an integer (press ENTER to end the program): "))
except ValueError:
break
else: numbers_list.append(n)
And then I tried to do this way, but it didn`t work:
num = False
for num in numbers:
if len(num) == 3:
num = True
break
print(num)
The answer should be: E.g. input = [1, 101, 2000], then output would be True; if input = [1,2,3], then output would be False
Use any function to return a bool value if any one element in the given list satisfies a particular condition.
numbers_list = []
while True:
try:
n = int(input("Enter an integer (press ENTER to end the program): "))
except ValueError:
break
else: numbers_list.append(n)
print(any(len(str(i))>2 for i in numbers_list))
It returns true if any one element in the list has the length greater than 2.
To return true if an element has exact three digits, then change the above any statement to,
print(any(len(str(i))==3 for i in numbers_list))
Related
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()
This question already has answers here:
Why does assigning to my global variables not work in Python?
(6 answers)
Closed 2 years ago.
I let the user input a 3-digit number, and let python throw a random 3-digit number, try to see when the random number can match the input. However, everytime I run it on cmd, it prints 'Python is too tired', which is a statement I set to prevent it from looping infinitely (I really did so, until I added this limitation of attempt times).
import random
my_num = int(input('Type your 3-digit int number: '))
if my_num >= 100 and my_num < 1000:
attempt = 0
my_lottery = []
my_lottery.append(int(num) for num in str(my_num))
def lottery_throw():
lottery = []
i=0
while i<3:
lottery.append(random.randint(1,9))
i+=1
return(lottery)
def check():
global boo
lottery_throw()
if lottery == my_lottery:
boo = 'true'
else:
boo = 'false'
while attempt < 100000:
check()
attempt += 1
if boo == 'true':
print('you win')
print(attempt)
break
elif attempt >= 100000:
print('python is too tired')
break
else:
print('You must enter a 3-digit number.')
Run it on cmd, everytime I run it, it returns 'Python is too tired'
But the number of possible combinations (9C3) is only 84. It's very unlikely that python really didn't throw a correct number. How can I fix this problem?
Errors
Do not use global variables unless you really need them. As you can see, writting to a global variable doesn't work our of the box
012 is a valid 3 digit number
If you append a list to another list you will get a nested list (list inside another list): [[1, 2, 3]]
Why create a list of each digit when you can create the number itself?
for loops should be used for a fixed number of iterations, while loops when a more complex condition is needed to return from the loop.
return should be used without parenthesis as they are redundant (it is not a function)
True and False are booleans, do not use "true" and "false" (strings) to represent them.
if condition return true else return false (in pseudocode) is the same as return condition
for loops also can have an else clause, which only is executed if no break was found.
Solution
import random
my_num = int(input("Type your 3-digit int number: "))
if 0 <= my_num < 1000:
for attempt in range(1, 100001):
if my_num == random.randint(0, 999):
print(f"You win in {attempt} attempts.")
break
else:
print("Python is too tired.")
else:
print("You must enter a 3-digit number.")
I have no idea what you did, but I wasn't able to fix it.
Here is my version incited:
num = input('Type your 3-digit int number: ')
for i in range(100000):
if (("00"+str(random.randint(0,999)))[-3:]) == num:
print("You win on attempt %i"%i)
did_win = True
break
else:print('python is too tired')
I am new to programming, and I'm trying to make a code to get six numbers from a user and sum only even numbers but it keeps error like, "unsupported operand type(s) for %: 'list' and 'int' How can I do with it?
Also, I want to make like this,
Enter a value: 1
Is it even number?:no
Enter a value: 2
Is it even number?:yes
Enter a value: 3
Is it even number?:no
Enter a value: 6
Is it even number?:yes
but it keeps like this,
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
Enter a value: 5
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
How can I fix this?
anyone who can fix this problem please let me know
Python 3.7
numbers = [int(input('Enter a value: ')) for i in range(6)]
question = [input('Is it even number?: ') for i in range(6)]
list1 = [] #evens
list2 = [] #odds
if numbers % 2 ==0:
list1.append
else:
list2.append
sum = sum(list1)
print(sum)
And I'd appreciate it if you could let me know if you knew the better code
This should do it. Note that there is no real need to ask the user if the number is even, but if you do want to ask, you can just add question = input('Is it even number?: ').lower() in the loop and then do if question=='yes'. Moreover, note that you cannot perform % on a list; it has to be on a single number.
evens = []
odds = []
for i in range(6):
number = int(input('Enter a value: '))
if number%2==0:
evens.append(number)
else:
odds.append(number)
print(sum(evens))
you are running the first two input statements in for loops and print at the same time.
You can just take inputs first 6 times and store them in a list. After that you can check each input and store in even and odd lists while printing if its even or odd. and print the sum at last.
Your if condition makes no sense:
if numbers % 2 == 0:
What is the value of [1, 2, 3, 6] % 2? There is no such thing as "a list, modulo 2". Modulus is defined between two scalar numbers.
Instead, you have to consider each integer in turn. This is not an operation you get to vectorize; that is a capability of NumPy, once you get that far.
for i in range(6):
num = int(input('Enter a value: '))
# From here, handle the *one* number before you loop back for the next.
If you want to show running sum. You can do something like :
import sys
sum_so_far = 0
while True:
raw_input = input('Enter an integer: ')
try:
input_int = int(raw_input)
if input_int == 0:
sys.exit(0)
elif input_int % 2 == 0:
sum_so_far = sum_so_far + input_int
print("Sum of Even integers is {}. Enter another integer er or 0 to exit".format(sum_so_far))
else:
print("You entered an Odd integer. Enter another integer or 0 to exit")
except ValueError:
print("You entered wrong value. Enter an integer or 0 to exit!!!")
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
I've tried to write like:
print "Enter numbers, stops when negative value is entered:"
numbers = [input('value: ') for i in range(10)]
while numbers<0:
but suddenly, I lose my mind, and don't know what to do next
the example is:
Enter numbers, stops when negative value is entered:
value: 5
value: 9
value: 2
value: 4
value: 8
value: -1
Maximum is 9
It sounds like you want something along these lines:
def get_number():
num = 0
while True: # Loop until they enter a number
try:
# Get a string input from the user and try converting to an int
num = int(raw_input('value: '))
break
except ValueError:
# They gave us something that's not an integer - catch it and keep trying
"That's not a number!"
# Done looping, return our number
return num
print "Enter numbers, stops when negative value is entered:"
nums = []
num = get_number() # Initial number - they have to enter at least one (for sanity)
while num >= 0: # While we get positive numbers
# We start with the append so the negative number doesn't end up in the list
nums.append(num)
num = get_number()
print "Max is: {}".format(max(nums))
This is what you're looking for:
print "Enter numbers, stops when negative value is entered:"
nums = []
while True: # infinite loop
try: n = int(raw_input("Enter a number: ")) # raw_input returns a string, so convert to an integer
except ValueError:
n = -1
print "Not a number!"
if n < 0: break # when n is negative, break out of the loop
else: nums.append(n)
print "Maximum number: {}".format(max(nums))
I think you want something like this:
# Show the startup message
print "Enter numbers, stops when negative value is entered:"
# This is the list of numbers
numbers = []
# Loop continuously
while True:
try:
# Get the input and make it an integer
num = int(raw_input("value: "))
# If a ValueError is raised, it means input wasn't a number
except ValueError:
# Jump back to the top of the loop
continue
# Check if the input is positive
if num < 0:
# If we have got here, it means input was bad (negative)
# So, we break the loop
break
# If we have got here, it means input was good
# So, we append it to the list
numbers.append(num)
# Show the maximum number in the list
print "Maximum is", max(numbers)
Demo:
Enter numbers, stops when negative value is entered:
value: 5
value: 9
value: 2
value: 4
value: 8
value: -1
Maximum is 9