how to select a decimal in python? - python

I'm trying to make a simple flight plan helper for Microsoft Flight Simulator in Python and i'm trying to turn a number into time
EXAMPLE- if something equals more than 0.6 (hours) in decimals it would add a 1 and minus the 0.6
PROBLEM 2:
How do i restart the code after its finished a question?
APOLOGIES TO EVERYONE CONFUSED :D
print 'Hello and Welcome to Flight planner Helper V1'
print '-'
question_1 = raw_input('time or fuel? ')
if question_1 == 'time':
a = input('nautical miles ')
b = input('average ground speed ')
c = a / float(b)
print c # <--- PROBLEM 1
print 'Hours'
elif question_1 == 'fuel':
c = input('travel time ')
d = input('fuel usage (in litres)')
e = c * d
f = input('number of engines ')
g = e * f
print '%s litres' % (g)
else:
print 'your not a pilot, your a emu'
CLOSE = input('Press ENTER to close')

If c is in hours you can do something like:
hours = int(c)
minutes = int((c - hours) * 60)
seconds = int((c - hours - minutes / 60.0) * 3600))
print "%d:%d:%d" % (hours, minutes, seconds)
To repeat your code just wrap it in a loop like
while (True):
your code here
Or even better put your code into a function and just call the function from the loop.

There are some minor bugs in your code, but it's easy to sort them out:
import math
while True:
print 'Hello and Welcome to Flight planner Helper V1'
print '-'
question_1 = raw_input('time or fuel? ')
if question_1 == 'time':
a = input('nautical miles ')
b = input('average ground speed ')
c = float(a) / float(b)
print math.ceil(c), # <--- PROBLEM 1
print 'Hours'
elif question_1 == 'fuel':
c = raw_input('travel time ')
d = raw_input('fuel usage (in litres)')
e = float(c) * float(d)
f = raw_input('number of engines ')
g = float(e) * float(f)
print '%s litres' % (g)
else:
print 'your not a pilot, your a emu'
again = raw_input('New calculation? y/n ')
if again != "y": break
What do you mean with 0.6? Do you want to round up? math.ceil() does this.

You would need to add some sort of loop to the code so it can keep going / 'restart'.
Try adding a 'while' loop.
while True
Or any while loop you need.

Related

Cant get my code to generate enough fields for bingo

I need my program to generate as many playing fields as the entered number of players playing the game. Currently it only generates 1 field. Cant wrap my head around this one.
s = int(input("Sisesta mängijate arv: "))
b = int(input("Sisesta väjaku suurus: "))
b = b + 1
bb = b
c = int(input("Sisesta korrutustabeli suurus: "))
for s in range (1 , s+1):
numberolemas = ['0']
t.write(str(s) + ". väljak \n\n")
print(str(s) + ". väljak \n")
for bb in range (1 , bb):
for b in range (1 , b):
import random
number = random.randint(1, c) * random.randint(1, c)
olemas = True
while olemas:
number = random.randint(1, c) * random.randint(1, c)
if number not in numberolemas:
olemas = False
t.write(str(number))
print(str(number), end = ' ')
if number <= 9:
t.write(" ")
print(" ", end = '')
elif number >= 100:
t.write(" ")
print(" ", end = '')
else: t.write(" ") and print(" ", end = '')
numberolemas.append(number)
b = b + 1
t.write("\n\n")
print(" ")
bb = bb + 1
print(" ")
t.close() ```

Program for Internet Service Provider

I am writing an internet service provider program. My problem with the code is that it is not printing the monthly bill correctly.
For example:
If the user enters package "A" and num of hours used (say 9 hrs)
Then it should print 9.95 when the function printBill is called
My question: How can I call the data from getPackage() to the function printBill()
#Bill for Package A
def getPackageA(hours):
if (hours < 10):
return 9.95 #Cost of Package A
else:
return (hours-10)*2 + 9.95
#Bill for Package B
def getPackageB(hours):
if (hours < 20):
return 13.95 #Cost of Package B
else:
return (hours - 20) + 13.95
#Bill for Package C
def getPackageC():
return 19.95 #Cost of Package C
#Print Bill and savings
def printBill(bill):
if (bill != 0):
print("Your monthly bill is $", format(bill, '.2f'),
sep = '')
getSavings(bill)
print()
print()
else:
print()
#Checks and display savings if applicable
def getSavings(bill):
if(bill > getPackageA(hours)):
print("If you had package A, you'd save $",\
format(bill - getPackageA(hours),'.2f'), sep =
'')
if(bill > getPackageB(hours)):
print("If you had package B, you'd save $",\
format(bill - getPackageB(hours),'.2f'), sep =
'')
if(bill > getPackageC()):
print("If you had package C, you'd save $",\
format(bill - getPackageC(), '.2f'), sep = '')
def main():
bill = 1
#Asks user to enter choice of package and hours used
packageChoice = str(input("Enter package purchased (A,
B, or C): "))
hours = int(input("Enter the number of hours used: "))
if(packageChoice == 'A' or packageChoice == 'a'):
getPackageA(hours)
elif (packageChoice == 'B' or packageChoice == 'b'):
getPackageB(hours)
elif (packageChoice == 'C' or packageChoice == 'c'):
getPackageC()
else:
print("Package choice must be A, B, or C.")
printBill(bill)
main()
You can pass in multiple parameters to a function.
def printBill(bill)
becomes:
def printBill(bill,hours):
and you call it with:
printBill(bill,hours)
You will also have to pass it to getSavings in the same way.
You need to pass hours to every function that needs to use it, also when you RETURN something, it needs a place to get returned to. So you were saying if hours were < 10, return 9.95, but when you say return it sends the code back to the place it got called, you didnt assign this to a variable, so bill defaults to $1. Here is the updated code to work
#Bill for Package A
def getPackageA(hours):
if hours < 10:
return 9.95 #Cost of Package A
else:
return (hours-10)*2 + 9.95
#Bill for Package B
def getPackageB(hours):
if hours < 20:
return 13.95 #Cost of Package B
else:
return (hours - 20) + 13.95
#Bill for Package C
def getPackageC():
return 19.95 #Cost of Package C
#Print Bill and savings
def printBill(bill, hours):
if (bill != 0):
print("Your monthly bill is $", format(bill, '.2f'), sep='')
getSavings(bill, hours)
print('\n')
#Checks and display savings if applicable
def getSavings(bill, hours):
if bill > getPackageA(hours):
print("If you had package A, you'd save $",\
format(bill - getPackageA(hours),'.2f'), sep='')
if bill > getPackageB(hours):
print("If you had package B, you'd save $",\
format(bill - getPackageB(hours),'.2f'), sep='')
if bill > getPackageC():
print("If you had package C, you'd save $",\
format(bill - getPackageC(), '.2f'), sep='')
def main():
bill = 1
#Asks user to enter choice of package and hours used
packageChoice = str(input("Enter package purchased (A, B, or C): "))
hours = int(input("Enter the number of hours used: "))
if packageChoice in ('a', 'A') :
bill = getPackageA(hours)
elif packageChoice.lower() == 'b':
bill = getPackageB(hours)
elif packageChoice.upper() == 'C':
bill = getPackageC()
else:
print("Package choice must be A, B, or C.")
printBill(bill, hours)
main()
I also edited your main() function to show you different ways to check responses. You also don't need to wrap things in brackets in Python in IF statements.
To answer your question, you can simply do:
bill = 1
bill += getPackage() # call function and add return value to total bill
printBill(bill)

This Python code for a Custom Calculator was working now I broke it and I can't figure out where I went wrong

I had this working and now I cannot figure out what I did to make it not function the way I intend it to. When the program is called by the pyshell it asks the questions as it is supposed to but when the reply is given this is where it loses it mind. It was working and would call the function I have defined but now it will not do so.
I might just redefine the responses to use numbers instead of strings to make it easier and faster to complete the entries, but at the moment it is not working so there is no point in doing that until I can get it figured out.
The error is in the run_time() section, it is not calling the function as it should be, I might be missing something. I want it to call the function when the proper response is given.
I did try:
k = (query())
f = function_list[k]
f()
This did not worth either, so I am stuck. I appreciate any help.
def f_to_c():
temp = int(input("How warm is it out?"))
f_or_c = str(input("Is it C or F?"))
if f_or_c == 'c' or f_or_c == 'C':
updatedtemp = float(temp * 9 / 5 + 32)
print (updatedtemp, 'F')
elif f_or_c == 'f' or f_or_c == 'F':
updatedtemp = float((temp - 32) * 5 / 9)
print (updatedtemp, 'C')
def calc_trapezoid_area():
height = float(Input('What is the height of the trapezoid?'))
length1 = float(Input('What is the length of the bottom base?'))
length2 = float(Input('What is the length of the top base?'))
formula = float((1 / 2 * (length1 + length2)) * height)
print ("The area of the trapezoid is:", (formula))
def cal_circle():
pi = float(245850922 / 78256779)
rad_or_diam = str(input('Diameter or Radius?'))
width = float(input('What is the %s of your Circle?' % rad_or_diam))
if rad_or_diam == 'r' or rad_or_diam == 'R':
print (float(pi * width ** 2))
elif rad_or_diam == 'd' or rad_or_diam == 'D':
print (float(pi * width))
def query():
query = str(input('What would you like to calculate? Degrees, Trapezoids, or Circles?')).lower
function_list = {
"degrees": f_to_c,
"trapezoids": calc_trapezoid_area,
"circles": cal_circle
}
def run_time():
try:
f = function_list[query()]
f()
except KeyError:
print ("You messed up!")
if __name__ == '__main__':
while True:
run_time()
x = str(input('True or False?'))
if x == 'True':
break
There are two problems with your query function:
It doesn't return anything; and
It doesn't call lower.
Instead, try:
def query():
prompt = 'What would you like to calculate? Degrees, Trapezoids, or Circles?'
return input(prompt).lower()
Note the following:
input already returns a string, no need to call str();
You need to explicitly return the value; and
Parentheses () are required to actually call lower, otherwise you return the method itself.
Also, in f_to_c, "flaot" != "float".
Finally, you could improve your run_time function, minimising the amount of code in the try block:
try:
f = function_list[query()]
except KeyError:
print ("You messed up!")
else:
f()
This prevents a KeyError from f() being accidentally silenced.

Invalid Syntax Error in Temperature Conversion Program

Alright, so I was working on a simple temperature conversion program but am stuck on an error message I keep getting. Whenever I try to run the program, the F in the line, F = (C * 9/5 + 32), gets highlighted and a window pops up that states "invalid syntax". I have no idea what the issue could be so i'm hoping it's something simple one of you can point out for me. Thanks in advance!
#Menu Interface
def menu():
print("1. C to F")
print("2. F to C")
print("3. Quit")
# C to F
def CtoF():
C = float(input("Temperature in Celsius:")
F = (C * 9/5 + 32)
print (F,"degrees Fahrenheit")
# F to C
def FtoC()
F = float(input("Temperature in Fahrenheit:")
C = (F-32) * 5/9
print (C,"degrees Celsius")
def option():
loop = 1
while loop == 1:
o = input("Choose an option:")
if o = 1:
CtoF()
elif o = 2:
FtoC()
elif o = 3:
loop = 0
option()
You're missing an end parenthesis on your line
C = float(input("Temperature in Celsius:")

New Hangman Python

I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.

Categories