Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
another problem with code
#1
What is wrong with my code listed below? Thanks in advance for your assistance!

Instructions:
You are given three numbers as input. Write a program to perform the following operations:
Divide the first number by the second number and print the quotient.
Find the remainder when the first number is divided by the second number and print the result.
Raise the first number to the power of the third number and print the result.

My Code:
# Input: Get three numbers from the user
number1 = int(input(""))
number2 = int(input(""))
number3 = int(input(""))

# Divide the first number by the second number and print the quotient
quotient = number1 / number2
print("Quotient:", quotient)

# Find the remainder when the first number is divided by the second number and print the result
remainder = number1 % number2
print("Remainder:", remainder)

# Raise the first number to the power of the third number and print the result
power = number1 ** number3
print("Result:", power)
Larz60+ write Dec-23-2024, 10:43 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Tags added this post.
Reply
#2
You tell me. What numbers are you testing, and what incorrect results are you getting?
Reply
#3
Nothing wrong, all OK!

# Input: Get three numbers from the user
number1 = int(input("Enter the first number ... "))
number2 = int(input("Enter the second number ... "))
number3 = int(input("Enter the third number ... "))
print(f'The numbers are number1 = {number1}, number2 = {number2}, number3 = {number3}')

# Divide the first number by the second number and print the quotient
# quotient = number1 / number2
print(f"Quotient = {number1/number2}")

# Find the remainder when the first number is divided by the second number and print the result
# remainder = number1 % number2
print(f"Remainder = {number1 % number2}")

# Raise the first number to the power of the third number and print the result
# power = number1 ** number3
print(f"Result = {number1**number3}")
snippsat and zane108 like this post
Reply
#4
Thank you so much! This is brilliant!
Reply
#5
When you collect input, you should check it to make sure it has the format you require. There are various ways of checking that the input is a number. Sooner or later however, you will encounter the module re. Might as well learn how to use it, it's never too early to start!

import re

# people, like me, have fat fingers, things go wrong when typing, so check the input

""" Explanation of the regex
Look here for regex help: https://www.rexegg.com/regex-quickstart.php
\d = a digit in re
\d+ = 1 or more digits
. is significant in re you need to "escape it" with \
\. = look for a dot
| = logical OR in re
\Z = the end of a string
Overall this: \d+\.\d+|\d+\Z means: look for 1 or more numbers, followed by a . followed by 1 or more numbers
OR look for 1 or more numbers followed by the end of the string.
This: \d+\.\d+ will detect a float number like 1.4
This: \d+ will detect an integer like 33
Anything in the input that is not a number will cause res = None
"""

# re.match looks for a match at the beginning of the string
# so if you use match you do not need to specify the beginning of the string with \A or ^
e = re.compile(r'\d+\.\d+|\d+\Z')

a = 'a'
b = '1.4'
c = '12'
d = '1w2'

res = e.match(a)
res == None # returns True = input is not a number
res = e.match(b)
res == None # False, we have a result res = <re.Match object; span=(0, 3), match='1.4'>
res = e.match(c)
res == None # False, we have a result res = <re.Match object; span=(0, 2), match='12'>
res = e.match(d)
res == None #  returns True = input is not a number
zane108 likes this post
Reply
#6
Pedroski, thank you so much for explaining this to me! I appreciate you taking the time to do that. :)
Reply
#7
Trying to catch/check all input as Pedroski55 dos is a difficult task,and regex dos not make it easier
That way is called Look Before You Leap(LBYL) Style.
Can depend on situation often most advisable to use Easier to Ask Forgiveness Than Permission(EAFP) Style.
Can read more about here LBYL vs EAFP: Preventing or Handling Errors in Python

The it look like this.
def numbers():
    while True:
        try:
            number1 = int(input("Enter the first number ... "))
            number2 = int(input("Enter the second number ... "))
            number3 = int(input("Enter the third number ... "))
            return number1, number2, number3
        except ValueError:
            print("Invalid integer! Please try again.")

print(numbers())

# Unpack to singe numbers
#n1, n2, n3 = numbers()
Try now to type in anything and you see that only when three valid integer is input,will get a output.
Pedroski55 likes this post
Reply
#8
If in doubt, you should listen to snippsat, not me. He is a programmer, I just do this for fun.

I think regex expressions are very useful. How does the function int(number) know there is a ValueError? I don't know. Most probably by running a regex on number first, but you do not see that, it is hidden in the function int(number).

In Python, you cannot dynamically generate variables like number1, number2 and number3, In PHP you can do that because all variables begin with $, like $number1, $number2, $number3. So, in Python, if you want to collect more than 1 variable at a time, like number1, number2 and number3, you need to save them in an array, a list, or tuple.

I was thinking like this when I mentioned re above:

import re
# here the regex expression is divided into 2 groups by the brackets
# one group is for floating point numbers, the other for integers
e = re.compile(r'(\d+\.\d+)|(\d+)\Z')
# try any number-as-string here
res = e.match('1.44')
# see the results that we obtained
res.groups() # returns ('1.44', None)
res.group(1) # '1.44'
res.group(2) # returns nothing, which is None
res = e.match('144')
res.groups() # returns (None, '144')

# now you can collect floating point numbers or integers
def get_a_number():
    number = input("Enter the a number ... ")
    res = e.match(number)
    if res:
        if res.group(1):
            return float(number)
        elif res.group(2):
            return int(number)        
    else:
        print(f'Hey, Fat-fingers! Is this: {number} a number? Try again!')
        # return something, or else the function will return None if a number is not entered
        return "Mistake"

# a list to take the numbers       
my_numbers = []

while not len(my_numbers) == 3:
    anum = get_a_number()
    # only append numbers
    if not anum == "Mistake":
        my_numbers.append(anum)

# assign the variables
n1,n2,n3 = my_numbers
Just for fun! Merry Christmas!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020