python program troubleshoot - python

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

Related

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}")

How to stop the list, missing number from user enter

I'm doing this exercise:
In your main function, you need to keep asking user to enter an
integer, then store those integers in a list. Once the user decides to
stop entering, the function should print out all the integers from the
list, and also find the largest number in that list. If the user did
not enter any number, you should print out “Your list is empty”.
I tried to code it but I got stuck on print "Your list is empty". I don't know where to put the statement.
And when the user enters the number, the list will come out missing the first number the user entered.
def main():
user_list = []
user_num = input('Enter an integer or enter x to stop: ')
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')
exit()
index = 0
while index < len(user_list):
user_list[index] = int(user_list[index])
index += 1
print ('Here is the list of the numberyou entered:')
print (*user_list, sep = '\n')
largest = max(user_list)
print ('The largest number in your listis: ',largest)
main()
Simple, change:
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')
exit()
To:
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' and user_num:
user_list.append(user_num)
elif not user_list:
print('Your List is empty')
exit()
else:
break
Here is the optimized code:
def main():
user_list = []
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' and user_num:
user_list.append(int(user_num))
elif not user_list:
print('Your List is empty')
exit()
else:
break
print ('Here is the list of the numbers you entered:')
print (*user_list, sep = '\n')
largest = max(user_list)
print ('The largest number in your list is: ', largest)
main()
if user_list == []:
print('Your List is empty')
exit()
You should write this portion outside the while loop. Like this
def main():
user_list = []
user_num = input('Enter an integer or enter x to stop: ')
while user_num != 'x':
user_num = input('Enter an integer or enter x to stop: ')
if user_num != 'x' :
user_list.append(user_num)
if user_list == []:
print('Your List is empty')
def main():
user_list = []
while True:
user_num = input('Enter an integer or enter x to stop: ')
if user_num == 'x':
break # exit the "while" loop
user_list.append(user_num)
# this is after the loop:
if user_list == []:
print('Your List is empty')
exit()
# user_list = list(map(int, user_list))
for index in range(len(user_list)): # range is a list-like thing of 0, 1, 2, 3... up to the length of the list
user_list[index] = int(user_list[index])
print ('Here is the list of numbers you entered:')
print (*user_list, sep='\n')
largest = max(user_list)
print ('The largest number in your lists: ', largest)
main()

Going back 2 step in nested loops

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()

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()

Categories