Fraction Value Operations in Python 2.7 - python-2.7

I want to make a program where fraction values can be operated mathematically.
I've made a code but it show me an error.
TypeError: both arguments should be Rational instances.
print "We'll ask you for two fraction values."
print "After taking values from you, we'll use python built in operaters to make it happen."
from fractions import *
value_1_one = raw_input("Please enter 1st value : ")
value_1_two = raw_input("Please enter 1st two value : ")
value_2_one = raw_input("Please enter 2nd one value.")
value_2_two = raw_input("Please enter 2nd two value.")
vaule_1 = Fraction(value_1_one, value_1_two)
value_2 = Fraction(value_2_one, value_2_two)
print "We have %i and %i as values." % (value_one, value_two)
print "What kind of operation you would like to make."
print "Like Add, Sub, Multi, Devide"
op_kind = raw_input(">>>")
if "Add" in op_kind:
print (value_1 + value_2)
elif "Sub" in op_kind:
print (value_1 - value_2)
elif "Multi" in op_kind:
print (value_1 * value_2)
elif "Devide" in op_kind:
print (value_1 / value_2)
else:
print "Ask Mr. Ramanuj for further details."

Related

I want the User to be able to continue using the program. But Im still Sketchy using while loop

print'Free fall distance and velocity calculator'
g=9.81
def finalvelocity(t):
vf=g*t
return vf
def height(t):
h=0.5*g*t
return h
t=input('Enter the value of time in seconds: ')
print'What do you want to get?'
print'[1]. Final Velocity'
print'[2]. Height'
choice= input('Enter Selected Number: ')
if choice==1:
print 'Answer is', finalvelocity(t),'meter per second'
if choice==2:
print 'Answer is', height(t), 'meters'
if choice>2:
print 'Invalid Selection'
if choice<1:
print 'Invalid Selection'
for choice in range(choice>2):
n=raw_input('Do you want to continue?[y]yes/[n]no: ')
while True:
t=input('Enter the value of time in seconds: ')
print'What do you want to get?'
print'[1]. Final Velocity'
print'[2]. Height'
choice= input('Enter Selected Number: ')
if choice==1:
print 'Answer is', finalvelocity(t),'meter per second'
if choice==2:
print 'Answer is', height(t), 'meters'
if choice>2:
print 'Invalid Selection'
if choice<1:
print 'Invalid Selection'
if n==n:
break
Thanks for updating your question. You can use infinite loops to run the program again and again until the user wishes to exit. A super simple example of this would be:
while True:
t = raw_input("Do you want to exit? y/n: ")
if t == 'y':
break
else:
print "You stayed!"
As for your code, here's how you'd make it run infinite times. Note how if the user selects 'No' the code breaks out of the loop to exit the program.
print 'Free fall distance and velocity calculator'
g = 9.81
def finalvelocity(t):
vf = g*t
return vf
def height(t):
h = 0.5*g*t
return h
# Start an infinite loop of user input until they exit
while True:
# Ask for time
t = input('Enter the value of time in seconds: ')
# Ask for query type
print'What do you want to get?'
print'[1]. Final Velocity'
print'[2]. Height'
choice= input('Enter Selected Number: ')
# Perform calculations
if choice==1:
print 'Answer is', finalvelocity(t), 'meter per second'
if choice==2:
print 'Answer is', height(t), 'meters'
else:
print 'Invalid Selection'
# Offer the user a chance to exit
n = raw_input('Do you want to calculate another? [y]yes/[n]no: ')
if n == 'n':
# User wants to exit
break # Break out of the infinite loop

Input validation python 2.7.13

I am trying to validate input that is going into a list. The input needs to be an integer. How I have it works if I input an integer or a single letter. but if I enter something like 'qw' the program crashes. What can I do to better validate the input? Here is my code:
def getPints(pints):
counter = 0
while counter < 7:
pints[counter] = raw_input("Enter the number of pints donated: ")
check = isinstance(pints[counter], int)
while check == False:
print "Please enter an integer!"
pints[counter] = input("Enter the number of pints donated: ")
counter = counter + 1
As written, check will always evaluate to False, because raw_input() only returns a string, never an integer. Then you'll get stuck in an infinite while loop, because you don't update check in it.
Instead of isinstance, use the string isdigit() method.
check = pints[counter].isdigit()
You'll also need to re-evaluate check inside the loop. But really, you don't need check at all.
pints[counter] = raw_input("Enter the number of pints donated: ")
while not pints[counter].isdigit():
print "Please enter an integer!"
pints[counter] = raw_input("Enter the number of pints donated: ")
I suspect you also want to convert pints[counter] to an int once you have a suitable input.
You're using the LBYL method (Look Before You Leap). You can also use the EAFP (Easier to Ask Forgiveness than Permission) method by just trying to convert the input to an int and catching the exception if the input is bad:
while True:
try:
pints[counter] = int(raw_input("Enter the number of pints donated: "))
break
except ValueError:
print "Please enter an integer!"

Python: Trying to loop through a string to find matching characters

I am trying to create a simple "guess the word" game in Python. My output is something like:
String: _____ _____
Guess a word: 'e'
String:_e__o __e_e
Guess a word: 'h'
(and so on)
String: hello there
I have a function to do this, and within this function I have this code:
def guessing(word):
count = 0
blanks = "_" * len(word)
letters_used = "" #empty string
while count<len(word):
guess = raw_input("Guess a letter:")
blanks = list(blanks)
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz "):
print "Please only guess letters!"
#Checks if guess is found in word
if guess in word and guess not in letters_used:
x = word.index(guess)
for x in blanks:
blanks[x] = guess
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-counter
print "There are", str(word.count(guess)) + str(guess)
guess is the raw input I get from the user for a guess, and letters_used is just a collection of guesses that the user has already input. What I'm trying to do is loop through blanks based on the word.index(guess). Unfortunately, this returns:
Guess a letter: e
e___
Yes, there are 1e
Help would be much appreciated!
Your code was almost correct. There were few mistakes which I have corrected:
def find_all(needle, haystack):
"""
Finds all occurances of the string `needle` in the string `haystack`
To be invoked like this - `list(find_all('l', 'hello'))` => #[2, 3]
"""
start = 0
while True:
start = haystack.find(needle, start)
if start == -1: return
yield start
start += 1
def guessing(word):
letters_uncovered_count = 0
blanks = "_" * len(word)
blanks = list(blanks)
letters_used = ""
while letters_uncovered_count < len(word):
guess = raw_input("Guess a letter:")
#Checks if guesses are valid
if len(guess) != 1:
print "Please guess only one letter at a time."
elif guess not in ("abcdefghijklmnopqrstuvwxyz"):
print "Please only guess letters!"
if guess in letters_used:
print("This character has already been guessed correctly before!")
continue
#Checks if guess is found in word
if guess in word:
guess_positions = list(find_all(guess, word))
for guess_position in guess_positions:
blanks[x] = guess
letters_uncovered_count += 1
letters_used += guess
print ("".join(blanks))
print "Number of misses remaining:", len(word)-letters_uncovered_count
print "There are", str(word.count(guess)) + str(guess)
else:
print("Wrong guess! Try again!")

How to sort a list from user input?

I've been trying to make this work for some time now and I can't seem to get my list to sort out in ascending order. My program asks the user to enter three integers and then outputs results and is supposed to sort the numbers entered from least to greatest. However, whenever I try to sort it, it does not sort it the way I want to do. I've tried several ways of modifying the sort method, but it still does not work. For example, if I enter in 2, 10, and 5 as my three numbers, it will display it as "List: [2, 10, 5]".
import math
print ("")
print ("Welcome to my program!")
print ("")
v1 = input("Enter the first number: ")
print ("")
v2 = input("Enter the second number: ")
print ("")
v3 = input("Enter the third number: ")
print ("")
#tried to sort list here
list1 = [int(v1), int(v2), int(v3)]
sorted(list1, key=int)
sum = int(v1) + int(v2) + int(v3)
product = int(v1) * int(v2) * int(v3)
integer = int(v1)//int(v2)
mod = float(v1) % float(v2)
average = (float(v1) + float(v2) + float(v3))/ 3
star= "*"
print ("------------------")
print (" RESULTS ")
print ("------------------")
print ("")
print ("Sum: " + str(sum))
print ("")
print ("Product: " + str(product))
print ("")
print ("Integer Division: "+ str(integer))
print ("")
print ("Mod: " + str(mod))
print ("")
print ("Maximum Number: ", max(list1))
print ("")
print ("Minimum Number: ", min(list1))
print ("")
print ("Average: " + str(average))
print ("")
#outputs the list
print ("List: " + str(list1))
print ("")
print (v1 + " " + "".join([star] * int(v1)))
print (v2 + " " + "".join([star] * int(v2)))
print (v3 + " " + "".join([star] * int(v3)))
You need to assign to the sorted output:
srted = sorted(list1) # creates a new list
To sort the original list sorting in place use list.sort:
list1.sort() # sorts original list
You don't need to pass a key to sort ints.
sorted returns a value that you must reassign and the key is unnecessary:
list1 = [int(v1), int(v2), int(v3)]
list1 = sorted(list1)
Alternatively, you can call the sort method of the list which directly modifies it without return and reassignment:
list1 = [int(v1), int(v2), int(v3)]
list1.sort()

Python's min() function does not work with raw_input converted to float

[Running on Xubuntu 12.04 LTS, Python 2.7]
Hey. I am struggling a bit with this assignment. It is from book about learning Python but I am probably missing something here. I do not require complete answer but a hint what should I do would be much better than copy/paste it.
My goal now is to create code that counts Smallest number so far from all the user inputs. I know that it has to do something with an impossibility of using min() and "for loops" for float numbers/single numbers as it is necessary to have some list but I do not have any idea what to do now..
Count = 0
Total = 0
Smallest = None #Or maybe I should use something like Smallest = []?
while True:
user = raw_input("Enter number, when you are finished enter done or press enter: ")
if len (user) < 1: break
if user == "done":
print "Done entered, program executed!"
break
try:
fuser = float(user)
print "Valid input.", "Your input:", fuser
except:
print "Invalid input.", "Your input:", user
continue
Count = Count + 1
Total = Total + fuser
#Smallest = None
#for i in [Total]:
#if Smallest is None or itervar < Smallest:
#Smallest = i
# As you can see I've been simply trying to find some way (code with # obviously doesn't work at all...)
#print "Min: ", Smallest
print "Count: ",Count
print "Total number: ",Total
try:
print "Average:", Total/Count
except:
print "NOT AVAILABLE"
Thank you very much for tips and hints on what to do next.
The easiest way may be:
Smallest = []
...
Smallest.append( float( user ) )
and then the total is sum( Smallest ), the smallest is min( Smallest ) and the number is len( Smallest ). You are storing all the intermediate values, which is not really necessary, but I think here is the simplest.