I am having a problem understanding this code [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
# 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

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

I am confused please help me solve it [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
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]))

How can i add an input in every line of a displayed data? [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 3 years ago.
Improve this question
im trying to have an input in every line of the displayed data.
here are the codes
def attendance():
print ("\n\nList of Students\n")
print ("StudNo StudName Age Course Attendance")
for idx in range(len(studNo)):
print (" {0:15} {1:10s} {2:10s} {3:10s}".format(studNo[idx],
studName[idx], Age[idx], Course[idx]))
and this is the output
List of Students
StudNo StudName Age Course Attendance
a1001 Daryl 21 CS
a1002 Akex 21 CS
a1003 John 24 CS
a1004 Jose 22 CS
im creating a simple attendance monitoring system. so im trying to have an input for each line so i can write A for absent or P for present.
You can use the input function. input("Write your prompt here") will print the prompt and ask the user to write an entry of text. This can get messy with your desired output, so I suggest collecting all attendance information and then printing
students = ['Kathy','Will','Nayeon']
attendanceRecord = []
for student in students:
attendance = input("What is "+student+"\'s attendance? ")
attendanceRecord.append(attendance)
print("\n") # add a space before printing student list
print("Name"+" Attendace")
for i in range(len(students)):
print(students[i] + " "+ attendanceRecord[i])

How can I prompt the user to assign a new name to each value in a list? [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 4 years ago.
Improve this question
So I need to name each item in the list being created from the first user input.
my first line of code is as follows:
num_assessment = int(input('How many assessments per student?'))
Now I need the user to name each item in the list; for example:
How many assessments per student?:2
What type of assessment was assessment 1? Essay
How many marks is the Essay worth? 30
What type of assessment was assessment 2 ? Test
How many marks is the Test worth? 70
What is the function I can use to perform this?
A dictionary with a for loop is one way to structure your data. Below is an example.
num_assessment = int(input('How many assesments per student?\n'))
data = {}
for i in range(1, num_assessment+1):
data_type = input('What type of assessment was assessment {0}?\n'.format(i))
data_marks = int(input('How many marks is the {0} worth?\n'.format(data_type)))
data[i] = {'type': data_type, 'marks': data_marks}
Example
How many assesments per student?
2
What type of assessment was assessment 1?
essay
How many marks is the essay worth?
30
What type of assessment was assessment 2?
assignment
How many marks is the assignment worth?
50
Result
print(data)
{1: {'marks': 30, 'type': 'essay'}, 2: {'marks': 50, 'type': 'assignment'}}
You can try this one :
n = int(input("How many assesments per student? "))
dct_values = {}
for i in range(1,n+1):
asesmnt = input("What type of assessment was assessment "+str(i)+"?
")
marks = int(input("How many marks is the "+asesmnt+" worth? "))
dct_values[i] = [{asesmnt:marks}]
print(dct_values)
It will store all the values in a dict , O/P willl be like this :
{1: [{'Essay': 30}], 2: [{'Test': 70}]}

How can I optimize my simple code (python)? [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 6 years ago.
Improve this question
I'm taking an intro programming class and am working ahead on some assignments that aren't due for a few weeks. This one asks me to take three text files - names, titles, and descriptions - and use them to randomly generate "fantasy character" names. My code runs and does what I want it to, but I feel like it's cluttered and could be cleaned up quite a bit. Keep in mind that this is an INTRO course and in class have just covered basic boolean logic, loops, arrays, etc.; not classes, object-oriented, or any advanced stuff (I'm trying to learn some of this on my own).
import random
def main():
for i in range(10):
# Load names, titles, descriptions into arrays
names = loadFile('names.txt')
title = loadFile('titles.txt')
descriptor = loadFile('descriptors.txt')
# Generate random number based on list length
nameListLength = len(names)
titleListLength = len(title)
descListLength = len(descriptor)
firstNameIndex = random.randrange(nameListLength)
lastNameIndex = random.randrange(nameListLength)
randTitleIndex = random.randrange(titleListLength)
randDescriptor = random.randrange(descListLength)
# Choose random list entry
firstName = names[firstNameIndex]
lastName = names[lastNameIndex]
title2 = title[randTitleIndex]
description = descriptor[randDescriptor]
nameList = [title2, firstName, lastName, description]
dumpFile(nameList)
print(title2, firstName, lastName, 'the', description)
print()
print('These names have been written to \"CharacterNames.txt\".')
def dumpFile(nameList):
title = str(nameList[0])
firstName = str(nameList[1])
lastName = str(nameList[2])
descriptor = str(nameList[3])
outfile = open('CharacterNames.txt', 'a')
outfile.write(title + ' ' + firstName + ' ' + lastName + ' ' +
'the' + ' ' + descriptor + '\n')
outfile.write('\n')
outfile.close()
def loadFile(nameFile):
nameList = open(nameFile, 'r')
nameArray = []
for line in nameList:
name = line
name = name.rstrip('\n')
nameArray.append(name)
nameList.close()
return nameArray
main()
I see value in having others look at your code and rewrite it as they would do it. I kind of ignored your restriction on "any advanced stuff," although I don't think any of it will be too complicated for you to intuit. Here's my rewrite:
import random
def generatePerson(names=loadFile('names.txt'),
titles=loadFile('titles.txt'),
descriptons=loadFile('descriptors.txt')):
firstName = random.choice(names)
lastName = random.choice(names)
title = random.choice(titles)
description = random.choice(descriptons)
return '{} {} {} the {}'.format(title, firstName, lastName, description)
def main():
people = [generatePerson() for _ in range(10)]
dumpFile('\n\n'.join(people))
print('\n'.join(people))
print('\nThese names have been written to "CharacterNames.txt".')
def dumpFile(data, filename='CharacterNames.txt'):
with open(filename, 'a') as outfile:
outfile.write(data)
def loadFile(nameFile):
with open(nameFile, 'r') as nameList:
return nameList.read().splitlines()
if __name__ == '__main__':
main()
It still resembles your code in many ways, however, most of it has been rewritten. Now for details on some of the more drastic changes.
I moved the code related to picking random strings from the three lists into its own function generatePerson. This makes the easier to maintain in case the method of generating a random person or something else changes in the future.
I greatly simplified the logic of picking the random strings by using random.choice.
I used a trick that uses default arguments in generatePerson to avoid reading from the three files each time a random name is created. The only part of this trick that you should know for now is that the values of default arguments are created only once in Python.
Instead of passing a list into dumpFile, I opted to pass a string, which I can then immediately write to the file. This makes more sense because I had generatePerson return the formatted string for that person rather than [title, firstName, lastName, description].
This is mostly just my preference, but I don't really like for-loops, so in main I used a list comprehension to create a list of 10 random names. From there, I used str.join to create a single string with all ten names that is suitable to be passed to dumpFile and print.
I believe that is (nearly) all of the changes I made. If I missed something or if you need further clarification on anything I mentioned either comment on my answer or just ask a new question.
Move file operations before the 'for' loop - there is no need to re-read the files 10 times. That should make the application run much faster.

Categories