Wishing to end a while: loop with break - python

nc = dict(zip(nation,cap))
print("Countries and Capitals :{}".format(nc))
k = 0
while k != 5:
k = input("input : ")
if k == 1:
break
if k != 1:
key = k
print("The capital of {} is {} ".format(key,nc[key]))
#This only makes an error when I type in 1. I want it to stop the program when pressed 1. What can I do about it?

input("input ") returns a string.
You could do:
nc = dict(zip(nation,cap))
print("Countries and Capitals :{}".format(nc))
k = 0
while k != 5:
k = int(input("input : "))
if k == 1:
break
if k != 1:
key = k
print("The capital of {} is {} ".format(key,nc[key]))

input() returns string by default.
So,
You need to take k as integer input using int() function.
k = int(input("input..."))

Related

Lucky Number counting

I'm trying to make a lucky number counter where if there is a number containing either a 6 or an 8 between the two inputs the number is lucky, but if there's both a 6 and an 8 the number is unlucky. I'm having an issue where it's double-counting numbers, like 66, 88, etc., and not calling unlucky numbers like 68, 86, etc. Please help fast :\
l, h = [int(x) for x in input().split()]
count = 0
for i in range(l,h+1):
i = str(i)
for j in range(len(i)):
if i[j] == '6' or i[j] == '8':
count += 1
print(count)
Try this:
import sys
temp1 = ""
while len(temp1) != 2:
temp1 = input("Enter 2 digits: ")
try:
temp2 = int(temp1)
except ValueError:
print("You did not enter valid input")
sys.exit(1)
lucky = False
if "6" in temp1:
lucky = True
if "8" in temp1:
lucky = True
if ("6" in temp1) and ("8" in temp1):
lucky = False
print("Lucky number: "+str(lucky))
Something like this, probably:
number = ''
while len(number) != 2 or any(ch not in '0123456789' for ch in number):
number = input('Enter a 2-digit positive integer:')
print(f'{number} is {"lucky" if ("6" in number) != ("8" in number) else "not lucky"}')
# or, if you meant to say "exactly one 6 or 8":
print(f'{number} is {"lucky" if len([ch for ch in number if ch in "68"]) == 1 else "not lucky"}')
You could try using the count() method for Strings:
numbers = input().split(' ')
count = 0
for num in numbers:
if num.count('6') > 0:
if num.count('8') > 0:
continue
else:
count += 1
elif num.count('8') > 0:
count += 1
print(count)
this, while not as elegant or efficient, seems to be the correct code for the implied question
l, h = [int(x) for x in input().split()]
count = 0
for i in range(l,h+1):
i = str(i)
if ('6' in i and '8' in i):
continue
if i.count('6') > 0 or i.count('8') > 0:
count += 1
print(count)

The last value in my list will not convert into integer

I am writing a code in which I take values from a user until they enter 'q'. I then have to print the EVEN numbers out in ascending order. I how to do the program, I just have run into a minor problem I do not know how to solve.
My code is:
integer = []
g = 7
while g > 1: # Initiate loop
num = input('Enter an integer or press q to quit. ')
if num == 'q':
break
integer = list(map(int, integer))
if num % 2 == 0:
integer.append(num)
integer.sort()
print(integer)
Running this code gives me the error that not all strings have converted. So I then erased the second if statement:
if num % 2 == 0:
integer.append(num)
Erasing this I can see that the last value in the list will not convert into an integer. I do not know why that is and I have tried numerous string-list to integer-list conversions and they all never convert the last value. Does anybody know why this is?
you can do this:
evens = []
while True: # Initiate infinite loop
num = input('Enter an integer or press q to quit. ')
if num == 'q':
break
num = int(num) #convert the num to int
if num % 2 == 0:
evens.append(num)
evens.sort()
print(evens)
Corrected code:
integer = []
g = 7
while g > 1: # Initiate loop
num = input('Enter an integer or press q to quit. ')
if num == 'q':
break
num = int(num) #convert input to integer
if num % 2 == 0:
integer.append(num)
integer.sort()
print(integer)
the issue is num is a string from user input, you must convert it to an integer like this
if int(num) % 2 == 0:
integer.append(int(num))

Finding the largest substring of 1's

I want the largest substring of 1's
inp = input("ENter number")
count = 1
num = []
for i in range(len(inp)):
if (inp[i] == inp[i+1]):
count+=1
num.append(count)
count = 1
print(max(num))
this is the input "10110111", the output must be 3
but there is error
if (inp[i] == inp[i+1]):
IndexError: string index out of range
You can solve it easily. Split() method will split your string input and returns a list and you can simply find the element with the maximum length
inp = input("Enter number")
max_Ones = len(max(inp.split('0'), key=len))
print(max_Ones)
I'd use re.findall and then convert each group to its length:
import re
inp = input("Enter number: ")
result = max(len(x) for x in re.findall('1+', input))
print(result)
Try this below:
inp = input("ENter number")
count = 0
result = 0
for i in range(0, len(inp)):
if inp[i] == '0':
count = 0
elif inp[i] == '1':
count += 1
result = max(result, count)
print(result)

Infinite amount of unique generated variables, python

So, I'm making a program that asks for user input to define a variable. What I want it to do is keep prompting them to define variables until they terminate the program. I.E. it prompts A1: and they input 2, and then it Prompts A2: and they input 6, and so on, until they press enter without inputting anything. The problem I am having is that I need unique variables for each time it loops. I also want these variables to be able to access the variables defined outside of the function, without using global.
Here is what I've got:
def userinput():
n = 0
while n >= 0:
c = str(n)
v = 'A'+c+':'
v = input(v)
if v != '':
n += 1
else:
while v == '':
break
break
userinput()
As you can see, what it does know is set the user's input equal to v each iteration. I want it to set the first input to A0, then the next iteration, I want it the input to be set to A1, and so on and so forth. Then, after the user has run this, I want to be able to call the variable A1 and get a result. Any ideas?
EDIT:
So, here is my program. It takes input, adds the input to a list, then converts the list items to global variables. I didn't want to use global, but I had to.
def userinput():
n = 0
values = []
while True:
c = str(n)
v = 'A'+c+':'
v = input(v)
values.append(v)
if v != '':
n += 1
else:
while v == '':
values.remove(v)
break
break
for x, val in enumerate(values):
globals()['A%d' % (x)] = val
return values
data = userinput()
Use a list?
def getUserInput():
values = []
while True:
val = input("Enter a value (press enter to finish):")
if not val:
break
values.append(val)
return values
data = getUserInput()
Instead of a while loop, make a for loop wrapped in a while loop, like this:
def userinput():
n = 0
while n >= 0:
for x in range(100):
v = 'A'+x+':'
v = input(v)
if v != '':
n += 1
else:
while v == '':
break
break
userinput()
Once again, here is the answer:
def userinput():
n = 0
values = []
while True:
c = str(n)
v = 'A'+c+':'
v = input(v)
values.append(v)
if v != '':
n += 1
else:
while v == '':
values.remove(v)
break
break
for x, val in enumerate(values):
globals()['A%d' % (x)] = val
return values
data = userinput()

How to read single digits from a string and perform a function on them?

I am trying to gather user input in the form of a non negative integer. I then want to take this integer and tell the user how many odd, even, and zero, single digit numbers there are in their integer.
Ex. User inputs "123" and the program outputs Evens: 1 Odds: 2 Zeros: 0
Here is my code so far.
def main():
print("1. Enter a new number")
print("2. Print the number of odd, even and zero digits in the integer")
print("3. Print the sum of the digits of the integer")
print("4. Quit the program")
value = (input("Please enter a non-negative integer"))
Sum = 0
evens = 0
odds = 0
zeros = 0
loop=True
while loop:
main()
choice = int(input("Enter a number between 1 and 4:"))
if choice==1:
loop=False
value = int(input("Please enter a non-negative integer"))
loop=True
elif choice==2:
loop=False
value_string = str(value)
for ch in value_string:
print(ch)
for [1] in value:
if i % 2 == 0:
evens = evens + 1
print(evens)
elif choice==3:
loop=False
while (value >0):
remainder = value % 10
Sum = Sum + remainder
value = value //10
print("Sum of the digits = %d" %Sum)
Your code is badly indented and hard to follow. But you could do something like this.
value = input('enter digits ')
digits = [int(d) for d in value]
odds = sum(d % 2 for d in digits)
zeros = sum(d == 0 for d in digits)
evens = len(digits) - odds
print('evens: {}, odds: {}, zeros: {}'.format(evens, odds, zeros))
Here, I have your same code well indented, refactored and refined to handle some edge cases and to provide correct results.
def main():
print("1. Enter a new number")
print("2. Print the number of odd, even and zero digits in the integer")
print("3. Print the sum of the digits of the integer")
print("4. Quit the program")
loop = True
while loop:
main()
choice = str(input("Enter a number between 1 and 4: "))
if (choice.isdigit() and 1 <= int(choice) <= 4):
choice = int(choice)
if choice == 1:
value = str(input("Please enter a non-negative integer"))
if (value.isdigit() and int(value) >= 0):
value = int(value)
else:
print(
"You provided an invalid input. Please enter a non-negative number")
elif choice == 2:
value = str(value)
odds = len([d for d in value if (int(d) % 2) == 1])
evens = len([d for d in value if (int(d) % 2) == 0])
zeros = len([d for d in value if d == '0'])
print('odd: {} even: {} zeros: {}'.format(odds, evens, zeros))
elif choice == 3:
value = str(value)
print('Sum of digits = {}'.format(sum(map(int, value))))
elif choice == 4:
print("Program is exiting")
loop = False
else:
print("You provided an invalid input. Please enter a number between 1 and 4")

Categories