So I've been trying to get this code to run:
def conference_call_discount(distance, basic_charge):
if(distance >= 50):
con_calc = basic_charge * 0.5
return con_calc
elif(distance < 50):
con_calc = 0
return con_calc
con_call = str(input("Is it a conference call? "))
from call_charge_functions import conference_call_discount
conference = conference_call_discount(dist, starting_cost)
if con_call == y:
print("your conference call discount is", conference)
else:
conference = 0
However I keep getting this error:
NameError: name 'y' is not defined
I don't know what's wrong
in this if:
if con_call == y:
You didn't set the value for y.
You should set a value for the y variable before comparing it.
Related
I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]
I'm learning to program with python and I came across this issue: I'm trying to make a Guessing Game, and while trying to check for the win condition, the function doesn't recognise the input variable, which I made sure I returned with a previous function. So i get the 'name << 'first_input' is not defined' >> error. I thought it had something to do with the variable not being global or sth like that.
import random
ran_int = random.randint(1,100)
guesses = 0
# here you input the number and it keeps asking unless you do so with 1 to 100
def ask():
first_input = 0
while first_input < 1 or first_input > 100:
first_input = int(input('Enter a number between 1 and 100: '))
return first_input
# this is just to increment the number of guesses stored for showing at the end # of the game
def guesses_inc():
global guesses
guesses += 1
return guesses
# here is where i get the error, as if my ask() function didn't return
# the value properly or as if I assigned it wrongly
def check_win_1():
if first_input == ran_int:
guesses_inc()
print(f'BINGO!\nYou guessed correctly after {guesses} times.')
elif (abs(ran_int - first_input) <= 10):
guesses_inc()
print('WARM!')
ask2()
elif first_input < 1 or first_input > 100:
print('Out of bounds!')
ask2()
else:
guesses_inc()
print('COLD!')
ask2()
ask()
check_win_1()
And here is the error
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-11-bfd5497995df> in <module>
----> 1 check_win_1()
NameError: name 'first_input' is not defined
I didn't paste the whole code because while testing it it returned the error at this stage so I didn't think the rest mattered for this particular problem. I tried making the var input global and stuff like that but i don't think I did it properly.
Your method call is not correct. You should call your functions like this
def check_win_1(first_input):
if first_input == ran_int:
guesses_inc()
print(f'BINGO!\nYou guessed correctly after {guesses} times.')
elif (abs(ran_int - first_input) <= 10):
guesses_inc()
print('WARM!')
ask2()
elif first_input < 1 or first_input > 100:
print('Out of bounds!')
ask2()
else:
guesses_inc()
print('COLD!')
ask2()
first_input = ask()
check_win_1(first_input)
The error is there because you are trying to use first_input somewhere (i.e. inside check_win_1()).
A possible, not recommended, solution is to qualify your variable as global, which should be used VERY sparingly.
Instead, it is recommended to use function parameters, so as to encapsulate your code in self-contained blocks, e.g.:
def func(a, b):
return a + b
x = func(10, 5)
rather than:
def func():
global a, b
return a + b
a = 10
b = 5
x = func()
For your that may mean doing something like:
def check_win_1(first_input, ran_int):
...
and use them accordingly, e.g.:
first_input = ask()
check_win_1(first_input, ran_int)
etc.
EDIT
Following the above principle, your code could have looked like:
import random
MIN_VAL = 1
MAX_VAL = 100
WARM_LIMIT = 10
def ask_number(
min_val=MIN_VAL,
max_val=MAX_VAL):
guess = None
while guess is None:
guess = int(input(f'Enter a number between {min_val} and {max_val}: '))
if guess < min_val or guess > max_val:
print('Out of bounds!')
guess = None
return guess
def check_guess(
guess,
target,
num_guesses,
warm_limit=WARM_LIMIT):
if guess == target:
print(f'BINGO!\nYou guessed correctly after {num_guesses} times.')
return True
else:
if (abs(guess - target) <= warm_limit):
print('WARM!')
else:
print('COLD!')
return False
# : main
target = random.randint(MIN_VAL, MAX_VAL)
num_guesses = 0
won = False
while not won:
guess = ask_number()
num_guesses += 1
won = check_guess(guess, target, num_guesses)
I was trying to make it so that my program will keep asking the user to input a certain value and if the user doesn't it keeps asking until they do.
I tried to use "while" instead of "if" but I know I'm probably missing something, somewhere.
def terrain(surface):
surface = raw_input("What surface will you be driving on? ")
if surface == "ice":
u = raw_input("what is the velocity of the car in meters per second? ")
u = int(u)
if u < 0:
u = raw_input("Velocity must be greater than 0")
return
if u == 0:
u = raw_input("Velocty must be a number greater than zero")
return
a = raw_input("How quickly is the vehicle decelerating? ")
a = int(a)
if a > 0:
print ("Deceleration cannot be a positive integer")
return
else:
s1 = u**2
s2 = 2*.08*9.8
s = s1/s2
print "This is how far the vehicle will travel on ice: "
print ("The vehicle will travel %i meters before coming to a complete stop" % (s))
terrain("ice")
The problem is you are using return after checking the condition which causes the function to return None you have to use break instead of return with while loop instead of if to achieve this. A better way to validate and get data is below
class ValidationError(Exception):
pass
def validate_and_get_data_count(x):
if int(x) < 0:
raise ValidationError("Cannot be less than 0")
return int(x)
def validate_and_get_data_name(x):
if len(x) < 8:
raise ValidationError("Length of name cannot be less than 8 chars")
elif len(x) > 10:
raise ValidationError("Length of name cannot be greater than 10 chars")
return x
validators = {
"count": validate_and_get_data_count,
"name": validate_and_get_data_name
}
data = {}
params = [
("count","Please enter a count: "),
("name","Please enter a name: "),
]
for param in params:
while True:
x = input(param[1])
try:
data[param[0]] = validators[param[0]](x)
break
except ValidationError as e:
print(e)
print(data)
What the above code does is for every param in params list it runs a while loop checking for every validation condition defined in its validator if valid it breaks the while loop and proceeds to next param and repeats the same process again
Hi having trouble trying to fix an error that occurs when I put just a '#' or rogue value in case someone doesn't want to add any data. I don't know how to fix it and I'm hoping to just end the code just like I would with data.
#Gets Data Input
def getData():
fullList = []
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
while inputText != "#":
nameList = []
nameList2 = []
nameList = inputText.split()
nameList2.extend((nameList[0],nameList[1]))
nameList2.append((float(nameList[2]) + float(nameList [3]))/2)
fullList.append(nameList2)
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
print("\n")
return fullList
#Calculates Group Average
def calc1(fullList):
total = 0
for x in fullList:
total = total + x[2]
groupAverage = total/(len(fullList))
return(groupAverage)
#Finds Highest Average
def calc2(fullList):
HighestAverage = 0
nameHighAverage = ""
for x in fullList:
if x[2] > HighestAverage:
HighestAverage = x[2]
nameHighAverage = x[0] + " " + x[1]
return (HighestAverage, nameHighAverage)
#Returns Marks above average
def results1(groupAverage,r1FullList):
r1FullList.sort()
print("List of students with their final mark above the group average")
print("--------------------------------------------------------------")
print("{:<20} {:<12}".format("Name","Mark"))
for x in r1FullList:
if x[2] > groupAverage:
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f}".format(name,x[2]))
def calc3(x):
if x[2] >= 80:
return 'A'
elif x[2] >= 65:
return 'B'
elif x[2] >= 50:
return 'C'
elif x[2] < 50:
return 'D'
else:
return 'ERROR'
def results2(fullList):
print("List of Studens with their Final Marks and Grades")
print("-------------------------------------------------")
print("{:<20} {:<12} {:<12}".format("Name","Mark","Grade"))
for x in fullList:
grade = calc3(x)
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f} {:<12}".format(name,x[2],grade))
#Checks for boundary and invalid data
def checkInput(question):
while True:
textInput = input(question)
if textInput == "#":
return textInput
splitList = textInput.split()
if len(splitList) !=4:
print("Invalid Format, Please Try Again")
continue
try:
a = float(splitList[2])
a = float(splitList[3])
if float(splitList[2]) < 0 or float(splitList[2]) > 100:
print("Invalid Format, Please Try Again")
continue
if float(splitList[3]) < 0 or float(splitList[3]) > 100:
print("Invalid Format, Please Try Again")
continue
return(textInput)
except ValueError:
print("Invalid Input, Please Try Again")
continue
#Main Program
#Input Data
fullList = getData()
#Process Data
groupAverage = calc1(fullList)
HighestAverage, nameHighAverage = calc2(fullList)
#Display Results
print("The group average was %.2f" % groupAverage)
print("The student with the highest mark was: %s %0.2f" %(nameHighAverage,HighestAverage))
results1(groupAverage,fullList)
print("\n")
results2(fullList)
Your program works OK for me, unless you enter a # as the first entry, in which case fullList is [] and has length 0. Hence, DivisionByZero at this line: groupAverage = total/(len(fullList)).
You could modify your code to check for this and exit:
import sys
fullList = getData()
if not fullList:
print('No Data!')
sys.exit()
I am having trouble getting this binary sort to work. I get syntax errors at lower_bound and in other places. I know it is something obvious but I am getting to the desk flipping point. Can someone help me to get this to run clearly, I know this is basic stuff but I am fairly new to this.
def main():
sortNames()
binarySearch()
def sortNames():
global names
names = ["Chris Rich", "Ava Fischer", "Bob White", "Danielle Porter", "Gordon Pike", "Hannah Beauregard", "Matt Hoyle", "Ross Harrison", "Sasha Ricci", "Xavier Adams"]
names.sort()
def binarySearch():
global names, found, nameSearch, lower_bound, middle_pos, upper_bound
nameSearch = string(input("What name are you looking for?")
lower_bound = 0
upper_bound = len(names)-1
found = False
while lower_bound <= upper_bound and not found:
middle_pos = (lower_bound+upper_bound) // 2
if name_list[middle_pos] < nameSearch:
lower_bound = middle_pos + 1
elif name_list[middle_pos] > nameSearch:
upper_bound = middle_pos - 1
else:
found = True
if found:
print("The name is at position", middle_pos)
else:
print("The name was not in the list.")
main()
You forgot to add the last closing parenthesis on the preceding line:
nameSearch = string(input("What name are you looking for?")
# 1--^ 2--^ 2--^
Also, you didn't define the function string(). Not that it is needed, input() returns a string already.
After that, I see an error for name_list, but presumably you have that list defined outside of the code posted here.
names = ["Chris Rich", "Ava Fischer", "Bob White",\
"Danielle Porter", "Gordon Pike", "Hannah Beauregard",\
"Matt Hoyle", "Ross Harrison", "Sasha Ricci", "Xavier Adams"]
def sortNames():
global names
names.sort()
def binarySearch():
global names, found, nameSearch, lower_bound, middle_pos, upper_bound
nameSearch = raw_input("What name are you looking for?")
lower_bound = 0
upper_bound = len(names)-1
found = False
while lower_bound <= upper_bound and not found:
middle_pos = (lower_bound+upper_bound) // 2
if names[middle_pos] < nameSearch:
lower_bound = middle_pos + 1
elif names[middle_pos] > nameSearch:
upper_bound = middle_pos - 1
else:
found = True
if found:
print("The name is at position", middle_pos)
else:
print("The name was not in the list.")
def main():
sortNames()
binarySearch()
if __name__ == "__main__":
main()
Output
anukalp#anukalp-Latitude-E6400:~$ python del1.py
What name are you looking for?Ross Harrison
('The name is at position', 7)