x=str(input('Where to'))
y=str(input('Which uber'))
if x == ('Cleveland'):
print('400 miles')
if x == ('Detriot'):
print('500 miles')
if x == ('Sandusky'):
print('100 miles')
if x == ('Lakewood'):
print('200 miles')
if x == ('Rocky River'):
print('550 miles')
elif x == ('none'):
print(compares)
compares = x * y
Question: if i made the user type in a new value for x how i would multiply that by the y they gave?
You can use dictionary
Note: by default input() returns string no need to convert it into string.
x = input('Where to: ')
y = input('Which uber: ')
cities = {'Cleveland': 400, 'Detriot': 500, 'Sandusky': 100, 'Lakewood': 200, 'Rocky River': 550}
if x in cities and y in cities:
compares = cities[x] * cities[y]
print(compares)
else:
print('Select valid location')
Related
import location
if __name__ == "__main__" :
locationlist = []
while True :
try :
coordinate = input("Enter X and Y separated by a space, or enter a non-number to stop: ")
a,b = coordinate.split()
a = int(a)
b = int(b)
locationlist.append(coordinate)
except ValueError:
break
print("Points: ",locationlist)
test = location.where_is_xy(coordinate,locationlist)
print(test)
^ This is my main.py
def where_is_xy(coordinate,locationlist) :
for coordinate in locationlist :
x,y = coordinate.split()
x = int(x)
y = int(y)
if x != 0 :
if y == 0 :
Point = 'X-Axis.'
elif x > 0 :
if y > 0 :
Point = 'Quadrant 1.'
elif y < 0 :
Point = 'Quadrant 4.'
elif x < 0 :
if y > 0 :
Point = 'Quadrant 2.'
elif y < 0 :
Point = 'Quadrant 3.'
elif x == 0 :
if y != 0 :
Point = 'Y-Axis.'
elif y == 0 :
Point = 'Origin.'
return(Point)
^ This is my location.py.
When "1 1" and "-1 -1" is input, the output is "Quadrant 1". I would like it to loop back and go through the list of tuples, but I cannot figure that out.
You used a return statement inside the for loop so after the first iteration it ends and comes out of the loop.
def where_is_xy(coordinate,locationlist) :
for coordinate in locationlist :
x,y = coordinate.split()
x = int(x)
y = int(y)
if x != 0 :
if y == 0 :
Point = 'X-Axis.'
elif x > 0 :
if y > 0 :
Point = 'Quadrant 1.'
elif y < 0 :
Point = 'Quadrant 4.'
elif x < 0 :
if y > 0 :
Point = 'Quadrant 2.'
elif y < 0 :
Point = 'Quadrant 3.'
elif x == 0 :
if y != 0 :
Point = 'Y-Axis.'
elif y == 0 :
Point = 'Origin.'
return(Point)
This is the code:
def check_ultra():
global arduinoSerialData, y, i, x
while True:
if arduinoSerialData.inWaiting() > 1:
myData = arduinoSerialData.readline()
myData = str(myData)
myData = myData.replace("b'", '')
myData = myData.replace("\\r\\n'", str(0))
myData = myData.replace("\\r00.000", str(0))
myData = myData.replace("\\r00.000", str(0))
if "c" in myData:
myData = myData.replace("c", str(0))
if y == 1:
y = 3
if float(myData) > 15:
x = 0
return y, x
else:
if float(myData) < 15 and float(myData) > 1:
y = 1
x = 0
return y, x
elif "a" in myData:
myData = myData.replace("a", str(0))
if y == 2:
y = 3
if float(myData) > 15:
x = 0
return y, x
else:
if float(myData) < 15 and float(myData) > 1:
y = 2
x = 0
return y, x
else:
y = 0
return y
set_servo1_angle(0)
set_servo2_angle(90)
go_out_count = 0
m1 = 0
count = 3
y = 0
i = 0
x = 0
while y == None or y == 0 or x == 1:
# i = 0
# y = None
check_ultra()
if y == 1 and x == 0:
print("1")
sleep(2)
elif y == 2 and x == 0:
print('2')
sleep(2)
What this currently does is it prints 1 every time sensor 1 is blocked, but then it ends the code. I want to make it such that every time I block a sensor, it prints the corresponding print statement, no matter how many times I block the sensor. I have tried adding many variables to help but they didnt work. How do I make the loop keep repeating?
Your outer-most loop has the following condition: y==None or y==0 or x==1. The if statements in it are only going to print if all of those conditions are False. That means the loop is guaranteed to terminate on the first printout.
If you want the loop to keep going indefinitely, ignore everything and keep going. Replace the loop with
while True:
check_ultra()
...
On an unrelated note, try to avoid globals. They may have unpredictable side effects when you set them in long-forgotten places, and generally make the code harder to maintain. Use arguments and return values instead.
For example:
def check_ultra(arduinoSerialData, x, y):
while True:
if arduinoSerialData.inWaiting() > 1:
myData = arduinoSerialData.readline()
myData = str(myData)
myData = myData.replace("b'", '')
myData = myData.replace("\\r\\n'", str(0))
myData = myData.replace("\\r00.000", str(0))
myData = myData.replace("\\r00.000", str(0))
if "c" in myData:
myData = float(myData.replace("c", "0"))
if y == 1:
if myData > 15:
return 0, 3
return x, 3
elif 1 < myData < 15:
return 0, 1
return x, y
elif "a" in myData:
myData = float(myData.replace("a", "0"))
if y == 2:
if myData > 15:
return 0, 3
elif 1 < myData < 15:
return 0, 2
return x, y
else:
return x, 0
You would call it as
x, y = check_ultra(arduinoSerialData, x, y)
'break' statement ends the while loop, so try replacing it with 'pass', like this:
elif y == 2:
print('2')
pass
I am a brand new programmer, and from what I have read Python is easy to learn so I tried learning it. This is just a fun script I made in a few minutes and I was wondering if I could shorten it. In case you can't tell, this essentially just has the user input three variables, then picks one of them, repeat three times, and then combines the answers.
import random
import time
print("name three diffrent animals")
animal1 = input("1")
animal2 = input("2")
animal3 = input("3")
x = (random.randint(1,3))
if x == 1:
x = animal1
if x == 2:
x = animal2
if x == 3:
x = animal3
print("name three diffrent colors")
color1 = input("1")
color2 = input("2")
color3 = input("3")
y = (random.randint(1,3))
if y == 1:
y = color1
if y == 2:
y = color2
if y == 3:
y = color3
print("name three diffrent sports")
sport1 = input("1")
sport2 = input("2")
sport3 = input("3")
z = (random.randint(1,3))
if z == 1:
z = sport1
if z == 2:
z = sport2
if z == 3:
z = sport3
print("your dream animal is a.....")
time.sleep(3)
print(y, ',' , z, 'playing', x,'!')
How about using packing-unpacking?
print("Name three different animals: ")
animals = input("1: "), input("2: "), input("3: ")
And using choice() instead of randint()?
x = random.choice(animals)
And (maybe) using f string for printing?
print(f"{y} {z} playing {x}!")
Here's a suggestion
# read a list of N animal names
animals = list(map(lambda i: input(str(i)), range(1, N)))
# read a small (fixed) number of animal names
animals = input("1"), input("2"), input("3")
# select a random animal from the list
x = animals[random.randint(0, len(animals) - 1)]
# or
x = random.choice(animals)
So I am trying to make a program that selects a random object in a list and then refer to that object.
Here's my code:
for hour in c.routine:
a = hour.hour
if hour.task == "idle":
if c.spouse:
if c.spouse[0].routine[a].task == "idle":
if hour.hour >= 6 and hour.hour <= 19:
x = random.choice(family_daytime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.spouse[0].routine[a].task = x
c.spouse[0].routine[y].task = x
if c.kids:
for k in range(len(c.kids)):
if c.kids[k].routine[a].task == "idle":
c.kids[k].routine[a].task = x
c.kids[k].routine[y].task = x
else:
x = random.choice(family_nighttime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.spouse[0].routine[a].task = x
c.spouse[0].routine[y].task = x
elif c.lover:
pick = random.choice(c.lover)
if c.lover[pick].routine[a].task == "idle":
c = random.randint(0,2)
if c == 1:
if hour.hour >= 6 and hour.hour <= 19:
x = random.choice(daytime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.lover[pick].routine[a].task = x
c.lover[pick].routine[y].task = x
else:
x = random.choice(nighttime_activities)
hour.task = x
y = hour.hour+1
c.routine[y].task = x
c.lover[pick].routine[a].task = x
c.lover[pick].routine[y].task = x
When I run this code I get an error:
Traceback (most recent call last): File
"C:\Users\Patrick\Pictures\Python\Westhope\2.0\exe.py", line 9, in
<module>
routine_creation() File "C:\Users\Patrick\Pictures\Python\Westhope\2.0\world_init.py", line
721, in routine_creation
if c.lover[pick].routine[a].task == "idle": TypeError: object cannot be interpreted as an index
Seems to be the way I try to refer to the pick but I am not sure why or how to fix it...
That's a lot of code to comb through. Could you make a smaller example?
According to your stack trace, the problem is at
if c.lover[pick].routine[a].task == "idle"
Okay, i see it. Change
pick = random.choice(c.lover)
if c.lover[pick].routine[a].task == "idle":
to:
pick = random.choice(c.lover)
if pick.routine[a].task == "idle":
you already have a random choice made (it is contained in pick), so you can just use that directly.
If you also need the index, use random.randrange
from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])
Sorry if not too clear, creating a program to calculate a formula and using cataloged values for one variable which are stored in a nested dictionary. I want to have the user be able to pull values from the dict like so:
def get_value():
x = input("Material: ")
if x in materials:
y = input("Gauge: ")
if y in x:
return materials[x][y]
elif not (not (y is None) and not (y not in x)):
return 0
elif x not in materials or x is None:
return "Invalid Punch"
is there any specific way to do this that I'm messing up? Every time I try to run it I get a Nonetype, which I have set to replace with a default value of 0.
Dict for reference
materials = {"ss": {22: "", 21: "", 20: "0.431", 19: "", 18: ""
,17: "", 16: "", 15: "", 14: ""
,13: "", 12: "", 11: "", 10: "", 9: "", 8: ""}, }
Change your line: if y in x: to if y in materials[x]: you need to check if y is in the dict of x. y in x checks if y is part of x
You should use raw_input() instead of input().
input() will evaluate the input as python code, whereas raw_input() will return a string.
Also, as #DanielMesejo mentioned in their answer the condition y in x won't work as both will be strings. You should check y in materials[x].
def get_value():
x = raw_input("Material: ")
if x in materials:
y = int(raw_input("Gauge: "))
if y in materials[x]:
return materials[x][y]
elif not (not (y is None) and not (y not in materials[x])):
return 0
elif x not in materials or x is None:
return "Invalid Punch"
print(get_value())
Output:
0
This doesn't work because the gauge index is an int, not a string. raw_input return a string! So we need to type cast it:
def get_value():
x = raw_input("Material: ")
if x in materials:
y = int(raw_input("Gauge: ")) # Converting raw_input response to int
if y in materials[x]:
return materials[x][y]
elif not (not (y is None) and not (y not in materials[x])):
return 0
elif x not in materials or x is None:
return "Invalid Punch"
print(get_value())
Output:
0.431
Your expression on line #7 is more complicated than is necessary so I have made a simpler function for you:
def get_value():
material = raw_input("Material: ")
if not material or material not in materials:
return "Invalid Punch"
gauge = int(raw_input("Gauge: "))
if not gauge or gauge not in materials[material]:
return 0
return materials[material][gauge]
Usage:
> python input.py
Material: ss
Gauge: 20
0.431
Try this:
def get_value():
x = raw_input("Material: ")
if x in materials:
y = raw_input("Gauge: ")
if int(y) in materials[x]:
return materials[x][int(y)]
elif not (not (y is None) and not (y not in x)):
return 0
elif x not in materials or x is None:
return "Invalid Punch"
Your problem was the x in y they are both string you need to call if y in materials[x] also converted y to an int. Since input returns Strings in general.