If statement for multiple values - python

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)

Related

Creating two and one condition in a program

I have a code that allows a user to choose between 3 options
0- Beginner
1- Intermediate
2: Advanced
The code I have is:
if inp == 0:
out = "Beginner"
elif inp == 1:
out = "Intermediate"
elif inp == 2:
out = "Advanced"
else:
print("Invalid")
However, I'm wanting it so if a number greater than 3 was entered, it won't proceed to the second part.
The second part of the code I have is:
x=float(input("Choose a number between [0,90]"))
if x > 0 and x < 90:
print("Is Latitude in the North or South Hemisphere?")
else:
print ("Invalid")
Can someone provide some insight into how the condition is supposed to be?
Thank you!
You can do it with your code if you test for the existence of out before the second section.
You just need to initialise out before the if
out = ""
if inp == 0:
out = "Beginner"
elif inp == 1:
out = "Intermediate"
elif inp == 2:
out = "Advanced"
else:
print("Invalid")
Now, because out has become a global variable, you can test for whether or not out has been set. If out is not set, this next section is skipped.
if out:
x=float(input("Choose a number between [0,90]"))
if x > 0 and x < 90:
print("Is Latitude in the North or South Hemisphere?")
else:
print ("Invalid")
Realistically though, there's a ton of different ways you can do this. Personally, I'd probably use a function and then a return statement out of it to stop execution, but you can also break out and stop things that way or use some form of loop to wait for the variable you want.
The great thing and the frustrating thing about programming is there's normally more than one way to get it right.

How do I add different levels & a quit option to my guess a number game?

So I'm a freshman in high school trying to figure out Python coding, and I need to make a guess a number game.
My first level works fine, but I need to make it so it has 3 different levels, and a quit option. I don't understand these while loops.
I'm really sorry if I posted something wrong or this is an already asked question, but any help would be much appreciated!
Here's my code so far:
import random
print("let's play guess a number!")
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
while number1!=guess1:
print
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
if guess1==number1:
print("you guessed it!")
if myLevel == 2:
nextumber2= random.randint (1,100)
guess2=int(input("guess an integer from 1 to 100"))
while number2!=guess2:
print
if guess2<number2:
print("guess is too low!")
guess2=int(input("guess again!"))
elif guess2>number2:
print("guess is too high!")
guess2=int(input("guess again!"))
print("you guessed it!")
Welcome to Python! Since you're new I'll go over the fundamentals of everything you need to learn to complete this game.
Your code looks good so far. Since your question is mainly about a while loop, you'll need to learn what exactly that does. A while loop is a block of code that first checks the provided condition, then executes the indented code block if the condition evaluates to true. Then, it checks the condition again, and executes the code again if it's still true. This continues until the condition evaluates to false.
x = 0
while x < 5:
print(x)
x += 1
Try this code out. It should print 0 to 4 then stop when x = 5.
What's actually happening:
x = 0
# loop starts here
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #false
# At this point, x is not longer < 5, so the repeating stops and the code continues to run as normal.
Imagine if you wanted to print numbers from 1 to 50. Would you rather have a loop, or do each number by hand like the above? In fact, if you want to print from 1 to x, where you don't know what x will be beforehand, you'll need a loop!
While loops are extremely powerful and are used all over the place. The idea is that you want to do something until some sort of flag or condition occurs, then stop doing the thing. I hope that makes sense.
Secondly, you need to learn about the input function.
x = input()
The input function is just a regular function that returns a string with the user input. If you want to make it into a number, then you have to typecast it to the type of number you want.
x = int(input())
You're already doing this. But what if you want a string?
Let's get back to your code:
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
# User inputs "quit"
>> ValueError: invalid literal for int() with base 10: 'quit'
This happens because we already converted our input to an int. However, at no point are we doing any math with MyLevel. Here's a better way:
myLevel = input("would you like to play level 1, 2, 3, or quit?")
if myLevel == "quit":
exit() # this exits a python program entirely.
if myLevel == "1":
#do level 1 stuff
if myLevel == "2":
#do level 2 stuff
if myLevel == "3":
#do level 3 stuff
Our lives are made easier by not converting this variable. However, it's correct to convert the guess-a-number input() results because those need to be compared to other numbers.
Finally, this project is meant to teach you a very valuable lesson! Don't repeat yourself in the code. If you find yourself doing ANYTHING twice (or any number of times more than one), then use a function, loop, or other construct to condense it. We'll use your project as an example. I updated the code to get it working.
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
# This whole while loop needs to be within the "if" statement's indented block.
# Why? Because we only want to execute the code *if* we're on level 1.
while number1!=guess1:
print(str(number1) + " isn't correct.") #fixed this
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
# The last if statement isn't needed so I took it out.
# Why? Because if the loop ends, it's because guess1==number1. So our condition
# always returns true. Therefore, we can just move the print statement outside of the
# while loop.
print("you guessed it!")
This is a fine start and it should be working. Now, what do we do for level 2? The first thing that comes to mind is to copy paste this whole code block... but that would be repeating ourself! We're going to reject that idea straight out because we don't repeat ourselves.
Instead, let's use a function to wrap up the core of the game into a nice little repeatable action. Functions are just repeatable actions.
# define a function with a variable to hold the highest possible guess
def guess(max):
# get a random number based on our max
number = random.randint(1,max)
guess = int(input("guess an integer from 1 to " + str(max)))
while number != guess: # Guess is wrong
if guess < number:
print("guess is too low")
elif guess > number:
print("guess is too high!")
# Since guess is wrong, we can just assume we'll always do this.
# I removed the int() wrapper for the next step
guess = input("guess again! or would you like to quit?")
# Adding "quit" as an option:
if guess == "quit":
exit()
else:
guess = int(guess) # Now we can convert to int for our comparisons.
print("you guessed it!")
With this defined, now we just need to call the function itself at the correct difficulty.
if myLevel == "1":
guess(10)
if myLevel == "2":
guess(100)
if myLevel == "3":
guess(500)
If you're still alive after reading all this, hopefully you noticed a problem here -- we're repeating ourselves with 3 different if statements. We can do better, but that's a lesson for another day!
tl;dr:
1) Input returns a string, so you converted it to an int immediately. However, a string of "quit" is a valid choice and this will give you an error if you convert it to an int. Instead, test for "quit" first, then convert to an int if needed.
2) A while loop is for repeating something until some sort of condition is cleared. Loops and if statements can be nested within other statements. Think about when you want your code to run and honestly just practice a bit to make this more natural.
3) If you're repeating something in your code (copy/pasting similar things over and over again), strongly consider making a function or loop or something similar to do the work for you!
For the quit it's simple. Either use quit(), or, if you don't want to reload the program, put everything in a while loop and have the quit function set it to false, and then true after a while. For the 3 levels, you could either write 3 entirely separate programs or use if statements to change numbers or something. I'm not sure that would work, though.
As for your while problem, just use while some_variable='whatever_you_want': and you're done.

How to run a function several times for different results in Python 3

EDIT: Thanks for each very detailed explanations for the solutions, this community is golden for someone trying to learn coding!! #DYZ, #Rob
I'm a newbie in programming, and I'm trying to make a simple lotto guesses script in Python 3.
The user inputs how many guesses they need, and the program should run the function that many times.
But instead my code prints the same results that many times. Can you help me with this?
I'm pasting my code below, alternatively I guess you can run it directly from here : https://repl.it/#AEE/PersonalLottoEn
from random import randint
def loto(limit):
while len(guess) <= 6: #will continue until 6 numbers are found
num = randint(1, limit)
#and all numbers must be unique in the list
if num not in guess:
guess.append(num)
else:
continue
return guess
guess = [] #Need to create an empty list 1st
#User input to select which type of lotto (6/49 or 6/54)
while True:
choice = int(input("""Please enter your choice:
For Lotto A enter "1"
For Lotto B enter "2"
------>"""))
if choice == 1:
lim = 49 #6/49
break
elif choice == 2:
lim = 54 #6/54
break
else:
print("\n1 or 2 please!\n")
times = int(input("\nHow many guesses do you need?"))
print("\nYour lucky numbers are:\n")
for i in range(times):
result = str(sorted(loto(lim)))
print(result.strip("[]"))
Your loto function is operating on a global variable, guess. Global variables maintain their values, even across function calls. The first time loto() is called, guess is []. But the second time it is called, it still has the 6 values from the first call, so your while loop isn't executed.
A solution is to make the guess variable local to the loto() function.
Try this:
def loto(limit):
guess = [] #Need to create an empty list 1st
while len(guess) <= 6: #will continue until 6 numbers are found
num = randint(1, limit)
#and all numbers must be unique in the list
if num not in guess:
guess.append(num)
else:
continue
return guess

Simpler If Statements

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'.

How do you make a while loop in python that stops two variables with the same answer?

I'm trying to make a 'who wants to be a millionaire' style program with random questions, random answers in random places (in Python). I'm struggling to form a while loop that repeats itself so that two variables are never the same.
My loop (that clearly doesn't work) is:
while rnd4 == rnd2:
rnd4 = random.randint(1,3)
break
In context of my current program:
if rnd2 == 1:
position1 = answer #the random question has already been printed and the
#answer set
elif rnd2 == 2:
position2 = answer
elif rnd2 == 3:
position3 = answer
rnd3 = random.randint(1,4)
rnd4 = random.randint(1,3)
while rnd3 == rnd1:
rnd3 = random.randint(1,4) #these loops are meant to mean that the same
break #answer is never repeated twice + the same
while rnd4 == rnd2: #position is never overwritten
rnd4 = random.randint(1,3)
break
if rnd3 == 1:
if rnd4 == 1:
position1 = (no1[1])
elif rnd4 == 2:
position2 = (no1[1])
elif rnd4 == 3:
position3 = (no1[1])
... (code skipped)
print (position1)
print (position2)
print (position3)
Due to the random nature of the program it has been difficult to test but I'm expecting a format like:
q1
answer
() #only two of the positions have had code written for them yet
random answer
Or a combination of the above. (basically one right answer and one wrong answer in different positions)
Ocassionally I get:
q1
answer
answer
()
or
q1
random answer
()
()
So this is obviously wrong with sometimes the same answer printed twice or the wrong answer overwriting the right one.
Apologies for such a long drawn out question with probably a very simple answer (how to fix the loop) but I know I'm not supposed to ask for code!!
Thanks a lot!
Delete those break statements and it should work.
Assume your two variables are equal. Then you enter the loop, and you create a new value for rnd4. The next step would be to check if the 2 variables are now different, if not, repeat. But before you get to the while clause again you break out of the loop. So effectively you run the loop body at most once.
In Your Example break statement in while loops seems to be unnecessary.
this brake ends loop even if numbers are equal.
As I understand main ussue is to generate rnd1 ... rnd4
can You try random.shuffle for these purposes
a = range(1, 5)
random.shuffle(a)
rnd1, rnd2, rnd3, rnd4 = a
random.shuffle shuffle the sequence x in place. so one can generate sequence with desired values and shuffle it

Categories

Resources