is this code, right? if there is an error, could you guide? - python-3.x

i am a complete noob to programming and i got an assignment from the online course where I am learning, mine also gives the output, but it is not same as the instructor's method. This works for me and this method was easy for me.
but i am not sure is this the right method or had i done something wrong? could someone help?
I was not allowed to use choice()
**
import random
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
a=len(names)
random_name=random.randint(0,a)
print(f"{names[random_name]} is going to pay the bill")
**

Welcome!
First of all you need to describe what exactly your problem and what is the problem you are facing.
It looks like you even have not tried to run that code. I will recommend an online interpreter to you to test your code on. You may use that
https://www.online-python.com/
Secondly "import" statement must be in lower case not "Import"
Finally the code works only incase of the string (names) is separated by a comma followed by space ", " same as the split string used. for example "a,b,c" is not going to work, but "a, b, c" does
random.randint(0,a) (a is included; may be returned) so it must be a-1 to avoid IndexError: list index out of range
Fixed code
import random
names_string = input("Give me everybody's names, separated by a comma. ")
names = names_string.split(", ")
a=len(names)
random_name=random.randint(0,a-1)
print(f"{names[random_name]} is going to pay the bill")

no, the code is not right.The error can be solved by replacing "Import" by "import".

Related

Can I make Python check my list to see if user input contains strings in my list using if statements? If not are there any alternatives?

Beginner with Python but I wanted to use a list to contain multiple potential string responses that the user may give in the input.
def Front_Door():
print("Welcome to the Party Friend!")
Emotional_state = input("How are You Today? ")
Positive_Emotion = ["good", "fine", "happy"]
I tried to use an if statement to get python to check through my list to see if the input contained any of the strings listed in the e.g. I gave.
if Positive_Emotion in Emotional_state:
print("That's Great! Happy to have you here!")
The code still manages to prompt me for Emotional_state but it just repeats the question one more time, if I respond with one of then strings I've listed again it gives me this error:
if Positive_Emotion in Emotional_state:
TypeError: 'in <string>' requires string as left operand, not list
I'm guessing there is a method to make Python search through my list of strings and cross reference it with my inputs and give me the response I want?
Any help is appreciated :).
You are checking if the whole list is in the string!
What you probably want to do is check if any of the items in the list are in the string.
Something like:
if any( [emotion in Emotional_state for emotion in Positive_Emotion] ):
print("That's Great! Happy to have you here!")
This will check each emotion in the list, and if any of them are in the string it will return True.
Hope this helps.
I'm all too late to the party, but here are my two cents.
You only need Positive_Emotion and Emotional_state to switch places in your if statement, so that it becomes:
if Emotional_state in Positive_Emotion:
print("That's Great! Happy to have you here!")

Questions regarding Python replace specific texts

I'm writing a script to scrape from another website with Python, and I am facing this question that I have yet to figure out a method to resolve it.
So say I have set to replace this particular string with something else.
word_replace_1 = 'dv'
namelist = soup.title.string.replace(word_replace_1,'11dv')
The script works fine, when the titles are dv234,dv123 etc.
The output will be 11dv234, 11dv123.
However if the titles are, dv234, mixed with dvab123, even though I did not set dvab to be replaced with anything, the script is going to replace it to 11dvab123. What should I do here?
Also, if the title is a combination of alphabits,numbers and Korean characters, say DAV123ㄱㄴㄷ,
how exactly should I make it to only spitting out DAV123, and adding - in between alphabits and numbers?
Python - making a function that would add "-" between letters
This gives me the idea to add - in between all characters, but is there a method to add - between character and number?
the only way atm I can think of is creating a table of replacing them, for example something like this
word_replace_3 = 'a1'
word_replace_4 = 'a2'
.......
and then print them out as
namelist3 = soup.title.string.replace(word_replace_3,'a-1').replace(word_replace_4,'a-2')
This is just slow and not efficient. What would be the best method to resolve this?
Thanks.

Concatenation Not Working

My delay codes are always 3 digits. Two letters a dash (-) and a number. I am trying to use a single line of code to detect either MT or DA, the actual classification number is irrelevant, so I want the message box to fire on the two letters only.
The code looks right, but it doesn't fire as it should. If I take out the wild card it works. I think I have a problem with the concatenation, but I'm not sure. I tried putting () brackets around it but that was not help.
Additionally I tried using an or statement to capture the MT code on the other side but got nothing but an error code for type mismatch. Any ideas?
If Range("L24").Value = "DA" & "*" Then
MsgBox "The flight had a Maintenance delay"
Else
End If
A simple solution to this kind of problem would be to ignore the wildcard altogether and check the first two digits:
If Left(Range("L24").Value, 2) = "DA" Then

With data.table, return between certain characters into a new column

I have a feeling this might be a simple question, but I've searched through SO for a bit now and found many interesting related Q/A, I'm still stumped.
Here's what I need to learn (in honesty, I'm playing with the kaggle Titanic dataset, but I want to use data.table)...
Let's say you have the following data.table:
dt <- data.table(name=c("Johnston, Mr. Bob", "Stone, Mrs. Mary", "Hasberg, Mr. Jason"))
I want my output to be JUST the titles "Mr.", "Mrs.", and "Mr." -- heck we can leave out the period as well.
I've been playing around (all night) and discovered that using regular expressions might hold the answer, but I've only been able to get that to work on a single string, not with the whole data.table.
For example,
substr(dt$name[1], gregexpr(",.", dt$name[1]), gregexpr("[.]", dt$name[1]))
Returns:
[1] ", Mr."
Which is cool, and I can do some further processing to get rid of the ", " and ".", but, the optimist(/optimizer) in me feels that that's ugly, gross, and inefficent.
Besides, even if I wanted to settle on that, (it pains me to admit) I don't know how to apply that into the J of data.table....
So, how do I add a column to dt called "Title", that contains:
[1] "Mr"
[2] "Mrs"
[3] "Mr"
I firmly believe that if I'm able to use regular expressions to select and extract data within a data.table that I will probably use this 100x a day. So thank you in advance for helping me figure out this pivotal technique.
PS. I'm an excel refugee, in excel I would just do this:
=mid(data, find(", ", data), find(".", data))
Umm.. I may have figured it out:
dt[, Title:=sub(".*?, (.*?)[.].*", "\\1", name)]
But I'm going to leave this here in case anyone else needs help, or perhaps there's an even better way of doing this!
You can use the stringr package
library(stringr)
str_extract(dt$name, "M.+\\.")
[1] "Mr." "Mrs." "Mr."
Different variations on the regular expression will let you extract other titles, like Dr., Master, or Reverend which may also be of interest to you.
To get all characters between "," and "." (inclusive) you can use
str_extract(dt$name, ",.+\\.")
and then remove the first and last characters of the result with str_sub (also from stringr package).
But as I think about it more, I might use grepl to create indicator variables for all the different titles that are in the Titanic dataset. For example
dr_ind <- grepl("Dr|Doctor", dt$name)
titled_ind <- grepl("Count|Countess|Baron", dt$name)
etc.

Read a string and create an acronym from the first initial letter of every word on the string

I just wrote a code with the criteria above, but it doesn't seem to work properly because I either miss a letter at the end or in the middle.
Could anyone please check out my code an tell me what I'm doing wrong. By the way I already checked other threads on this similar problem, but I'm not allowed to use regex or print function.
phrase=('my room is cold')
allSpaces=findstr(' ',phrase);
k=length(allSpaces)
acr=phrase(1:allSpaces(1):allSpaces(k)-1)
Output:
acr= mrms
Change last line to
acr = phrase([1 allSpaces+1])
That way you get the first letter, and then the first after each space.

Resources