Asking multiple things in an if statement? - python

im new to StackOverflow and Python, I am working on my first program that is not hello world, it is a simple rock, paper, scissors game.
So, my question is can you ask multiple things in an if statement?
quick sample
sport = raw_input("Whats a good sport?")
if sport == 'Football','Soccer','Hockey':
print 'Those are fun sports!'
elif sport != 'Football','Soccer','Hockey':
print 'I dont like those sports!'
I know there are ways to fix that code but I am curious as to if that is a thing?

You can use and and or:
if sport == "Fooball" or sport == "Soccer":
print "those are fun sports!"
You can also check for a string in a list (or in the following example, a tuple) of strings:
if sport in ("Football", "Soccer", "Hockey"):
print "those are fun sports"

You could also use regular expressions to find if the sport is fun or not. The benefit to regular expressions is that it makes it easy to handle different scenarios. For example if the user inputted football instead of Football you could still determine that the sport is fun or not.
import re
pattern = re.compile('[fF]ootball|[sS]occer|[hH]ockey')
sport = 'Football'
if pattern.search("Football"):
print sport + " is fun"
else:
print sport + " is not fun"
For more info:
https://docs.python.org/3.5/howto/regex.htmlYou

Related

How to give a space between 'apple' and 'is ' in a code written in python?

I have coded Apple is the favorite fruit of SP in python.
But in the output, I got: Appleis the favorite fruit of SP
Plz, help me to identify the mistake and tell me how to add a space between Apple and is.
The code is:
hey = "hello world"
print(hey)
name = "sp"
food = "apple"
print(str(food) + "is the favourite fruit of " + str(name))
You can also use "formatted string literals" (a.k.a. "f-strings", available since Python 3.6) to make it easier on yourself:
>>> f"{food} is the favourite fruit of {name}"
apple is the favourite fruit of sp
Just like what the other answers suggest, you can use f-strings to join things together.
However, if you want to use the same method as in your question, you an do this:
hey = "hello world"
print(hey)
name = "sp"
food = "apple"
print(str(food) + " is the favourite fruit of " + str(name))
The difference here is that there is a space before the word is,
so instead of being "is the favourite..." it becomes " is the favourite...".
This will add a space just after str(food) and so there will be a space in between apple and is.
Hope this was helpful :-)
2 easy ways, first your food could be "apple ", or in your string, insert a space before + "is..., so " is....." In either case, you need to add a space.
You can use format printing here,
hey = "Hello world"
print(hey)
name = "sp"
food = "apple"
print(f"{food} is the favourite food of the {name}")
output
Hello world
apple is the favourite food of the sp
The simplest answer for you is adding a space after the double quotes before the "s".
hey = "hello world"
print(hey)
name = "sp"
food = "apple"
print(str(food) + " is the favourite fruit of " + str(name))
The next step would be using commas instead of the "+" symbols to which a space is automatically made, and you won't feel like you have to define the data type.
print(food, "is the favourite fruit of",name)
The best answer that will be most useful in most situations is using an f-string where you type "f" before your string and then place curly brackets "{}" with your variables enclosed. I think you'll find this to be more comfortable and natural.
print(f'{food} is the favourite fruit of {name}')

What is the most pythonic way to iterate through a long list of strings and structure new lists from that original list?

I have a large list of strings of song lyrics. Each element in the list is a song, and each song has multiple lines and some of those lines are headers such as '[Intro]', '[Chorus]' etc. I'm trying to iterate through the list and create new lists where each new list is comprised of all the lines in a certain section like '[Intro]' or '[Chorus]'. Once I achieve this I want to create a Pandas data frame where each row are all the song lyrics and each column is that section(Intro, Chorus, Verse 1, etc.) of the song. Am I thinking about this the right way? Here's an example of 1 element in the list and my current partial attempt to iterate and store:
song_index_number = 0
line_index_in_song = 0
intro = []
bridge = []
verse1 = []
prechorus = []
chorus = []
verse2 = []
verse3 = []
verse4 = []
verse5 = []
outro = []
lyrics_by_song[30]
['[Intro]',
'(Just the two of us, just the two of us)',
'Baby, your dada loves you',
"And I'ma always be here for you",
'(Just the two of us, just the two of us)',
'No matter what happens',
"You're all I got in this world",
'(Just the two of us, just the two of us)',
"I would never give you up for nothin'",
'(Just the two of us, just the two of us)',
'Nobody in this world is ever gonna keep you from me',
'I love you',
'',
'[Verse 1]',
"C'mon Hai-Hai, we goin' to the beach",
'Grab a couple of toys and let Dada strap you in the car seat',
"Oh, where's Mama? She's takin' a little nap in the trunk",
"Oh, that smell? Dada must've runned over a skunk",
"Now, I know what you're thinkin', it's kind of late to go swimmin'",
"But you know your Mama, she's one of those type of women",
"That do crazy things, and if she don't get her way, she'll throw a fit",
"Don't play with Dada's toy knife, honey, let go of it (No)",
"And don't look so upset, why you actin' bashful?",
"Don't you wanna help Dada build a sandcastle? (Yeah)",
'And Mama said she wants to show you how far she can float',
"And don't worry about that little boo-boo on her throat",
"It's just a little scratch, it don't hurt",
"Her was eatin' dinner while you were sweepin'",
'And spilled ketchup on her shirt',
"Mama's messy, ain't she? We'll let her wash off in the water",
"And me and you can play by ourselves, can't we?",
'',
'[Chorus]',
'Just the two of us, just the two of us',....
for line in lyrics_by_song:
if lyrics_by_song == '[Intro]':
intro.append(line)
Refer to python's doc: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
you could also use this
Intro = lyrics_by_song[lyrics_by_song.index('[Intro]'):lyrics_by_song.index('something_else')]
See top answer here: Understanding slice notation

How to return a word in a string if it starts with a certain character? (Python)

I'm building a reddit bot for practice that converts US dollars into other commonly used currencies, and I've managed to get the conversion part working fine, but now I'm a bit stuck trying to pass the characters that directly follow a dollar sign to the converter.
This is sort of how I want it to work:
def run_bot():
subreddit = r.get_subreddit("randomsubreddit")
comments = subreddit.get_comments(limit=25)
for comment in comments:
comment_text = comment.body
#If comment contains a string that starts with '$'
# Pass the rest of the 'word' to a variable
So for example, if it were going over a comment like this:
"I bought a boat for $5000 and it's awesome"
It would assign '5000' to a variable that I would then put through my converter
What would be the best way to do this?
(Hopefully that's enough information to go off, but if people are confused I'll add more)
You could use re.findall function.
>>> import re
>>> re.findall(r'\$(\d+)', "I bought a boat for $5000 and it's awesome")
['5000']
>>> re.findall(r'\$(\d+(?:\.\d+)?)', "I bought two boats for $5000 $5000.45")
['5000', '5000.45']
OR
>>> s = "I bought a boat for $5000 and it's awesome"
>>> [i[1:] for i in s.split() if i.startswith('$')]
['5000']
If you dealing with prices as in float number, you can use this:
import re
s = "I bought a boat for $5000 and it's awesome"
matches = re.findall("\$(\d*\.\d+|\d+)", s)
print(matches) # ['5000']
s2 = "I bought a boat for $5000.52 and it's awesome"
matches = re.findall("\$(\d*\.\d+|\d+)", s2)
print(matches) # ['5000.52']

Conditional statements with multiple if statements (Involves raw_input)

I'm experimenting with raw_input and it works fine except for my 1st if statement and my else statement. Whenever I run the code and answer the 2nd question with a raw_input listed after 'League' in the 1st if statement, it returns both the 1st if's print and the else's print when it should only print the 1st if. Any idea what's wrong?
name = raw_input('What is your name?\n')
game = raw_input('\nWhat MOBA do you play/have played? \n(The answer ' \
'must be case sensitive i.e. LoL for League and DoTA for y\'know the whole darn thing '\
'is too '\
'darn long to say even though I typed a lot more than the name)\n')
if game in ('League' , 'League of Legends' , 'LoL'):
print '\nYou go girl! '
if game in ('DoTA' , 'DoTA 2' , 'DoTA2'):
print '\nThat\'s cool and all but........ Go play League you dang noob. '
else:
print '\nAre you kidding me? You play %s? I\'m severely disappointed in you %s. You ' \
'should at least be playing ' \
'one of these popular games. \nShame, shame, shame. Go install one. ' % (game, name)
you can always use if for the first conditional, elif for any number of other conditionals (if the input is in the second list in your instance) and else if the input is not in any of those lists, your indentation is also a little messed up,nesting if statements inside each other will only run the nested conditional if the first statement is true, I'd also recommend you use the string.lower() method on your users input so you don't have to instruct the user to type case-sensitive input and use variables to store those lists so you can reuse them elsewhere in your code..something like this:
name = raw_input('What is your name?\n')
game = (raw_input('\nWhat MOBA do you play/have played?')).lower()
awesomeGames=['league' , 'league of legends' , 'lol']
coolGames=['dota' , 'dota 2' , 'dota2']
if game in awesomeGames:
print '\nYou go girl! '
elif game in coolGames:
print '\nThat\'s cool and all but........ Go play League you dang noob. '
else:
print '\nAre you kidding me? You play %s? I\'m severely disappointed in you %s. You ' \
'should at least be playing ' \
'one of these popular games. \nShame, shame, shame. Go install one. ' % (game, name)
The indent level is incorrect.
Spend one more space for the second if statement.
or 1 less space and elif instead of the second if.
Replace the second if condition by elif. elif can be used as many times as you want until the condition matches but its better practice to have the last condition as else (which is like default statement when other conditions have failed)

Manipulating strings in python - concentrating on part of a user's input

resp = raw_input("What is your favorite fruit?\n")
if "I like" in resp:
print "%s" - "I like" + " is a delicious fruit." % resp
else:
print "Bubbles and beans."
OK I know this code doesn't work, and I know why. You can't subtract strings from each other like numbers.
But is there a way to break apart a string and only use part of the response?
And by "is there a way" I really mean "how," because anything is possible in programming. :D
I'm trying to write my first chatterbot from scratch.
One option would be to simply replace the part that you want to remove with an empty string:
resp = raw_input("What is your favorite fruit?\n")
if "I like" in resp:
print "%s is a delicious fruit." % (resp.replace("I like ", ""))
else:
print "Bubbles and beans."
If you want to look into more advanced pattern matching to grab out more specific parts of strings via flexible patterns, you might want to look into regular expressions.
# python
"I like turtles".replace("I like ","")
'turtles'
Here's a way to do it with regular expressions:
In [1]: import re
In [2]: pat = r'(I like )*(\w+)( is a delicious fruit)*'
In [3]: print re.match(pat, 'I like apples').groups()[1]
apples
In [4]: print re.match(pat, 'apple is a delicious fruit').groups()[1]
apple
Can you just strip "I like"?
resp.strip("I like")
be careful of case sensitivity though.

Categories