Is there a way to make this script shorter? - python

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)

Related

How to correctly use objects of class in Python?

The problem I've been getting is the program should produce player 2 Won! instead of draw
Can't figure it out
This is a question from CIE 9618\42\O\N\2022
Even the Code from thier marking scheme(for python)produces errors
Help would be apreciated
the code is pasted below:
Oh and i've tried to see what values are being assigned using print function but I get stuff like: <main.Card object at 0x000001FBCD177940>
maybe thats the problem
I have no idea how to fix it
#Part A i:
class Card:
# __Number as Integer
# __Colour as String
def __init__(self, Number, Colour):
self.Number = Number
self.Colour = Colour
#Part A ii:
def GetNumber(self):
return self.Number
def GetColour(self):
return self.Colour
#Part A iii:
IRed = Card(1, "red")
IIRed = Card(2, "red")
IIIRed = Card(3, "red")
IVRed = Card(4, "red")
VRed = Card(5, "red")
IBlue = Card(1, "blue")
IIBlue = Card(2, "blue")
IIIBlue = Card(3, "blue")
IVBlue = Card(4, "blue")
VBlue = Card(5, "blue")
IYellow = Card(1, "yellow")
IIYellow = Card(2, "yellow")
IIIYellow = Card(3, "yellow")
IVYellow = Card(4, "yellow")
VYellow = Card(5, "yellow")
#Part B i:
class Hand:
# __Cards as Array of Card
# __FirstCard as Integer
# __NumberCards as Integer
def __init__(self, ICard, IICard, IIICard, IVCard, VCard):
self.Cards = []
self.Cards.append(ICard)
self.Cards.append(IICard)
self.Cards.append(IIICard)
self.Cards.append(IVCard)
self.Cards.append(VCard)
self.FirstCard = 0
self.NumberCards = 5
#Part b ii:
def GetCard(self, index):
return self.Cards[index]
#Part b iii:
Player_1 = Hand(IRed, IIRed, IIIRed, IVRed, IYellow)
Player_2 = Hand(IIYellow, IIIYellow, IVYellow, VYellow, IBlue)
#Part c i:
def CalculateValue(Player):
Score = 0
for index in range(0, 5):
Player_Hand = Player.GetCard(index)
Colour = Player_Hand.GetColour
Numbers = Player_Hand.GetNumber
if Numbers == 1:
Score = Score + 1
if Numbers == 2:
Score = Score + 2
if Numbers == 3:
Score = Score + 3
if Numbers == 4:
Score = Score + 4
if Numbers == 5:
Score = Score + 5
if Colour == "red":
Score = Score + 5
if Colour == "blue":
Score = Score + 10
if Colour == "Yellow":
Score = Score + 15
return Score
#Part c ii:
Player_1Score = CalculateValue(Player_1)
Player_2Score = CalculateValue(Player_2)
if Player_1Score > Player_2Score:
print("Player 1 Won!")
elif Player_1Score < Player_2Score:
print("Player 2 Won!")
else:
print("Draw")
I tried over writing builtin functions for repr and str it made it readable but wasn't able to get it to work
Problems:
-Used double underscore with attributes
*removed them
-for index in range(0, 4) should be for index in range(0, 5)
*fixed
-return self.__Number.__dict__ should be return self.__Number
*fixed
-GetNumber in function CalculateValue should be GetNumber()
*fixed it and now the program works!!
TYSM to all the comments

I want the program to loop every time the sensor detects anything in 15cm

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

Python, google colab

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')

Select a random object in a list

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])

Mastermind Python coding

Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)

Categories

Resources