Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
i of iteration "for" do not grow. Although the i do not grow, the plain is infinitely adhered to the '#'
program : This is find width and height as close to the square as possible. So If length of string is prime number, string += "#" and re-calculate.
def build_size(plain: str, length: int, length_name: int):
def size_control(plain, length): return plain + "#", length + 1
print(f"length : {length} | length_name {length_name} \n plain : {plain}") #debug
input("continue? : ") #debug
while True:
try:
print(f"plain : {plain}") #debug
aliquot = list()
for i in range(int(length // 2) + 1):
print(f"i : {i}") #debug
if length % i == 0:
aliquot.append(i)
if len(aliquot) < 2 or aliquot[-1] <= length_name: raise NotImplementedError
break
except: plain, length = size_control(plain, length)
return plain, aliquot[-1] , length // aliquot[-1]
if __name__ == "__main__":
name = input("name : ")
plain = input("plain : ")
build_size(plain, len(plain), len(name))
How can I do? Please help me.
I believe the reason i does not grow is that your while loop always raises an error on the first pass of the for loop. So the for loop ends, the while loop advances, and i gets set back to 0.
Speaking of 0, I think that's your problem. When you call range() with only one argument, the starting point defaults to 0, not 1. Anything modulo 0 is undefined, so length % i always throws a ZeroDivisionError, which your bare except: clause always catches.
Edit: To fix this bug, I suggest two things. First, start your range at 1 instead of zero, replacing that line with something like:
for i in range(1, int(length // 2) + 1):
Second, try to avoid bare except: clauses. If you had used except NotImplementedError: instead, then it wouldn't have caught the ZeroDivisionError, and you would have seen the normal error message and been able to figure out the problem much more easily.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I want a program that sums the even numbers of a bigger number using while function.
Exemple :
Number is : 12345
Print : 6 (2+4)
This is what i wrote so far:
num = int(input("Introduce a non negative number: "))
if num % 2 == 0:
sum += num
print("sum")
I can't stress this enough
When doing school assignments, the whole idea with assignments is to teach you concepts, not solutions. There's a reason why you were given this assignment, asking others to solve it for you - is not the way to go.
Go back to your teacher, and ask for help if something is unclear. But because others start posting solutions I might as well just keep mine here.
Skipping the conversion to an early integer, will allow you to iterate over it as a string, and grab one number a a time.
num = input("Introduce a non negative number: ")
total = 0
for i in num:
if int(i) % 2 == 0:
total += int(i)
print("sum:", total)
You can then use your original logic, with some minor modifications.
Since for whatever reason, you're only allowed to use while and not for, you'd have to just adapt a bit.
num = input("Introduce a non negative number: ")
total = 0
i = 0
while i < len(num):
if int(num[i]) % 2 == 0:
total += int(num[i])
i += 1
print("sum:", total)
While I'm at it, after reading my code again. I am quite sure that a while loop here is the least pretty solution to this problem. But from a teaching standpoint there might be some benefit here. But I'd recommend going with the for loop if at all possible.
Try this one:
# split the number to list of digits
digits_list = list(input("Introduce a non negative number: "))
total = 0
# loop over the digits list and pick a digit till the list is empty
while digits_list:
digit = digits_list.pop()
if int(digit) % 2 == 0:
total += int(digit)
print(total)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to not accept the username if it is not between 3 and 9 characters.
print (""+winner+", please input your first name, maximum of 10 characters.")
winnername = str(input())
length = (int(len(winnername)))
if 3 > length > 10:
loop5 = 1
while loop5 == 1:
print ("name is too short")
winnername = input()
length = len(winnername)
if (length) <3 and (length) <10:
break
print ("name accept")
I would expect it to loop and ask the user for another input if the provided input doesn't meet the requirements outlined in the above text.
if 3 > length > 10: is checking to make sure that length is LESS than 3 and Greater than 10, which is impossible.
Therefore the check should be if 2 < length < 10: (this will be true for lengths 3 to 9)
Let me fix your code, elegant and clean:
while True:
# I don't know if `winner` is defined
firstname = input(""+winner+", please input your first name, maximum of 10 characters.")
if 3 < len(firstname) < 10:
break
print("name is too short or too long")
print('name accepted')
The problem is 3 > length > 10 will never be executed because 3 will never be greater > than 10
Regarding your first sentence, as far as I can see form the code you are actually trying to allow maximum number of characters to be 10, not 9.
Below is a possible solution for what you're trying to achieve. The below script will keep asking user until name length is within allowed range.
print ("'+winner+', please input your first name, maximum of 10 characters.")
while True:
winnername = str(input())
if(len(winnername) < 3):
print("Name is too short")
elif(len(winnername) > 10):
print("Name is too long")
else:
break
print ("Name accepted")
You may also consider to perform some validation of winnername first (do not allow spaces or any other special characters).
winner = "Mustermann"
# Build a string called "prompt"
prompt = winner + ", please input your first name, between 3 and and 10 characters."
loopLimit = 5 # Make this a variable, so it's easy to change later
loop = 0 # Start at zero
winnername = "" # Set it less than three to start, so the while loop will pick it up
# Put the while loop here, and use it as the length check
# Use an or to explicitely join them
while True: # Set an infinite loop
loop += 1 # Increment the loop here.
# Add the string to the input command. The "input" will use the prompt
# You don't need the "str()", since input is always a string
winnername = input(prompt)
length = len(winnername)
# Separate the checks, to give a better error message
if (length < 3):
print ("Name is too short!") # Loop will continue
elif (length > 10):
print("Name is too long!") # Loop will continue
else: # This means name is OK. So finish
print("Name accepted!")
break # Will end the loop, and the script, since no code follows the loop
if loop >= loopLimit:
# Raise an error to kill the script
raise RuntimeError("You have reached the allowed number of tries for entering you name!")
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have been going through an introduction to python booklet and have been stuck on the following question. the question is outlined below and my attempt follows after the question.
Take this program:
m = 0
finished = False
while not finished:
print('Enter another whole number (0 to finish): ', end = '')
s = input()
num = int(s)
if num != 0:
if num > m:
m = num
else:
finished = True
print(str(m))
If you have worked out what the above program does, can you see that,
for certain series
of numbers, it will not produce the correct output? In what
circumstances will it not
work correctly, and how could you change
the program to make it work properly?
My understanding is that the series of numbers, where the above program will fail, are decimal numbers (non-whole number), therefore my attempt is as follows:
m='0'
finished = False
while not finished:
print('enter number, 0 to finish: ', end = '')
num = input()
if num != '0':
if num > m:
m = num
else:
finished = True
print(m)
However this fails at understanding that 77 is larger than 8 since it is reading it as a string.
This program calculates the maximum value from the inputted sequence. It stores the maximal value in m, and if a num is inputted that's larger than it, it keeps it as the new maximum.
However, note that m is initialized with 0, making the implicit assumption that at least one number you'll input is positive. If you input only negative numbers, you'll get 0 as the largest number, which is clearly wrong, as you never inputted it.
A quick fix could be to initialize m with None and explicitly check for it:
m = None
finished = False
while not finished:
print('Enter another whole number (0 to finish): ', end = '')
s = input()
num = int(s)
if num != 0:
if not m or num > m:
m = num
else:
finished = True
print(str(m))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have the following code to print the (distinct numbers), but I'm trying to check the inputs before the process, should be ten digits numbers only with only one space.
I tried while and try but still can't figure out:
def main():
list1 = input("Enter ten numbers: ").split()
set1 = set(list1)
print(set1)
list2 = list(set1)
string = string.join(list2)
print("The distinct numbers are: " + str(string))
main()
A simpler version using the isnumeric() method built in strings. Also, I put a loop around the input so as the user can easily retry in case of wrong data:
def main():
while(True):
numbers = input("Enter ten space-separated numbers: ").split()
if len(numbers) != 10 or not all(n.isnumeric() for n in numbers):
print("Wrong input, please retry")
continue
numbers = ' '.join(set(numbers))
print("The distinct numbers are:", numbers)
break # or return numbers if you need the data
main()
Do you mean check if there are ten numbers inputted?
import re
def check_input(input_string):
compare_to = '\s'.join(10*['\d+'])
if re.match(compare_to[:-1], input_string):
return True
return False
This is a regular expression, it checks if the input string is equal to a specified input format. This one specifically checks whether 10 sets of at least 1 number [\d+] are added with a space inbetween \s.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I wrote two functions. First one, when called checks if the number is three-digit, and second one is checking if the number is even or odd:
def even(n):
if n%2==0:
print('number {} is even'.format(n))
else:
print('number {} is not even'.format(n))
return
def main(n):
kraj=True
while(kraj):
a=int(input('three-digit number pls: '))
if (a>99 and a<1000):
kraj=False
return True
else:
print('I said three-digit number!! ::')
return False
main(0)
What my problem is, when I call function even like even(a), it gives me an error saying a is not defined.
You must return a in the main() function and pass it to the even function.
def main(n):
kraj=True
while(kraj):
a=int(input('three-digit number pls: '))
if (a>99 and a<1000):
kraj=False
return a
else:
print('I said three-digit number!! ::')
return False
a = main(0)
even(a)
You have to return the value of a so you can use it somewhere else
Also you have a while and return in if and else.
Therefore you do not need your while loop. Or you want the user to reenter on error you then have to get rid of the return in else
You should give your function a more meaningfull name like read_threedigit_number
You normally don't put paranthesis around if and while
Improved Code
def read_threedigit_number(n):
while True:
a=int(input('three-digit number pls: '))
if a>99 and a<1000:
return a
else:
print('I said three-digit number!')
a = read_threedigit_number(0)
even(a)