Going back 2 step in nested loops - python

def get_user_choice():
global user_choice
''' 3users give their numbers to be validated'''
for i in range(1, 4):
choices = []
** choices = input("User {}, please enter 5 numbers separated by ',' :".format(i))
nums = choices.split(',')
while True:
if len(nums) != 5:
print(" Wrong choice,You have to enter 5 numbers separated by ','")
break
for nr in nums:
if nr.isdigit():
if int(nr) < 1 or int(nr) > 25:
print(" Wrong! Enter 5 Numbers between 1 and 25")
continue
else:
print(nr + " is not a number, try again")
continue
# How can i go back to ** from here????

This code corrects the logic for requesting numbers and returns the numbers selected.
def get_user_choice():
''' 3users give their numbers to be validated'''
#global user_choice--didn't understand why you needed a global user_choice so commented out for now
user_choices = []
for i in range(1, 4):
while True:
choices = input("User {}, please enter 5 numbers separated by ',' :".format(i))
nums = choices.split(',')
if len(nums) != 5:
print(" Wrong choice,You have to enter 5 numbers separated by ','")
else:
for nr in nums:
if nr.isdigit():
if int(nr) < 1 or int(nr) > 25:
print(" Wrong! Enter 5 Numbers between 1 and 25")
break
else:
print(nr + " is not a number, try again")
break
else:
user_choices.append(nums)
break
return user_choices
# Get user choices
choices = get_user_choice()
A cleaner version of the Above Code
def get_user_choice():
''' 3users give their numbers to be validated'''
invalid_numbers = lambda numbers: list(filter(lambda y: not y.isdigit(), numbers))
invalid_range = lambda numbers: list(filter(lambda y: not (1 <= int(y) <= 25), numbers))
user_choices = []
for i in range(1, 4):
while True:
choices = input("User {}, please enter 5 numbers separated by ',' :".format(i))
nums = choices.split(',')
if len(nums) != 5:
print(" Wrong choice, You have to enter 5 numbers separated by ','")
continue
p = invalid_numbers(nums)
if p:
print(*p,' are not numbers. Enter 5 numbers separaterd by "," ')
continue
p = invalid_range(nums)
if p:
print(*p, ' are out of range. Enter 5 numbers between 1 and 25')
continue
## uncomment if you wanted the number rather than strings
# nums = list(map(int, nums))
user_choices.append(nums)
break
return user_choices
choices = get_user_choice()

Related

python program troubleshoot

if the user enters a char it should show the wrong input and continue asking for input until it reaches the range of 10 elements. how to solve this? output
list = []
even = 0
for x in range(10):
number = int(input("Enter a number: "))
list.append(number)
for y in list:
if y % 2 == 0:
even +=1
print("Number of even numbers: " ,even)
for y in list:
if y % 2 == 0:
count = list.index(y)
print("Index [",count,"]: ",y)
myList = []
while len(myList) < 10:
try:
number = int(input("Enter a number: "))
myList.append(number)
except ValueError:
print('Wrong value. Please enter a number.')
print(myList)
Hope code is self explanatory:
arr = []
even = 0
error_flag = False
for x in range(10):
entry = input("Enter a number: ")
if not entry.isdigit():
print("Entry is not a number")
error_flag = True
break
arr.append(int(entry))
if not error_flag:
brr = []
for id, y in enumerate(arr):
if y%2 == 0:
brr.append([id,y])
print(f"Even numbers are: {len(brr)}")
for z in brr:
print(f"Index{z[0]} is {z[1]}")
list = []
even_list=[]
c=0
for x in range(10):
number = (input("Enter a number: "))
list.append(number)
if number.isdigit()==False :
print("wrong input")
break
elif int(number)%2==0:
even_list.append(number)
if len(list)==10:
print("Number of even numbers: ",len(even_list))
for i in list:
i=int(i)
if (i) %2==0:
print("Index %d : %d" %(c,i)) # print("Index",c,":",i)
c=c+1

I have a problem with the return statement returning no value

I have some code that takes overlapping elements from two lists and creates a new one with these elements. there are two functions which check for a valid input, however, the return statement returns no value to the main function. Can someone help me?
This is the code:
import random
import sys
def try_again():
d = input("\nTry again? (y/n): ")
if d == 'y':
main_func()
elif d != 'y' and d != 'n':
print("Invalid entry")
try_again()
elif d == 'n':
sys.exit()
def first_list_test(length_a, range_a):
length_a = int(input("Enter the length of the first random list: "))
range_a = int(input("Enter the range of the first random list: "))
if length_a > range_a:
print("The length of the list must be greater than the range for unique elements to generate")
first_list_test(length_a, range_a)
else:
print("Length: " + str(length_a))
print("Range: " + str(range_a))
return length_a, range_a
def second_list_test(length_b, range_b):
length_b = int(input("Enter the length of the second random list: "))
range_b = int(input("Enter the range of the second random list: "))
if length_b > range_b:
print("The length of the list must be greater than the range for unique elements to generate")
second_list_test(length_b, range_b)
else:
print("Length: " + str(length_b))
print("Range: " + str(range_b))
return length_b, range_b
def main_func():
length_a = int()
range_a = int()
first_list_test(length_a, range_a)
print(length_a)
print(range_a)
print("\n")
length_b = int()
range_b = int()
second_list_test(length_b, range_b)
print(length_b)
print(range_b)
print("\n")
a = random.sample(range(1, range_a), length_a)
a.sort()
b = random.sample(range(1, range_b), length_b)
b.sort()
num = int()
print(a, "\n")
print(b, "\n")
c = []
d = []
for num in a:
if num in b:
c.append(num)
for test_num in c:
if test_num not in d:
d.append(test_num)
d.sort()
if len(d) == 0:
print("No matches found")
else:
print("Overlapping elements: ")
print(d)
try_again()
main_func()

Giving one hint for each of the tries (guessing number game)

I am making a game which requires the user to enter a number. They get four tries, and if they get the number wrong, they get a hint.
How can I try to give only one hint for each of the four tries the user has to get the number right? For example, after the user gets the first try wrong, I would like the program to display the even_or_odd hint.
from random import randrange
new_number = randrange(1, 101)
class Hints:
def __init__(self, new_number):
self.new_number = new_number
def even_or_odd(self):
if self.new_number % 2 == 0:
print('Hint. The number is even.')
else:
print('Hint. The number is odd.')
def multiple3to5(self):
for x in range(3, 6):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of {x}', end = ' ' )
def multiple6to10(self):
for x in range(6, 11):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of x {x}', end = ' ')
print('Guess a number beteen 1 and 100.')
hint = Hints(new_number)
for x in range(1, 5):
is_answer_given = False
while not is_answer_given:
try:
user_input = int(input(f'Attempt {x}: '))
is_answer_given = True
except ValueError:
print('Please enter a numerical value.')
if user_input == new_number and x == 1: #hint after first attempt
print('You win!')
break
else:
print('Incorrect!')
hint.even_or_odd()
if user_input == new_number and x == 2: #hint after second attempt
print('You win!')
break
else:
print('Incorrect!')
hint.multiple3to5()
if user_input == new_number and x == 3: #hint after third attempt
print('You win!')
break
else:
print('Incorrect!')
hint.multiple6to10()
if x == 4:
print('You are out of attempts!')
print(f'The number was {new_number}')
break
You should make one if statement that checks for the correct answer. In the else statement you can use if - elif statements to check for the attempt number.
if user_input == new_number:
print('You win!')
break
else:
print('Incorrect!')
if x == 1:
hint.even_or_odd()
elif x == 2:
hint.multiple3to5()
elif x == 3:
hint.multiple6to10()
else:
print('You are out of attempts!')
print(f'The number was {new_number}')
The reason you see multiple hints on attempt is that for multiple if statements their condition is not true, so their 'else' block is run
Here is a neat trick:
from random import randrange
new_number = randrange(1, 101)
class Hints:
def __init__(self, new_number):
self.new_number = new_number
self.choices = {
1: self.even_or_odd,
2: self.multiple3to5,
3: self.multiple6to10
}
def run(self,key):
action = self.choices.get(key)
action()
def even_or_odd(self):
if self.new_number % 2 == 0:
print('Hint. The number is even.')
else:
print('Hint. The number is odd.')
def multiple3to5(self):
for x in range(3, 6):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of {x}', end = ' ' )
else:
print("Well, Not a multple of 3 or 5")
def multiple6to10(self):
for x in range(6, 11):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of x {x}', end = ' ')
else:
print("Well, Not a multple of 6 or 10")
print('Guess a number beteen 1 and 100.')
hint = Hints(new_number)
print(new_number)
i = 3
win = False
while i >= 1 :
is_answer_given = False
while not is_answer_given:
try:
user_input = int(input(f'Attempt {i}: '))
is_answer_given = True
except ValueError:
print('Please enter a numerical value.')
if user_input == new_number:
print('You win!, Number is: {new_number}')
win = True
break
hint.run(i)
i -= 1
if not win:
print("You lost!")
print(f"Number is {new_number}")

Python 3-Returning a recursive value from a choice option and

I am having a touch of difficulty in getting my values to display using recursive methods. I am wanting to type in 10 numbers and, depending on the choice, will return the largest number, the smallest number, and the sum of the numbers. I am getting two errors: One is that the (len) cannot return an int and if I put in a value in the individual function, it will continue to loop until the program reaches it's parsing limit (999). I am not sure how to proceed and get the values I want and it seems to be a main issue with the values I put in. Any suggestions would be appreciated!
def displayMenu():
print('Enter 1 to find the largest number: ')
print('Enter 2 to find the smallest number: ')
print('Enter 3 to sum the list of numbers: ')
print('Enter 4 to exit: ')
choice = int(input('Please enter your choice: '))
while choice <= 0 or choice >= 5:
print('Enter 1 to find the largest number: ')
print('Enter 2 to find the smallest number: ')
print('Enter 3 to sum the list of numbers: ')
print('Enter 4 to exit: ')
choice = int(input('Please enter your choice: '))
else:
return choice
def main():
MIN = 1
MAX = 100
num_MAX = 10
user_num = []
number_list = []
for i in range(num_MAX):
user_num = int(input('Please enter a number at this time: '))
while user_num < 1 or user_num > 100:
user_num = int(input('Please re-enter numbers between 1 and 100:' ))
number_list.append(user_num)
choice = displayMenu()
while choice != 4:
if choice == 1:
largest = find_largest(user_num)
print('The largest number is: ', largest)
elif choice == 2:
smallest = find_smallest(user_num)
print('The smallest number is: ', smallest)
elif choice == 3:
summy = find_sum(user_num)
print('The sum of the numbers entered is: ', summy)
choice = displayMenu()
def find_largest(user_num):
n = len(user_num)
if n == 1:
return user_num[0]
else:
temp = find_largest(user_num[0:n - 1])
if user_num[n - 1] > temp:
return user_num[n - 1]
else:
return temp
def find_smallest(user_num):
n = len(user_num)
if n == 1:
return user_num [0]
else:
temp = find_smallest(user_num[0:n - 1])
if user_num[n - 1] < temp:
return user_num[n - 1]
else:
return temp
def find_sum(user_num):
user_num = [1,2,3,4]
n = len(user_num)
if len(user_num) == 1:
return user_num [0]
else:
return user_num[n - 1] + sum[0:n - 1]
main()

IndexError: string index out of range, the index is in the range

import random
four_digit_number = random.randint(1000, 9999) # Random Number generated
def normal():
four_digit = str(four_digit_number)
while True: # Data Validation
try:
guess = int(input("Please enter your guess: "))
except ValueError or len(str(guess)) > 4 or len(str(guess)) < 4:
print("Please enter a 4 digit number as your guess not a word or a different digit number")
else:
break
guess = str(guess)
counter = 0
correct = 0
while counter < len(four_digit):
if guess[counter] in four_digit:
correct += 1
counter += 1
if correct == 4:
print("You got the number correct!")
else:
print("You got " + str(correct) + " digits correct")
normal()
I don't understand why it says the index is not in range. When I use 0 instead of actually using counter it works. This only happens when I enter a value under 4 and when I enter a value over 4 the loop does not restart but it breaks out of the loop.
I would propose such a solution:
def normal():
four_digit = str(four_digit_number)
while True: # Data Validation
try:
guess = str(int(input("Please enter your guess: ")))
assert len(guess) == 4
except (ValueError, AssertionError):
print("Please enter a 4 digit number as your guess not a word or a different digit number")
else:
break
correct = sum(a == b for a, b in zip(four_digit, guess))
if correct == 4:
print("You got the number correct!")
else:
print("You got " + str(correct) + " digits correct")

Categories