Simpler If Statements - python

I have very little coding experience with Python, and am making a game for a Python coding class. I don't know any complicated stuff except this.
Is there a way to simplify the if statements from the code provided below to possibly one single if statement to reduce repetition? I have many more of these that will have to do many more rather than 4 numbers. Thanks.
import random
hero = random.randint(1,4)
if hero == 1:
print 'Marth'
elif hero == 2:
print 'Lucina'
elif hero == 3:
print 'Robin'
else:
print 'Tiki'

Use random.choice
import random
hero = ['Marth', 'Lucina', 'Robina', 'Tiki']
print(random.choice(hero))

import random
hero_list = ['Marth', 'Lucina', 'Robin', 'Tiki']
print hero_list[random.randint(0, len(hero_list)-1)]

import random
def GetHeroName(x):
return {
1 : 'Marth',
2 : 'Lucina',
3 : 'Robin'
}.get(x, 'Tiki')
hero = random.randint(1,4)
print GetHeroName(hero)
Note: the get(x, 'Tiki') statement is saying get x, but if that fails default to 'Tiki'.

Related

Conditional statement not working with input function

i'm just writing a simple program that should give me a random integer between 1 and 10 if i input the value of 'r'in code. here's what i have:
import sys, random
from random import *
def randomly():
return (randint(1, 10))
while True:
x = input("input string ")
x = str(x)
print (x)
if x == 'r':
print ("your generated number is", randomly())
else:
break
i know there's just something small i'm overlooking. but i can't figure out what. the randomly function works. and if i replace the 'r' conditional with an integer (i used 1) convert x with int(x) and then input 1 the program works fine. like so:
import sys, random
from random import *
def randomly():
return (randint(1, 10))
while True:
x = input("input number ")
x = int(x)
print (x)
if x == 1:
print ("your generated number is", randomly())
else:
break
for some reason the if conditional won't respond to my string. i tried x.lower() and it still won't work, while it's true that just using the method i described before with the integer would work fine. it frustrates me that my code won't work the way i want it to. for what it's worth i checked len(x) and it says 2 when i input a single character(r). i'm fairly novice to python but i have the knowledge i need, at least, to write a program like this. any help would be greatly appreciated.
i'm using visual studio 2015
python environment: python 3.2
this is my first question here. i searched to the best of my capabilities and couldn't find an answer. i apologize in advance if there is anything wrong with my question.

How do I get a random object from a list, only once per object? [duplicate]

Sorry if this is obvious, im pretty new.
Here is the code.
It should never print the same two things as i understand it, but it sometimes does. The point is that p1 being 1 should prevent p2 from being 1, and if p2 is 1, p2 should run again with the same p1 value, but should generate a new random number. It might be 1 again, but then the function should just keep returning else and running until they're different, right?
#Random Test with Exclusion
P1Item = 'Empty'
P2Item = 'Empty'
import random
import time
def P1():
global P1Item
global P2Exclusion
P1Local = random.randint(1,3)
if P1Local == 1:
P1Item = 'Candy'
P2(P1Local)
elif P1Local == 2:
P1Item = 'Steak'
P2(P1Local)
elif P1Local == 3:
P1Item = 'Vegetables'
P2(P1Local)
def P2(A):
global P2Item
P2Local = random.randint(1,3)
if P2Local == 1 and A != 1:
P2Item = 'Candy'
elif P2Local == 2 and A != 2:
P2Item = 'Steak'
elif P2Local == 3 and A != 3:
P3Item = 'Vegetables'
else:
B = A
P2(B)
def Test():
print('Test')
print('Define')
P1()
print(P1Item + ' ' + P2Item)
time.sleep(1)
input()
Test()
Test()
Instead of picking random integers, shuffle a list and pick the first two items:
import random
choices = ['Candy', 'Steak', 'Vegetables']
random.shuffle(choices)
item1, item2 = choices[:2]
Because we shuffled a list of possible choices first, then picked the first two, you can guarantee that item1 and item2 are never equal to one another.
Using random.shuffle() leaves the option open to do something with the remaining choices; you only have 1 here, but in a larger set you can continue to pick items that have so far not been picked:
choices = list(range(100))
random.shuffle(choices)
while choices:
if input('Do you want another random number? (Y/N)' ).lower() == 'n':
break
print(choices.pop())
would give you 100 random numbers without repeating.
If all you need is a random sample of 2, use random.sample() instead:
import random
choices = ['Candy', 'Steak', 'Vegetables']
item1, item2 = random.sample(choices, 2)
You can use the random module in Python to do the heavy lifting for you, specifically random.sample():
>>> import random
>>> random.sample(['candy', 'steak', 'vegetable'], 2)
['vegetable', 'steak']
if you want to keep the original logic, here is some pseudo code:
while(P2Local == A)
P2Local = random.randint(1,3)
from random import choice
x = ['foo','bar','fight']
num_uniq = 2
uniq_rand = set()
while len(uniq_rand) < num_uniq:
uniq_rand.add(choice(x))
print uniq_rand
As #Martijn pointed out, this is not surely not as efficient as random.sample() =)

If statement for multiple values

Here is my aim in an example. If you could help me complete it that would be great!
exampleNumbers = [One,Uno,Two,Dos]
randomNumber = random.choice(exampleNumbers)
From here on I want it to then change randomNumber to 1 if the random selection of exampleNumbersis One or Uno or change randomNumber to 2 if the random selection of exampleNumbers is Two or Dos.
I think I can do it using an if statement, however I am unsure on how to use an if statement with multiple values.
So basically if the random selection is Two for example, I want it to then make randomNumber = 2.
Sorry if I haven't explained this very well, I'm slowly getting there but my knowledge and terminology is still at an amateur state. I'll happily tick and vote up any great answers!
Thanks in advance! :)
You can use the operator in:
if randomNumber in (One,Uno):
randomNumber = 1
else:
randomNumber = 2
Or the classic or boolean operator:
if randomNumber == One or randomNumber == Uno:
randomNumber = 1
else:
randomNumber = 2
The in is great to check for a lot of values.
The or, with the other boolean operators and and not can be used to build arbitrarily complex logical expressions.
you can use and and or to compound statements. and for multiple statements you can also use parenthesis (ie: (True and False) or (False or True)). There does exist an order of operations which is basically left to right. So for you question you can do
if(num == "two" or num == "dos"):
//do things
elif (num == "one" or num == "uno"):
//do other things
You could also define options:
options = { One : thisIsOne,
Uno : thisIsOne,
Two : thisIsTwo,
Dos : thisIsTwo,
}
def thisIsOne()
randomNumber = 1
def thisIsTwo()
randomNumber = 2
You can then simply call options[randomNumber]()
I'm a little rusty with my python but I'm pretty sure that works (but so does the previous answer by rodrigo! matter of preference and reusability)

python variable NameError

I am having trouble with assigning values to vars and then accessing the values. For example:
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"
tSizeAns = raw_input()
if tSizeAns == 1:
tSize = "100Mb"
elif tSizeAns == 2:
tSize = "250Mb"
else:
tSize = 100Mb # in case user fails to enter either a 1 or 2
print "\nYou want to create a random song list that is " + tSize + "."
Traceback returns:
Traceback (most recent call last):
File "./ranSongList.py", line 87, in <module>
print "\nYou want to create a random song list that is " + tSize + "."
NameError: name 'tSize' is not defined
I have read up on python variables and they do not need to be declared so I am thinking they can be created and used on the fly, no? If so I am not quite sure what the traceback is trying to tell me.
By the way, it appears as though python does not offer 'case' capabilities, so if anyone has any suggestions how to better offer users lists from which to choose options and assign var values I would appreciate reading them. Eventually when time allows I will learn Tkinter and port to GUI.
Your if statements are checking for int values. raw_input returns a string. Change the following line:
tSizeAns = raw_input()
to
tSizeAns = int(raw_input())
This should do it:
#!/usr/local/cpython-2.7/bin/python
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"
tSizeAns = int(raw_input())
if tSizeAns == 1:
tSize = "100Mb"
elif tSizeAns == 2:
tSize = "250Mb"
else:
tSize = "100Mb" # in case user fails to enter either a 1 or 2
print "\nYou want to create a random song list that is {}.".format(tSize)
BTW, in case you're open to moving to Python 3.x, the differences are slight:
#!/usr/local/cpython-3.3/bin/python
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print("\nHow much space should the random song list occupy?\n")
print("1. 100Mb")
print("2. 250Mb\n")
tSizeAns = int(input())
if tSizeAns == 1:
tSize = "100Mb"
elif tSizeAns == 2:
tSize = "250Mb"
else:
tSize = "100Mb" # in case user fails to enter either a 1 or 2
print("\nYou want to create a random song list that is {}.".format(tSize))
HTH
In addition to the missing quotes around 100Mb in the last else, you also want to quote the constants in your if-statements if tSizeAns == "1":, because raw_input returns a string, which in comparison with an integer will always return false.
However the missing quotes are not the reason for the particular error message, because it would result in an syntax error before execution. Please check your posted code. I cannot reproduce the error message.
Also if ... elif ... else in the way you use it is basically equivalent to a case or switch in other languages and is neither less readable nor much longer. It is fine to use here. One other way that might be a good idea to use if you just want to assign a value based on another value is a dictionary lookup:
tSize = {"1": "100Mb", "2": "200Mb"}[tSizeAns]
This however does only work as long as tSizeAns is guaranteed to be in the range of tSize. Otherwise you would have to either catch the KeyError exception or use a defaultdict:
lookup = {"1": "100Mb", "2": "200Mb"}
try:
tSize = lookup[tSizeAns]
except KeyError:
tSize = "100Mb"
or
from collections import defaultdict
[...]
lookup = defaultdict(lambda: "100Mb", {"1": "100Mb", "2": "200Mb"})
tSize = lookup[tSizeAns]
In your case I think these methods are not justified for two values. However you could use the dictionary to construct the initial output at the same time.
Initialize tSize to
tSize = ""
before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.
I would approach it like this:
sizes = [100, 250]
print "How much space should the random song list occupy?"
print '\n'.join("{0}. {1}Mb".format(n, s)
for n, s in enumerate(sizes, 1)) # present choices
choice = int(raw_input("Enter choice:")) # throws error if not int
size = sizes[0] # safe starting choice
if choice in range(2, len(sizes) + 1):
size = sizes[choice - 1] # note index offset from choice
print "You want to create a random song list that is {0}Mb.".format(size)
You could also loop until you get an acceptable answer and cover yourself in case of error:
choice = 0
while choice not in range(1, len(sizes) + 1): # loop
try: # guard against error
choice = int(raw_input(...))
except ValueError: # couldn't make an int
print "Please enter a number"
choice = 0
size = sizes[choice - 1] # now definitely valid
You forgot a few quotations:
# offer users choice for how large of a song list they want to create
# in order to determine (roughly) how many songs to copy
print "\nHow much space should the random song list occupy?\n"
print "1. 100Mb"
print "2. 250Mb\n"
tSizeAns = raw_input()
if tSizeAns == "1":
tSize = "100Mb"
elif tSizeAns == "2":
tSize = "250Mb"
else:
tSize = "100Mb" # in case user fails to enter either a 1 or 2
print "\nYou want to create a random song list that is " + tSize + "."

Fight simulator with random numbers

I'm trying to create a function that simulates a fight. So far I have a list and something that picks at random one of them that I found in another post. I can't seem to make an if statement that prints out “Hit!” or “Dodge!” or “Critical Hit!” when it chooses the respective word because it gives a syntax error for whatever reason. Can anyone help me? What do I do so I can make the if statement?
Health = 10
dodge = 1
dmg = 1
hit = dmg + 1
crhit = hit * 2
def fight():
while 1 == 1:
global Health
global dodge
global hit
global dmg
chances = [hit, hit, dodge, crhit, hit]
from random import choice
fight()
You have only imported the function choice, you still have to call it:
from random import choice # This makes it so we can use the function in the script.
Health = 10
dodge = 1
dmg = 1
hit = dmg + 1
crhit = hit * 2
def fight():
while 1:
mychoice = choice(chances) # We call the function. It gets a random value from the list
if mychoice == hit: # Create an if/elif for each possible outcome
dostuff()
elif ...
fight()
Then you can use an if/elif structure to do stuff with each option
Also, those global statements are not needed, as you actually aren't modifying the variables themselves (Unless you plan on doing this later).
while 1 == 1 can simply be written as while 1, as that can also be considered True.
I'm not gonna give away the entire answer, since you should work at that, but doing random.choice(testList) returns a random element from the list, you can use these to get one from hit, dodge and crhit. You can just write three if-elif statements to check for each. Short examples (you should get your answer from here),
>>> varOne = 2
>>> varTwo = 3
>>> varThree = 4
>>> from random import choice
>>> testVar = choice([varOne, varTwo, varThree])
>>> if testVar == varOne:
print 'abc'
elif testVar == varTwo:
print 'def'
else:
print 'ghi'
abc

Categories

Resources