How to write if statements to print various strings - python

I am writing a function that checks if two numbers in a list are within a certain range and then print various statements if one number is in the range or if both numbers are in the range. My problem is that the right statements aren't being printed under the right conditions despite the statements looking fine.
def qualitative_reading(input_list):
humidity = 0
temp = 0
humid_round= round(input_list[0])
temp_round= round(input_list[1])
if humid_round in range(39, 61, 1):
humidity = 1
else:
humidity = 0
if temp_round in range(67, 75, 1):
temp = 1
else:
temp = 0
if humidity + temp ==2:
print('The room is comfortable')
elif temp == 1 & humidity == 0:
print("Ideal conditions for bacteria and virus")
print('The room is not comfortable to be in')
elif temp == 0 & humidity == 1:
print('The room is not comfortable to be in')
print('Energy being wasted')
elif humidity + temp ==0:
print('The room is not comfortable to be in')

You can try something like this instead
def qualitative_reading(input_list):
humidity = False
temp = False
humid_round= input_list[0]
temp_round= input_list[1]
humidity = 39 <= humid_round < 61
temp = 67 <= temp_round < 75
if humidity and temp:
print('The room is comfortable')
elif temp and not humidity:
print("Ideal conditions for bacteria and virus")
print('The room is not comfortable to be in')
elif not temp and humidity:
print('The room is not comfortable to be in')
print('Energy being wasted')
elif not humidity and not temp:
print('The room is not comfortable to be in')
I suspect that the problem lies with the fact that you are using & but python uses the keyword and.
Some of the other things I noticed were:
The use of range is not very applicable here so you can use an if statement instead.
humidity and temp seem to only have two values, so they can be turned into booleans.

Related

Return multiple values in a function

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]

Undefined dictionaries in my main function

def monday_availability(openhours_M): #openhours_M = number hours pool is open
hourone = int(input('Input the first hour in the range of hours the guard can work'))
hourlast = int(input('Input the last hour in the range of hours the guard'))
hour = 1
availability_M = []
while hour <= openhours_M:
if hour >= hourone & hour <= hourlast:
availability_M.append(1)
else:
availability_M.append(0)
return availability_M
Above is a function gathering the availability of a lifeguard and storing the hours a guard can work as a 1 in availability list or a 0 if they cannot. I return this list with the intent of adding it to a dictionary in the function below.
def guard_availability(guards, openhours_M, openhours_T, openhours_W,
openhours_R, openhours_F, openhours_S, openhours_Su):
continueon = 1
while continueon == 1:
name = input('Input guards name of lifeguard to update availability' )
availability = {}
days = {}
if openhours_M != 0:
monday_availability(openhours_M)
if openhours_T != 0:
tuesday_availability(openhours_T)
if openhours_W != 0:
wednesday_availability(openhours_W)
if openhours_R != 0:
thursday_availability(openhours_R)
if openhours_F != 0:
friday_availability(openhours_F)
if openhours_S != 0:
saturday_availability(openhours_S)
if openhours_Su != 0:
sunday_availability(openhours_Su)
days['Monday'] = availability_M
days['Tuesday'] = availability_T
days['Wednesday'] = availability_W
days['Thursday'] = availability_R
days['Friday'] = availability_F
days['Saturday'] = availability_S
days['Sunday'] = availability_Su
availability[name]= days
continueon = input('Enter 1 to add availability for another guard, 0 to stop: ')
return days
When I run this code, I get an error saying my availability lists are undefined even though I returned them in the functions above. Where is the error in my understanding of returning in functions, and how can I remedy this problem.
monday_availability(openhours_M) returns a value.
Returning a variable does not assign it to anything outside the scope of that function.
If you renamed return availability_M to use return foo and update the other uses only within that function accordingly, would the error make more sense?
Now, actually capture the result
availability_M = monday_availability(openhours_M)
Or even just
days['Monday'] = monday_availability(openhours_M)
Also, not seeing how that function has anything to do with Mondays. Try to write DRY code
You return the dic value in your function but don't assign it to any variable. You should do it like this:
if openhours_M != 0:
availability_M=monday_availability(openhours_M)
if openhours_T != 0:
availability_T=tuesday_availability(openhours_T)
if openhours_W != 0:
availability_W=wednesday_availability(openhours_W)
if openhours_R != 0:
availability_R=thursday_availability(openhours_R)
if openhours_F != 0:
availability_F=friday_availability(openhours_F)
if openhours_S != 0:
availability_S=saturday_availability(openhours_S)
if openhours_Su != 0:
availability_Su=sunday_availability(openhours_Su)

Checking a variable state

I am facing a problem at the moment... I am trying to make a naughts and crosses game, and i am trying to decided whether the user has guessed outside of the grid... this is the code that i have so far come up with and the outcome is that the code crashes, please could you help?
The code below is what i am currently running to get this outcome.
if 'users input' in (command = to left):
Left_new = input("How many places would you like to move left")))
elif 'users input' in (command = right):
Right_new = input("How many places would you like to move right")))
elif 'users input' in (= to up):
up_new = input("How many places would you like to move up")))
elif 'users input' in (= down ):
Down_new =input("How many places would you like to move down")))
else:
if ( users input <9) or ( users input > 100 ):
print("Sorry one of your inputs were invalid...")
Try incorporating a while statement and break from it if the data input is good.
i.e.
while True:
Down_position = (int(input("How many places would you like to move down")))
step = Down_position
if (step + x <= grid_size) and (step + x >= 0):
x += step
break
else:
print ("Sorry, that isn't on the grid")
print_board(board)
Here is some working code (only using Down) as an example.
def print_grid():
print (0,top)
print ("-----------------------------------")
for i in range(len(grid)):
print (i,grid[i])
print ("-----------------------------------")
x = 0
y = 0
top =[0,1,2,3,4,5,6,7,8,9]
grid=[]
for i in range(10):
grid.append([0]*10)
grid_size = len(grid)-1
while True:
while True:
Down_position = (int(input("How many places would you like to move down ")))
step = Down_position
if (step + x <= grid_size) and (step + x >= 0):
grid[x][y] = 0
x += step
grid[x][y] = 1
print_grid()
break
else:
print("******************************")
print ("Sorry, that isn't on the grid")
print("******************************")
print_grid()

Python Never - Ending While Loop [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
Currently I'm working in Python to try and simulate a set in a match of tennis based on player probabilities. There's a while loop that's never ending in my "ftsix" (firsttosixpoints) function, but I can't figure out what the bug is because my logic isn't sound. I've been working on the problem for a few hours but I can't seem to find the solution.
P.S - please play nice
#One set in tennis = 1st to 6 games
#One game = 1st to four points
#Serve switches after each game.
def main():
printIntro()
probA, probB = getInputs()
gamesA, gamesB = ftsix(probA, probB)
if gamesA > gamesB:
print"Player A has won with", gamesA, "to player B's", gamesB, "."
else:
print "Player B has won with", gamesB,"to player A's", gamesA, "."
def printIntro():
print "This is a simulation of 1 tennis set based on player probabilities!"
def getInputs():
probA = input("What is the probability that player A will win?: ")
probB = input("What is the probability that player B will win?: ")
return probA, probB
def ftsix(probA, probB):
#First one to six games = one set
x = 0
gamesA = 0
gamesB = 0
while gamesA or gamesB != 6:
if x % 2 == 0 or x == 0:
serving = "A"
else:
serving = "B"
#This is one game, not in a seperate function because I couldn't figure out how to change serve inside the function!
pointsA = 0
pointsB = 0
while pointsA or pointsB != 4:
if serving == "A":
if probA >= random():
pointsA = pointsA + 1
else:
pointsB = pointsB + 1
if serving == "B":
if probB >= random():
pointsB = pointsB + 1
else:
pointsA = pointsA + 1
if pointsA > pointsB:
gamesA = gamesA + 1
else:
gamesB = gamesB + 1
x = x + 1
return gamesA, gamesB
I think your syntax in the while loops is incorrect. You need a full conditional on each side of the or, for example:
while gamesA != 6 and gamesB != 6:
You need to change your loop to terminate when either gamesA or gamesB reaches 6:
while gamesA != 6 and games != 6:

Issue with Python Slot Machine

import random
balance = 50
def generator():
slot = 0
count = 0
gen = random.random()
while count < 3:
count = count + 1
if gen <= 0.01:
slot = 'Cherry'
elif gen <= 0.06:
slot = 'Diamond'
elif gen <= 0.16:
slot = 'Heart'
elif gen <= 0.36:
slot = 'Spade'
elif gen <= 0.66:
slot = 'Club'
elif gen <= 1:
slot = 'Monkey'
else:
break
return slot
def win(generator):
if generator() == 'Monkey' and generator() == 'Monkey' and generator() == 'Monkey':
balance = balance + 2122
print "Welcome to the International Slot Machine"
print ""
print "Balance: $",balance
print ''
spinyn = (raw_input("Would you like to spin? $5 per spin. Enter y or n:\n"))
while True:
if spinyn == "y":
break
elif spinyn == "n":
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spinyn = raw_input('\033[31mPlease enter only y or n.\033[0m\n')
spin = (raw_input("Press enter to spin for $5:\n"))
while True:
if spin == '':
balance = balance - 5
if balance <= 0:
print ""
print "Final Balance: $",balance
print "You have run out of money, the game has now ended."
raise SystemExit
print ""
print "\033[34mResult:\033[0m"
print "\033[34m-------\033[0m"
print generator()
print generator()
print generator()
print ""
print "New balance:$",balance
print ""
spinagain = (raw_input("Would you like to spin again? Press enter to spin again, type anything to exit.\n"))
while True:
if spinagain == "":
break
else:
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spin = (raw_input("Please press enter to spin.\n"))
I'm trying to make a very basic slot machine.
My question is: How do I make the generator function repeat 3 times and return 3 outputs, and then how do I make it recognise certain combinations?
Is this possible at all, keeping with my current format?
Also, how could I incorporate arrays into my code?
Thanks
Make the generator return a list or tuple of three values after generating three values, also it would be easier to use random.choice() rather than random.random() . random.choice() randomly selects a element for a list of values/iterable with equal probability for all elements. Example -
def generator():
ret = []
for _ in range(3):
ret.append(random.choice(['Cherry','Diamond','Heart','Spade','Club','Monkey']))
return tuple(ret)
If you want to have different probabilities for different elements, you can keep the current method, just loop over that three times and append to ret like done above and return ret from it.
Then in your win function, keep a dictionary such that the key is the tuple of combination and the value is the amount the user wins, then you can simply use .get() with a default value of 0 , to get how much the user won. Do not pass in generator as an argument. Example -
def win():
roll = generator()
d = {('Monkey','Monkey','Monkey'):21222,...}
return d.get(roll,0)
Then in your main loop, call this win() function to roll and see how much the user won.
Use the range function to choose 3 times and store it in a list.
import random
choices_list=[]
for ctr in range(3):
gen = random.choice(['Cherry', 'Diamond', 'Heart',
'Spade', 'Club', 'Monkey'])
choices_list.append(gen)
print choices_list

Categories