I've managed to save input into a variable then called it in the function below it. I wanted to account for .upper() and .lower() choices such as if someone inputs "C", "c", "Circle", or "circle". Not sure how to do that though...
"""
a calculator that can compute the area of a chosen shape, as selected by the user. The calculator will be able to determine the area of a circle or a triangle
"""
from math import pi
from time import sleep
from datetime import datetime
#opening comments and thinking computer thinks for 1 second
now = datetime.now()
print("Calculator is booting up! Beep Boop...")
print(("%s/%s/%s " + "%s:%s \n") % (now.month, now.day, now.year, now.hour, now.minute))
sleep(1)
#nagging teacher comment if needed
hint = str("Don\'t forget to include the correct units! \nExiting...")
#user input choose Circle or Triangle
option = input("Enter C for Circle or T for Triangle: ")
#Circle computing
if (option.upper() == input(str(C))) or (option.lower() == input(str(c))):
radius = input(float("What is the radius?: "))
area = (pi * radius ** 2)
print("The pie is baking...")
sleep(1)
print(str(area + hint))
It's from a code academy project and tried to search for an answer but couldn't find one here
Just lower the input you get from the user and only test against lowercase:
if option.lower() == expected_lowercase_input:
That way you don't have to worry about case at all as 'FOO', 'Foo', 'fOO', etc., will all be lowered to 'foo'.
To account for variations like 'c' or 'circle', you could do something like:
expected = ('c', 'circle')
if option.lower() in expected:
...
Which will execute the if block if the lowercase version of option is 'c' or 'circle'.
Stick with the Codecademy stuff. It is a great resource in my opinion!
Related
You have to build a dictionary (Or any other container of your choice) which contains multiple True/false type quiz questions.
Every participant/user will attempt 5 rounds and in each round random quiz questions will be displayed to the user/participant.
If the participant answers the quiz question correct, then congratulate him and add the scores.
At the end display the details and score of the participant.
I have tried but I am not getting expected output.
I hope it can be useful for you. There are many other ways to do it but i think in this way you can understand easier what the script is doing.
import requests
import random
import numbers
def get_quiz_questions():
response = requests.get('https://raw.githubusercontent.com/curiousily/simple-quiz/master/script/statements-data.json')
if response.status_code != 200:
return [
["The Mars Rover \"Spirit\" is powered by six small motors the size of \"C\" batteries. It has a top speed of 0.1 mph.", True],
["Burt Reynolds was originally cast to be Han Solo in the first Star Wars film. He dropped out before filming.", True]
]
return response.json()
# Get questions
quiz_questions = get_quiz_questions()
# Get numeric value, retry if it's not valid.
def get_numeric_value(message):
print(message)
value = input()
if not(value and value.isnumeric()):
print('Entered value is not valid\n')
# using recursion to prompt again for a valid value
return get_numeric_value(message)
return int(value)
def request_boolean_answer():
print('Enter answer: [ 0: false | 1: true]')
answer = input()
# Check if the value entered is numeric and if it's not 1 or 0
if answer.isnumeric() and ( 0 != int(answer) != 1):
print('Entered answer is not valid\n')
# using recursion
return request_boolean_answer()
return bool(answer)
# Start Game
num_players = get_numeric_value('\nEnter number of players: ')
num_questions = get_numeric_value('\nEnter number of questions: ')
score = {}
for player in range(num_players):
print("\nPlayer #:", player )
# initialize score for current user
score[f'player_{player}'] = 0
for question in range(num_questions):
question, answer = random.choice(quiz_questions)
print(question)
user_answer = request_boolean_answer()
print(f'Your answer: {user_answer}, correct answer: {answer}\n')
# Add a point if the answer is correct
if answer == user_answer:
score[f'player_{player}']+=1
print(f'\nScore: {score}')
code
I am trying to remove cards with the same color and number from total cards but I am having trouble making conditions for my for loop
total_Cards=['Ace_of_clubs', '2_of_clubs', '3_of_clubs', '4_of_clubs', '5_of_clubs', '6_of_clubs', '7_of_clubs', '8_of_clubs', '9_of_clubs', '10_of_clubs', 'King_of_clubs', 'Queen_of_clubs', 'Jack_of_clubs', 'Ace_of_diamonds', '2_of_diamonds', '3_of_diamonds', '4_of_diamonds', '5_of_diamonds', '6_of_diamonds', '7_of_diamonds', '8_of_diamonds', '9_of_diamonds', '10_of_diamonds', 'King_of_diamonds', 'Queen_of_diamonds', 'Jack_of_diamonds', 'Ace_of_spades', '2_of_spades', '3_of_spades', '4_of_spades', '5_of_spades', '6_of_spades', '7_of_spades', '8_of_spades', '9_of_spades', '10_of_spades', 'King_of_spades', 'Queen_of_spades', 'Jack_of_spades', 'Jocker', 'Ace_of_hearts', '2_of_hearts', '3_of_hearts', '4_of_hearts', '5_of_hearts', '6_of_hearts', '7_of_hearts', '8_of_hearts', '9_of_hearts', '10_of_hearts', 'King_of_hearts', 'Queen_of_hearts', 'Jack_of_hearts']
for i in range(len(total_Cards)):
first=total_Cards[i].split("_")
for y in range(len(total_Cards)-1):
y+=1
second=total_Cards[y].split("_")
if second[0]==['jocker']:
pass
elif first[0]==["jocker"]:
pass
elif ((first[0]==second[0])and((first[2]==("spades")or(first[2]=="clubs"))and (second[2]==("spades")or(second[2]=="clubs")))):
total_Cards.pop(i)
total_Cards.pop(y)
elif ((first[0]==second[0])and((first[2]==("diamonds")or(first[2]=="hearts"))and (second[2]==("diamonds")or(second[2]=="hearts")))):
total_Cards.pop(i)
total_Cards.pop(y)
Okay, since there are some things about your question that are not very clear, I am going to assume what seems reasonable and answer with that in mind. My assumptions are:
When there is a match of number and color, both cards should be removed;
If there are repeated cards (same color and number), all of their instances should be removed.
So, first, I believe in order to make the comparisons easier to understand and more efficient, we can make a specific function to tell us the color of the card based on its suit. This will make your conditions much cleaner:
def get_suit_color(suit: str) -> str:
if suit.lower() == "clubs" or suit.lower() == "spades":
return "black"
elif suit.lower() == "diamonds" or suit.lower() == "hearts":
return "red"
else:
raise ValueError("Suit is not a supported type (clubs, spades, diamonds, hearts)")
This function simplifies the color comparison, as we can see from an example:
foo = 'Clubs'
bar = 'sPADES'
baz = 'diAmOnDs'
qux = 'HEARTS'
print(get_suit_color(foo))
print(get_suit_color(bar))
print(get_suit_color(baz))
print(get_suit_color(qux))
That will output:
>>> black
>>> black
>>> red
>>> red
So, now, let's get into removing 'color duplicates'. The function, basically, gets the number and suit of a card and compares to the pair of number and suit of each other card. If the numbers match, we check color, if the color then matches, we remove the card from the list we will return. This will work:
def deduplicate(cards_list: list[str]) -> list:
return_list = cards_list.copy()
for card in cards_list:
new_list = cards_list.copy()
try:
number, _, suit = card.split("_")
except ValueError:
# Happens when Joker is found
continue
else:
new_list.remove(card)
for other_card in new_list:
try:
other_number, _, other_suit = other_card.split("_")
# print(f"Comparing {number} of {suit} with {other_number} of {other_suit}")
except ValueError:
# Happens when Joker is found
continue
else:
if not number == other_number:
continue
else:
if get_suit_color(suit) == get_suit_color(other_suit):
try:
return_list.remove(other_card)
except ValueError:
# Happens when there are repeated cards (same number and suit)
continue
# print(f"Updated list:\n{return_list}")
return return_list
Note that the get_suit_color function is used to compare the two cards (card and other_card). I left two commented print statements because I believe they might aid in the understanding of the function, though they pollute the output.
Another important thing is copying the original list, not to change it. The return_list starts off just like cards_list, and at each match of color and number, cards are removed. The new_list is just an object created by removing the current card of the list, in order to avoid comparing it with itself.
With both these functions, you can expect this to go well:
all_cards = ['Ace_of_clubs', '2_of_clubs', '3_of_clubs', '4_of_clubs', '5_of_clubs', '6_of_clubs', '7_of_clubs', '8_of_clubs', '9_of_clubs', '10_of_clubs', 'King_of_clubs', 'Queen_of_clubs', 'Jack_of_clubs', 'Ace_of_diamonds', '2_of_diamonds', '3_of_diamonds', '4_of_diamonds', '5_of_diamonds', '6_of_diamonds', '7_of_diamonds', '8_of_diamonds', '9_of_diamonds', '10_of_diamonds', 'King_of_diamonds', 'Queen_of_diamonds', 'Jack_of_diamonds', 'Ace_of_spades', '2_of_spades', '3_of_spades', '4_of_spades', '5_of_spades', '6_of_spades', '7_of_spades', '8_of_spades', '9_of_spades', '10_of_spades', 'King_of_spades', 'Queen_of_spades', 'Jack_of_spades', 'Joker', 'Ace_of_hearts', '2_of_hearts', '4_of_hearts', '5_of_hearts', '6_of_hearts', '7_of_hearts', '8_of_hearts', '9_of_hearts', '10_of_hearts', 'King_of_hearts', 'Queen_of_hearts', 'Jack_of_hearts']
new_deck = deduplicate(all_cards)
print(new_deck)
The output should be:
>>> ['3_of_diamonds', 'Joker']
Since I removed the 3 of Hearts from all_cards, and there is only one Joker.
Note: if you have older Python, remove the type annotations from the functions. Also, I believe "Joker" is the correct spelling, so I used that.
I have the following problem for part of my python class homework:
Using the functions you created earlier, make a flask application that takes arguments and displays the results of the calculations using routes/views.
For example, you will have three routes and they can be called square, triangle, and cost. You will pass GET query string parameters to these routes and the view will display the appropriate results.
I did some research and could not figure out what to do with Flask. My teacher gave a very short overview in class on Flask, and I'm a beginner with Python, so hoping someone can help me.
I just have no idea what to do. Any help I can get would be appreciated. Thanks!
Here is the code for the functions (this code works)
functions.py file:
# Using the input function ask the user for the base of a triangle and store in a variable
print()
b = int(input(str(user_name)+ ", please enter the base length of your triangle: "))
print()
#Using the input function ask the user for the height of a triangle and store the value in a variable
#Where b = length of base and h = length of height
h = int(input("Now please enter the height length of your triangle: "))
print()
#Call your function passing the two variables that contain the values for base and height
print("The area of your triangle", user_name, "is", str(area_tr(b,h)) +".")
print()
#Part 3: Total Cost
#Assume you work for an outdoor clothing company. Your job is to find out the total cost of buying raw materials for a winter jacket.
#Create a function that takes two arguments and returns the total cost using the formula:
#Total cost = Number of units X price per unit
def tc_wjacket(u,p):
"""
total cost of buying raw materials for a winter jacket.
Total cost = Number of units X price per unit.
"""
return u * p
#Using the input function ask the user for the numbers of units and store it in a variable.
print()
u = int(input(str(user_name)+ ", please enter the number of winter jackets you want for your store: "))
print()
#Using the input function ask the user for the price per unit
p = int(input("Now please enter the cost of the raw materials per jacket: "))
print()
#Call your function passing the two variables that contain the values for number of units and price per unit
print(str(user_name)+ ", according to my calculations, the cost to buy the raw materials for", b ,"jackets with at", p ,"dollars per jacket is", tc_wjacket(u,p) ,"dollars.")
print()
print("I hope this information was helpful " + str(user_name)+ ".")
print()
#importing Flask
from flask import Flask
#creating an app instance in the current namespace
app = Flask(__name__)
#decorator
#app.route("/")
#app.route("/square/<int:side1>/<int:side2>/<int:side3>/<int:side4>")
def add(side1,side2,side3,side4):
"""
perimeter of a square
"""
perim = (side1 + side2 + side3 + side4)
return "<h2>Your square's parimeter is {}</h2>".format(perim)
#app.route("/triangle/<int:b>/<int:h>")
def area_tr(b,h):
"""
Function calculates the area of a triangle
formula = (base * height)/2
"""
area_tr = b * h / 2
return "<h2>Your triangle's area is {}</h2>".format(area_tr)
#app.route("/cost/<int:u>/<int:p>")
def tc_wjacket(u,p):
"""
total cost of buying raw materials for a winter jacket.
Total cost = Number of units X price per unit.
"""
total_cost = u * p
return "<h2>Your triangle's area is {}</h2>".format(total_cost)
#debug=True allows us to make changes to our code and see them in the browser without having to re-run our app
app.run(debug=True, port=8000, host='0.0.0.0')
I am trying to create a program that will allow a game reviewer to input what categories the game falls under, it should then print the appropriate category with a checkbox, and the other categories with a blank box.
I have managed to write a for loop that prints out the correct category with the checkbox, but am struggling to loop through the rest of the values to print them with a blank box.
yes = '\u2611' #checkbox
no = '\u2610' #blank box
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
audience= int(input("1. Kids, 2. Everyone, 3. Casual 4. Pro: "))
print ("===[ Audience: ]===")
for i in audience_list: #cycles through the list of audience options
if i == audience_list[audience-1]: #for the audience option that was selected, print it with a check box
print ("%s %s" % (yes, audience_list[audience-1]))
else: #for the audience options weren't selected, print them with a blank checkbox
print ("%s %s" % (no, audience_list))
Is there a way for me to print every index other than the one that has been assigned to the 'audience' variable?
I'm using Python 3.2.3.
Just print i! If you print audience_list, you will output the whole list of every element; whereas i is the one you are currently checking.
for i in audience_list:
if i == audience_list[audience-1]:
print ("%s %s" % (yes, audience_list[audience-1]))
else:
print ("%s %s" % (no, i))
and a test (having entered 3) gives a neat output of:
☐ Kids
☐ Everyone
☑ Casual Players
☐ Pro Players
Consider enumerating the list items:
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
choice = 3 # Casual.
for (index, name) in enumerate(audience_list, start=1):
if index == choice:
print("[X] " + name)
else:
print("[ ] " + name)
Output:
[ ] Kids
[ ] Everyone
[X] Casual Players
[ ] Pro Players
I'm going to answer this because I feel the other answers haven't answered your underlying question.
Here's the code I propose:
yes = '\u2611' #checkbox
no = '\u2610' #blank box
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
audience= int(input("1. Kids, 2. Everyone, 3. Casual 4. Pro: "))
selection = audience_list[audience-1]
print ("===[ Audience: ]===")
for option in audience_list: #cycles through the list of audience options
print ("%s %s" % (yes if option == selection else no, option))
There are two major changes here.
First, I created the variable selection, outside of your for loop. This cleans up your loop and is closer to what you're doing. You don't care about the number, you care about what the user selected.
Second, I put the if part of your for loop into the print statement. This is to highlight something important: the only difference you want in each iteration of your loop is whether or not the box is checked. Either way, you want to print the element of audience_list. This print statement shows that. You either print an empty box or a checked one, and either way, you print the element.
Note that some confusion may have come from your for i..., because typically an i like that is an int. Consequently, I changed my for loop iterator to be named option, which is much more clearly a string.
I think your main question gets addressed by this. You could have printed audience_list[audience-1] in both your yes and no lines, or you could more simply have printed i in both of your lines. (Or, as per Joe's code at this time, you could have made one audience_list[audience-1] and one i, since as it's written, they're both the same.) But since you're looping through all the options, other than the box, you should print the same option string, whether it's selected or not.
Note, in my comments with Joe, I mentioned that you could squeeze the for loop and below all on to one line. Then your code would look like this:
yes = '\u2611' #checkbox
no = '\u2610' #blank box
audience_list = ["Kids", "Everyone", "Casual Players", "Pro Players"]
audience= int(input("1. Kids, 2. Everyone, 3. Casual 4. Pro: "))
selection = audience_list[audience-1]
print ("===[ Audience: ]===")
_ = list(map(lambda o: print ( "%s %s" % (yes if o == selection else no, o)), audience_list))
This is logically equivalent, but a lot harder to read, so while it's fun to do, I wouldn't recommend it. (Briefly: map takes a function, in this case, the unnamed lambda function, and runs every member of the iterator audience_list through that function. list is necessary to make the map object actually do the processing, and the _ = is just to tell any other readers that we know we're throwing away the list.)
As Joe mentions, there is a less ugly way to do it that doesn't require mapping. The last line could be:
_ = [print ( "%s %s" % (yes if o == selection else no, o)) for o in audience_list]
This is slightly less confusing, since it removes the list(map( noise.
These are pretty much all functionally equivalent. And while it's fun to toss things in to a single line, don't get lost in that. Readability, maintainability and the ability to easily debug are the most critical.
I've been researching this for a while, and have seen some questions similar to mine, but I don't quite understand / think they're what I'm looking for. I'm trying to do something like this:
def run():
cost = input("enter cost")
size = input("enter size")
print("For color, 1 = red, 2 = blue, 3 = green, enter one")
color = input("enter color")
shoe1 = [cost, size, color]
repeat = input("Do you want to order another shoe? Y/N")
if repeat == "Y" or repeat == "y":
run()
But then, save shoe1 so that it isn't redefined when we re-run the function, and that a new list is defined, maybe shoe2 (Or any variable name). So that at the end we can list all the shoes, and specifications of the shoes that were ordered. Other questions said that a dictionary should be used for this, how might I do that?.All help appreciated, thanks a bunch!