I need to have the output look like this: "The sum of (num1) and (num2) is (num3) and (num1)>(num2)." or visa versa with which number is bigger. I cannot figure out how to append or join these strings together without getting error codes. The + and \ are not working to join them and I even tried to make another string with a new name for it and join them all together.
CODE:
num1 = int(input("Enter number 1:"))
num2 = int(input("Enter number 2:"))
num3 = num1 + num2
print (" The sum of", (num1))
print ("and", (num2))
print ("is:", (num3))
the_text = "".join([ "The sum of", (num1), "and", (num2), "=" (num3)])
if num1 > num2:
print ("The number", (num1))
print (">")
print (num2)
elif num2 > num1:
print ("The numer", (num2))
print (">")
print (num1)
else:
print (num1)
print ("=")
print (num2)
input ("Press enter to close.")
Assuming the language required is Python,
comparison_result = ""
if num1 > num2:
comparison_result = ">"
elif num1 < num2:
comparison_result = "<"
else:
comparison_result = "="
the_text = "The sum of " + str(num1) + " and " + str(num2) + " is " + str(num1 + num2) + " and " + str(num1) + comparison_result + str(num2)
You just need to typecast the int as str.
You can use formatting:
cmp_char = ""
if a > b:
cmp_char = ">"
elif a < b:
cmp_char = "<"
else:
cmp_char = "="
print "The sum of {} and {} is {} and {} {} {}".format(num1, num2, num3, num1, cmp_char, num2)
Related
This question already has an answer here:
Using a loop to create and assign multiple variables (Python) [duplicate]
(1 answer)
Closed 4 years ago.
This is some code I wrote for school. The problem is that it gets extremely long in two areas if I keep adding more "input" functions, the lines used and the number of "and" functions I use. It's so big, that it's making my school assignment page lag. If you wanted to do it with 7 numbers or more, then it would make my page lag even more. How do I simplify the code below?
Assignment: Write a program to input 6 numbers. After each number is inputted, print the biggest of the numbers entered so far.
num1 = int(input("Enter a number:"))
print ("Largest: " + str(num1) + "\n")
num2 = int(input("Enter a number:"))
if (num1 > num2):
print ("Largest: " + str(num1) + "\n")
else:
print ("Largest: " + str(num2) + "\n")
num3 = int(input("Enter a number:"))
if (num1 > num2 and num1 > num3):
print ("Largest: " + str(num1) + "\n")
elif (num2 > num3):
print ("Largest: " + str(num2) + "\n")
else:
print ("Largest: " + str(num3) + "\n")
num4 = int(input("Enter a number:"))
if (num1 > num2 and num1 > num3 and num1 > num4):
print ("Largest: " + str(num1) + "\n")
elif (num2 > num3 and num2 > num4):
print ("Largest: " + str(num2) + "\n")
elif (num3 > num4):
print ("Largest: " + str(num3) + "\n")
else:
print ("Largest: " + str(num4) + "\n")
num5 = int(input("Enter a number:"))
if (num1 > num2 and num1 > num3 and num1 > num4 and num1 > num5):
print ("Largest: " + str(num1) + "\n")
elif (num2 > num3 and num2 > num4 and num2 > num5):
print ("Largest: " + str(num2) + "\n")
elif (num3 > num4 and num3 > num5):
print ("Largest: " + str(num3) + "\n")
elif (num4 > num5):
print ("Largest: " + str(num4) + "\n")
else:
print ("Largest: " + str(num5) + "\n")
num6 = int(input("Enter a number:"))
if (num1 > num2 and num1 > num3 and num1 > num4 and num1 > num5 and num1 > num6):
print ("Largest: " + str(num1) + "\n")
elif (num2 > num3 and num2 > num4 and num2 > num5 and num2 > num6):
print ("Largest: " + str(num2) + "\n")
elif (num3 > num4 and num3 > num5 and num3 > num6):
print ("Largest: " + str(num3) + "\n")
elif (num4 > num5 and num4 > num6):
print ("Largest: " + str(num4) + "\n")
elif (num5 > num6):
print ("Largest: " + str(num5) + "\n")
else:
print ("Largest: " + str(num6) + "\n")
This can be done without any lists or special syntax as long as you use a simple loop to run the body six times:
largest = None
for _ in range(6):
number = int(input('Enter a number: '))
if largest is None or number > largest:
largest = number
print('Largest: {}\n'.format(largest))
If for some reason you're not allowed to use a loop, you can get the same result by manually unrolling the loop:
largest = int(input('Enter a number: '))
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
largest = number
print('Largest: {}\n'.format(largest))
number = int(input('Enter a number: '))
if number > largest:
largest = number
print('Largest: {}\n'.format(largest))
You can just store the number in a variable and overwrite it when your user enters a larger one.
awesome_number = 0
while True: # Always loop unless we break the loop.
userInput = int(input("Enter a number:")) # Your input phrase
# Compare values, evaluates to True if the user input is greater
if userInput > awesome_number:
awesome_number = userInput # Overwrite if compare evaluates to True
# Print using the .format method to dynamically insert the greatest
# number
print("So far, the biggest number you've entered is {}".format(awesome_number))
If you want to stop after n number of inputs, you could add a simple counter to count iterations.
awesome_number = 0
counter = 0
while True: # Always loop unless we break the loop.
userInput = int(input("Enter a number:")) # Your input phrase
# Compare values, evaluates to True if the user input is greater
if userInput > awesome_number:
awesome_number = userInput # Overwrite if compare evaluates to True
# Print using the .format method to dynamically insert the greatest
# number
print("So far, the biggest number you've entered is {}".format(awesome_number))
# Increment the counter
counter = counter + 1
if counter == 500: # Arbitrary number to end on
break
num1 = random.randint(1,20)
num2 = random.randint(1,20)
question = ["Bigger" , "Smaller"]
questiondecide = random.choice(question))
if questiondecide == "Higher":
userAnswer=input("Please find the Higher value between" + num1 "and" +
num2)
elif questiondecide == "Lower":
userAnswer=input("Please find the Lower value between" + num1 "and" +
num2)
I'm stuck on this point, I'm trying to figure out a way that if the code chooses Bigger/smaller
, the code will identify the bigger/smaller number generated and thus require the user to input the answer based on the question, but how do I identify if num1 or num2 is bigger or smaller and thus write a condition to award the user a point for answering correctly?
Basically want this: (Possible algorithm)
if set of numbers generated is higher
require user to input bigger number
userMarks = userMarks + 1
and so on if smaller number is asked, how do I write this down in Python?
import random
from random import randint
num1 = random.randint(1,20)
num2 = random.randint(1,20)
question = ["Bigger" , "Smaller"]
questiondecide = random.choice(question)
biggest = max(num1, num2)
smallest = min(num1, num2)
if questiondecide == "Bigger":
userAnswer = input("Please find the Higher value between " + str(num1) + " and " + str(num2) + ":" + "\n")
print(biggest)
if userAnswer == biggest:
print("This is the biggest number")
print("and you have chosen the bigger number!")
elif userAnswer == smallest:
print("This is the smallest number")
print("but you have not chosen the bigger number!")
elif questiondecide == "Smaller":
userAnswer = input("Please find the Lower value between " + str(num1) + " and " + str(num2) + ":" + "\n")
if userAnswer == biggest:
print("This is the biggest number")
print("but you have not chosen the smaller number!")
elif userAnswer == smallest:
print("This is the smallest number")
print("and you have chosen the smaller number!")
Hope this helps! Have any questions ask away!
I did a calculator code which works perfectly fine, but I need to append the results on a text file and/or read from the text file. I've done most of it but I'm having some errors which I need help with
-When I append the result, it just prints "5.098.042.0..." and it is supposed to be printing like this
"5 + 3 = 8
7 * 3 =43..."
It does show it in the code, but for some reason it just prints the result in the text
Please help, any suggestions to save work in the future or anything will be appreciated, thanks!
def menu():
print("\t1. Addition")
print("\t2. Substraction")
print("\t3. Multiplication")
print("\t4. Division")
print("\t5. Show")
print("\t6. Quit")
def option(min, max, exi):
option= -1
menu()
option= int(input("\n\t-> What would you like to calculate?: "))
while (option < min) or (option > max):
print("\n\t>>> Error. Invalid option.")
menu()
option= int(input("\n\t-> What would you like to calculate?: "))
return option
def add():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 + num2
print("\n\t-> The result of " + str(num1) + " + " + str(num2) + "= ", answer)
return answer
def subs():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 - num2
print("\n\t-> The result of " + str(num1) + " - " + str(num2) + "= ", answer)
return answer
def mult():
num1 = float(input("\tFirst number: "))
num2 = float(input("\tSecond number: "))
answer = num1 * num2
print("\n\t-> The result of " + str(num1) + " * " + str(num2) + "= ", answer)
return answer
def div():
num1 = float(input("\tFirst number: "))
num2 = float(input("\tSecond number: "))
if num2 != 0:
answer = num1 / num2
print("\n\t-> The result of " + str(num1) + " / " + str(num2) + "= ", answer)
else:
print("\n\t>>> Error. Division by zero.")
answer= "Error. Division by zero."
return answer
def result(r):
print("\n\t The last result was" , r)
def ex():
print("Goodbye")
def main():
solution = 0
op= -1
while op != 6:
op = option(0, 6, 0)
if op == 1:
solution = str(add())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 2:
solution = str(subs())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 3:
solution = str(mult())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 4:
solution = str(div())
with open ("myResultt.txt","a") as f:
f.write(solution)
elif op == 5:
with open ("myResultt.txt","r") as f:
for line in f:
print(line)
else:
solution = ex()
with open ("myResultt.txt","r") as f:
f.close()
main()
You prompt for the operands in the sum and etc... functions. If you want those operands to appear in the result file, you either have to return them along with the answer, or do the write in the function itself. For example,
def add():
num1 = float(input("\tEnter a number: "))
num2 = float(input("\tEnter a number: "))
answer = num1 + num2
result = "{} + {} = {}".format(num1, num2, answer)
print("\n\t-> The result of " + result)
with open ("myResultt.txt","a") as f:
f.write(result + "\n")
return answer
I'm creating program which will teach my little brother math. But for example, when program is saying 2 + 2, and I enter 4 it's saying "Incorrect!". What am I doing wrong?
import random
import math
def addition():
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
result = num1 + num2
guess = input(str(num1) + " + " + str(num2) + " = ")#this is the line with problem
if guess == result:
print("Correct!")
if guess != result:
print("Incorrect!")
addition()
result is an integer (e.g., 4), and the inputed guess is a string (e.g., '4'). You need to convert them to the same type in order to compare them. E.g.:
result = str(num1 + num2)
Wrap the answer to int
guess = int(input(str(num1) + " + " + str(num2) + " = "))
typecast the input to int:
import random
import math
def addition():
num1 = random.randint(1, 5)
num2 = random.randint(1, 5)
result = num1 + num2
guess = input(str(num1) + " + " + str(num2) + " = ")
guess = int(guess) #input is string and it must be typecast to int
if guess == result:
print("Correct!")
if guess != result:
print("Incorrect!")
addition()
I have a text file that has results listed like this:
Welcome to your results
The result of 50+25=75
The result of 60+25=85
The result of 70+25=95
The result of 80+25=105
I need python to read the file and pull out the numbers to the left of the "=" and add them up. I have no idea how to get this to work.
# take input from the user
print("Select operation.")
print("1.Display The Content of the result file")
print("2.Add two numbers")
print("3.Subtract two numbers")
print("4.Multiply two numbers")
print("5.Divide two numbers")
print("6.Append results to file")
print("7.Display Total of inputs")
print("8.Display Average of inputs")
print("9.Exit")
choice = input("Select an option(1-9):")
if choice == 1:
file = open('results.txt', 'r')
print file.read()
elif choice >= 2 and choice <= 5:
l_range = int(input("Enter your Lower range: "))
h_range = int(input("Enter your Higher range: "))
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 < l_range:
print "The input values are out side the input ranges \n Please check the numbers and try again"
elif num2 > h_range:
print "The input values are out side the input ranges \n Please check the numbers and try again"
else:
if choice == 2:
print "The result of", num1,"+", num2,"=", add(num1,num2)
resultstr = "The result of " + str(num1) + "+" + str(num2) + "=" + str(add(num1,num2))
elif choice == 3:
print "The result of", num1,"-",num2,"=", subtract(num1,num2)
resultstr = "The result of " + str(num1) + "-" + str(num2) + "=" + str(subtract(num1,num2))
elif choice == 4:
print "The result of", num1,"*", num2,"=", multiply(num1,num2)
resultstr = "The result of " + str(num1) + "*" + str(num2) + "=" + str(multiply(num1,num2))
elif choice == 5:
print "The result of", num1,"/", num2, "=", divide(num1,num2)
resultstr = "The result of " + str(num1) + "/" + str(num2) + "=" + str(divide(num1,num2))
if num2 == 0:
print "The result of", num1,"/", num2, "=", "You can't divide by zero!"
elif choice == 6:
print("The results have been appended to the file")
file = open('results.txt', 'a')
file.write(resultstr + "\n")
file.close()
elif choice == 7:
print ("Display total inputs")
elif choice == 8:
print ("Display average of total inputs")
elif choice == 9:
print ("Goodbye!")
else:
print("Invalid input")
lp_input = raw_input("Do you want to perform another action? Y/N:")
if lp_input == 'n':
print("Goodbye!")
From what I understand from the question, a simple regex match would solve the problem. You may do it like so:
Read the file line by line.
Make a regex pattern like so, to get the data from the string:
>>> pattern = "The result of (\d+?)[+-/*](\d+?)=(\d+).*"
Say if a line from the file is stored in the variable result:
>>> result = "The result of 25+50=75"
import the re library and use the match function like so which gives you the data from the string:
>>> s = re.match(pattern, result)
>>> print s.groups()
('25', '50', '75')
You can then get the numbers from this tuple and do any operation with it. Change the regex to suit your needs, but given the contents of the file at the start, this should be fine.