I am confused please help me solve it [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to use an dictionary with b and c like in the code such that when I give input o, then I receive 1 as an result with o.
science_dictionary = {"O": 1, "H": 2}
print("Hey welcome to the chemical reactor")
import time
time.sleep(2)
print("\n")
print("In this chemical reactor you can receive the product of any two "
"elements")
b = input("Please enter your first element element in short forms : ").upper().strip()
c = input("Please enter your second element element: ").upper().strip()
time.sleep(1)
print("Calculating")
time.sleep(2)
print(f"{b}{c}")

You can access dictionary items by using the dictionary name with the specific key you want. I.e. science_dictionary['O'] will return 1. You can also pass in variable names as keys, for example science_dictionary[b] would be matched with the input (if the input is either O or H).

I'm not sure what's your purpose; but i think that if you want to try a make a product using the keys in the dictionary with the inputs [key name] , that would be like this:
import time
science_dictionary = {"O": 1, "H": 2}
print("Hey welcome to the chemical reactor")
time.sleep(2)
print("\n")
print("In this chemical reactor you can receive the product of any two elements")
b = input("Please enter your first element element in short forms : ").upper()
c = input("Please enter your second element element: ").upper()
time.sleep(1)
print("Calculating")
time.sleep(2)
print("{}".format(science_dictionary[b] * science_dictionary[c]))

Related

I am trying to know the reason my code is not running [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
I want to know where I have mistakes in my codes I am trying to fix it , hope someone will help )
def make_list(number) :
names = []
for item in number:
names.append(input("Enter your name') )
print (names)
number = int(input("How many names need to be entered?"))
names = make_list(number)
for name in names:
if name[1] == "A":
print("Name", name, “Starting from the work A")
I hope I've fixed all the indentations:
def make_list(number) : # function to make a list of numbers
names = [] # create an empty list
for i in range(number): # range(number) is a list of numbers from 0 to number-1
names.append(input("Enter your name: ")) # append() adds an element to the end of the list
return names # return the list
number = int(input("How many names need to be entered?")) # ask the user for the number of names
names = make_list(number) # call the function make_list()
for name in names: # for each name in the list
if name[1] == "A": # if the second letter of the name is "A"
print("Vmsa", name, "Starting from the work A") # print the name and the message

Python Library with options to add books, shows all books, delete and display details of the books [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
library = ['Harry Potter','Lord of the rings','Lupin']
user_input=input('Choose option: ')
# When adding a book , it is not saved in library, it only prints out what was by default.
How to save books in Library?
if user_input == 'add_book':
x = input('add_book: ')
library.append(x)
elif user_input =='show_books':
for e in library:
print((e),end=' ')
# How to specify which book to remove?
elif user_input =='remove':
library.pop()
Where to place details for each book? Details should appear when book is selected.
This code resolves the problems you stated in your comments, the following points explain the changes.
library = ['Harry Potter','Lord of the rings','Lupin']
while True:
user_input = input('\n Choose option: ')
if user_input == 'add_book':
to_add = input('add_book: ')
library.append(to_add)
elif user_input =='show_books':
for e in library:
print((e),end=' ')
elif user_input =='remove_book':
to_remove = input("remove_book: ")
library.remove(to_remove)
elif user_input == 'quit':
break
else:
print("Available options: add_book, show_books, remove_book, quit")
While True lets your entire algorithm start again until user_input == 'quit', when the break command tells the program to exit the While True loop, ending the program. This was necessary to solve the problem you described of the program not saving changes: the reason was your program ended after your first input, and when you start the program again, it only runs its source code, so it couldn't show any "changes" to variables you made using it previously. Now until you type quit it "saves" every change you make.
I used library.remove() because it accepts the library key value as an argument. library.pop() required the index instead. (Now you just need to enter the item (book) name.
( I couldn't implement the last function you described)
Where to place details for each book? Details should appear when book is selected.
You didn't describe the concept of "selecting" a book and what are the "details" of one.
Hope I've been of some help.
I've figured out how to implement logic for displaying details about selected book.
elif user_input == 'book_details':
which_book = input('Which book: ')
if which_book == 'Harry Potter':
print('\n''Author: J. K. Rowling')
print('ISBN: 9780747532743')
print('Year of release: 1997')
if which_book == 'Lupin':
print('\n''Author: Maurice Leblanc')
print('ISBN: 9780141929828')
print('Year of release: 1907')
if which_book == 'Lord of the rings':
print('\n''Author: J. R. R. Tolkien')
print('ISBN: 9788845292613')
print('Year of release: 1954')

I am having a problem understanding this code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
# Split string method
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
# 🚨 Don't change the code above 👆
#Write your code below this line 👇
import random
num_items = len(names)
random_choice = random.randint(0, num_items - 1)
person_who_will_pay = names[random_choice]
print(person_who_will_pay + " Is going to pay the bill!")
I have took 100 days of code from angela Yu from udemy I am currently in the random module Day-4 but i did not understand this code can anyone explain me what is going on with this code Please.
names_string = input("Give me everybody's names, separated by a comma. ")
# Gets input from the user as a string type.
names = names_string.split(", ")
# Splits the input string into a list of names.
# If names_string = "John, Mark, Mary", names = ["John", "Mark", "Mary"]
import random
num_items = len(names)
# Gets number of names in the list
random_choice = random.randint(0, num_items - 1)
# Selects a random index in the array from 0 to (number of names - 1)
person_who_will_pay = names[random_choice]
# Gets name stored at the chosen index.
print(person_who_will_pay + " Is going to pay the bill!")
# Prints person's name

How to have a function feed another function's input [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm making a hangman game and testing how different letter picking algorithms fare, but to do this, the guessing algorithm function has to feed a letter into the hangman function's input('Select a letter').
How do you make it so that a function detects when another function is waiting for an input ?
Assuming you are doing input() in a loop inside your hangman function, you could switch that to a yield and let an external function drive input as needed. In this example I have a hangman function that uses yield to get data. Now its a generator and driving function can use next and the generator's .send method to pump data into it.
def hangman(chances=5):
for i in range(chances):
letter = yield "prompt"
if letter == "quit":
yield "quit"
return
print("letter", letter)
# do all the things
solved = False
if solved:
yield "solved"
yield "failed"
def command_line_prompt_hangman():
feeder = hangman()
state = next(feeder)
while state == "prompt":
state = feeder.send(input("Next letter: "))
def test():
# after years of testing the best algorithm is
test = ['a', 'b', 'c', 'd', 'e', 'f']
feeder = hangman()
assert next(feeder) == "prompt"
for count, letter in enumerate(test, 1):
state = feeder.send(letter)
if state == "solved":
print("did it in ", count, "tries")
break
if state == "failed":
print("exceeded count")
break
command_line_prompt_hangman()
test()
Instead of using the input function, write a custom function to pull an output from whatever algorithm you are using. That would look something like this:
user_input = algo_obj.get_input(game_state)
In this case, algo_obj would be an object storing the current state of the algorithm/generator (if such a state exists, otherwise you can just call the function normally). game_state would be some representation of the game's current state (available letters, the word-form -- ie. blanks & letters).
You can then feed user_input to your Hangman function.
This should be as simple as:
Define both functions.
Pass one function return value to the other one as argument.
This can be done by using input() as according to this
e.g. Define the functions
def first_function():
input_variable = input("Please enter some data")
return input_variable
def second_function(a):
print(a) # Do some calculations here
And use them:
second_function(first_function())
I wouldn't say that this is necessarily the best way to go about but it solves Your problem. If You would like to receive a more detailed answer please provide code samples.

Is there a way I can collect all the names and IDs before collecting the scores? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Is there a way I can gather all the student's names and IDs before getting their grades for each of the assignments? Currently, my code runs through one student at a time, but is there a way to recall their IDs one at a time to add their grades afterwards?
nameID = {}
while input("Would you like to add a student? ") == "yes":
name = input("What is the student's name?: ")
ID = input("What is the student's ID?: ")
nameID[ID] = name
scores = []
assignments = int(input("How many assignments were given? "))
for i in range(assignments):
score = int(input("Enter {}'s score for assignment {} (0-100): ".format(nameID[ID], i+1)))
scores.append(score)
average = (sum(scores))/assignments
print("{}'s average score was {:.1f}".format(name, average))
nameID[ID] = {"Name": name, "Scores": scores}
print(nameID)
First of all, you need to work through some sort of tutorials on Python data types and how to apply them. It appears that you're trying to build a table of student data, including name, ID, and a list of scores for each student.
This suggests a data frame -- although that data structure is likely beyond what you've learned in class. In the meantime, it looks like you're trying to use a dict to do the job -- this is reasonable. However, you haven't designed the structure in ways that Python will recognize.
I don't know whether you need to access the data by student name or student ID; your posted code is confused about the relationships. Assuming that you want to do this by name, perhaps you need a nested dict: name at the upper level, ID and scores underneath.
ledger = {}
while input("Would you like to add a student? ") == "yes":
name = input("What is the student's name?: ")
id = input("What is the student's ID?: ")
ledger[name] = {"ID": id}
assignments = int(input("How many assignments were given? "))
for name in ledger:
score_list = []
for i in range(assignments):
score = input("Enter {}'s score for assignment {}: ".format(name, i+1))
score_list.append(int(score))
ledger[name]["scores"] = {"ID": ID, "scores": scores}
Does this move you somewhat down the path to an overall solution?

Categories