I am a beginner in Python and I think I need some help with my program. Any kind of help or advice would be appreciated:)
You can see the program below, when I run it it gets stuck on the part of comparing the random ticket with the winning ticket(win_combination).
from random import choice
#Winning ticket
win_combination = input("Enter the winning combination of 4 numbers(1-digit-numbers): ")
while len(win_combination) != 4:
if len(win_combination) > 4:
win_combination = input("Reenter a shorter combination(4 one-digit-numbers): ")
elif len(win_combination) < 4:
win_combination = input("Reenter a longer combination(4 one-digit-numbers): ")
print(f"Winning combination is {win_combination}.")
#Specifying range of numbers to choose from
range = range(0, 10)
#Making a fake comparison-ticket to start of the loop
random_ticket = [0, 0]
random_ticket_string = f"{random_ticket[0]}{random_ticket[1]}{random_ticket[2]}{random_ticket[3]}"
#Params for the loop
n_tries = 0
n_guesses = 1
while random_ticket_string != win_combination:
while n_tries > 4:
random_ticket.clear()
number = choice(range)
random_ticket.append(number)
n_tries += 1
n_guesses += 1
random_ticket_string = f"{random_ticket[0]}{random_ticket[1]}"
if random_ticket_string == win_combination:
chance_to_win = f"{(1 / n_guesses) * 100}%"
print("Estimated percent to win is " + chance_to_win + ", it took " + f"{n_guesses} to match the winning combination.")
else:
n_tries = 0
When I input my number or anything else, it just skips the if statement and goes to the else. I can't figure out what's wrong; I've tried every way to change it. Still a total noob here.
arv = input("Sisestage arv: ")
arv1 = 0
kordus = 1
while kordus <= 10:
arv = input("Sisestage arv: ")
if arv == arv.isnumeric():
arv1 + arv
print (arv1)
kordus += 1
else:
print (arv)
break
You do not need to check if arv == arv.isnumeric(). arv.numeric() returns a boolean (True or False). To add a number to a variable you need += not just +. Here is your fixed code:
arv = input("Sisestage arv: ")
arv1 = 0
kordus = 1
while kordus <= 10:
arv = input("Sisestage arv: ")
if arv.isnumeric():
arv1 += int(arv)
print (arv1)
kordus += 1
else:
print (arv)
break
You can use the isinstance() function to check if the input is an int or not
arv1 = 0
kordus = 1
while kordus <= 10:
arv = eval(input("Sisestage arv: "))
if isinstance(arv, int):
arv1 += arv
print(arv1)
kordus += 1
else:
print(arv)
print(arv1)
break
This is a very basic program. It stores the student data and then displays the student name with the highest marks.
Ignoring the time complexity for my code, how can I format my code in such a way that it uses less while loops.
student_names, test_1, test_2, test_3, total_score = [], [], [], [], []
i = 0
while i < 30:
student = input("Student: ").title()
student_names.append(student)
while True:
test1 = int(input("Test-1 score: "))
if 0 <= test1 <= 20:
test_1.append(test1)
break
else:
print("Range Error for Test1 Score :( ")
while True:
test2 = int(input("Test-2 score: "))
if 0 <= test2 <= 25:
test_2.append(test2)
break
else:
print("Range Error for Test2 Score :( ")
while True:
test3 = int(input("Test-3 score: "))
if 0 <= test3 <= 35:
test_3.append(test3)
print('')
break
else:
print("Range Error for Test3 Score :( ")
total = test_1[i] + test_2[i] + test_3[i]
total_score.append(total)
max_score = total_score[0]
if total_score[i] > max_score:
max_score = total_score[i]
i += 1
avg_score = 0
for i in range(30):
avg_score += total_score[i]
print(f"Average Score: {avg_score/3}")
print(f"{student_names[total_score.index(max_score)]} scored Highest of {max_score}/{35+25+20}")
You can factor the duplicated input validation code.
def input_int(name, max_score):
while True:
x = int(input(name))
if 0 <= x <= max_score:
return x
else:
print('Range error for %s :(' % name)
and then in your code:
test_1.append(input_int('Test 1 Score', 20))
test_2.append(input_int('Test 2 Score', 25))
test_3.append(input_int('Test 3 Score', 35))
Here's my code:
def ispalindrome(p):
temp = p
rev = 0
while temp != 0:
rev = (rev * 10) + (temp % 10)
temp = temp // 10
if num == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (palindrome(i) == True):
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
I believe my ispalindrome() function works. I'm trying to figure out what's wrong inside my while loop.
here's my output so far:
n = 1 answer = 1,
n = 2 answer = 22,
n = 3 answer = 333 ...
I also think the runtime on this really sucks
Please help
i belive the problem is with your ispalindrom functon it returns 200 as palindrome number
def ispalindrome(p):
rev = int(str(p)[::-1])
if p == rev:
return True
else:
return False
num = int(input("Enter a number: "))
i = 1
count = 0
sum = 0
while (count <= num - 1):
if (ispalindrome(i) == True):
print(i)
sum = sum + i
count = count + 1
i = i + 1
print("Sum of first", num, "palindromes is", sum)
def is_palindrome(number):
return str(number) == str(number)[::-1]
num = int(input("Enter a number: "))
palindromes = [i for i in range(1, num) if is_palindrome(i)]
print(f"Sum of the {len(palindromes)} palindromes in range {num} is {sum(palindromes)}")
I decided to make a calculator as a project.
Implementing basic addition, subtraction, division, and multiplication was fairly easy.
I wanted to add more functionality so I decided to implement a list of results the user view. However, I had a difficult time keeping track of the results numerically. I wrote a maze of if statements that are functional but seem to be overwrought with code. I am sure there is a better way to handle this.
Any advice?
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
value = None
while True:
try:
value = x / y
break
except ZeroDivisionError:
print('Value is not dividable by 0, try again')
break
return value
def num_input(prompt='Enter a number: '):
while True:
try:
print(prompt, end='')
x = int(input())
break
except ValueError:
print('You must input a number. Try again.')
return x
def get_two_val():
x, y = num_input(), num_input()
return x, y
print("Welcome to Simple Calc")
# declaration of variables
num_of_calc_counter = 0
index_of_calc = 1
calculations = []
while True:
print("Choose from the following options:")
print(" 1. Add")
print(" 2. Subtract")
print(" 3. Multiply")
print(" 4. Divide")
print(" 5. Sales Tax Calculator")
print(" 6. Recent Calculations")
print(" 0. Quit")
usrChoice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if usrChoice is 1:
numbers = get_two_val()
result = add(*numbers)
print(numbers[0], "plus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 2:
numbers = get_two_val()
result = sub(*numbers)
print(numbers[0], "minus", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 3:
numbers = get_two_val()
result = mul(*numbers)
print(numbers[0], "times", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 4:
numbers = get_two_val()
result = div(*numbers)
print(numbers[0], "divided by", numbers[1], "equals", result)
calculations.extend([result])
num_of_calc_counter += 1
elif usrChoice is 5:
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
#
elif usrChoice is 6:
if len(calculations) is 0:
print('There are no calculations')
elif num_of_calc_counter == 0:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif index_of_calc == num_of_calc_counter:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif num_of_calc_counter > index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter -= 1
elif num_of_calc_counter < index_of_calc:
index_of_calc = 1
for i in calculations:
print(index_of_calc, i)
index_of_calc += 1
num_of_calc_counter += 1
elif usrChoice is 0:
break
I don't know if you could find this simpler:
def num_input(prompt='Enter a number: '):
finished = False
while not finished:
string_input = input(prompt)
try:
input_translated = int(string_input)
except ValueError:
print('You must input a number. Try again.')
else:
finished = True
return input_translated
def division_operation(x, y):
if y == 0:
print('Value is not dividable by 0, try again')
return None
else:
return x / y
math_operations_values = [
(lambda x, y: x + y, 'plus'),
(lambda x, y: x - y, 'minus'),
(lambda x, y: x * y, 'times'),
(division_operation, 'divided by')
]
def get_two_val():
return (num_input(), num_input())
def operate_on_numbers(operation_index):
def operate():
numbers = get_two_val()
operator, operation_string = math_operations_values[operation_index]
result = operator(*numbers)
if result is not None:
print(numbers[0], operation_string, numbers[1], "equals", result)
calculations.append(result)
return operate
def tax_computation():
tax_rate = .0875
price = float(input("What is the price?: "))
total_tax = tax_rate * price
final_amount = total_tax + price
print('Tax rate: ', tax_rate * 100, '%')
print('Sales tax: $', total_tax)
print('_____________________________')
print('Final amount: $', final_amount)
def show_computations():
if calculations:
for (index, values) in enumerate(calculations, start=1):
print(f'{index}: {values}')
else:
print('There are no calculations')
calculations = []
finished = False
choices_actions = [
operate_on_numbers(0),
operate_on_numbers(1),
operate_on_numbers(2),
operate_on_numbers(3),
tax_computation,
show_computations
]
while not finished:
print("""
Choose from the following options:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Sales Tax Calculator
6. Recent Calculations
0. Quit""")
user_choice = num_input('Enter your choice: ')
'''
Menu workflow
options 1-4 take in two numbers and perform the specified calculation and
then add the result to a master list that the user can reference later.
lastly, the workflow increments the num_of_calc variable by 1 for recent
calc logic
option 5 is a simple tax calculator that needs work or option to enter
or find tax rate
option 6 returns a list of all the calculations perform by the user
'''
if user_choice == 0:
finished = True
else:
try:
operation_to_do = choices_actions[user_choice - 1]
except IndexError:
print('Please enter one of choice shown.')
else:
operation_to_do()