I'm just getting started with coding and took python as my first language. I decided to do this guessing number mini-project and I've gotten this far. It works perfectly but I want the user to only input a number between 1-10 and if it exceeds that or other input is given that isn't in that range. I want to print out a text.
I have been scouring the python documentation and haven't found anything, I'm pretty sure it's something pretty simple in the conditions but I can't figure out what it is.
Also if you see any way that this code could be improved please tell me I would love to know it
def game():
mysteryNumber = random.randint(1,10)
print("I just guessed a number.")
inputByUser = input("Now choose a number from 1 to 10 : ")
chosenNumber = int(inputByUser)
if mysteryNumber == chosenNumber:
print("You guessed it right.")
elif mysteryNumber > chosenNumber:
print("Too low. Try again buddy.")
elif mysteryNumber < chosenNumber:
print("Too high. Try again buddy.")
else:
print("The number you chose ' {} ' is not a valid number.".format(chosenNumber))
Here is a picture of the full code
EDIT: Nevermind I figured it myself I added this line of code after the first if statement
elif chosenNumber > 10:
print("The number you chose ' {} ' is not a valid number.".format(chosenNumber))
game()
It's not a perfect solution as it doesn't check within the range but I'll learn more about that down the road
You could improve your if statement
elif (chosenNumber > 10) or (chosenNumber < 1):
print("The number you chose ' {} ' is not a valid number.".format(chosenNumber))
game()
Related
I am making a game where if a variable is equal to one number in a range of numbers an if statement will take effect. e.g. if var1 = 4, then the if will activate but it will also give an output if var1 was to equal 5, 6, 7 or 8 for example (the numbers in a set range).
I currently have no code for this part of the game so I won't be able to add it to this question.
Sorry if this question is badly explained or too vague to answer, I am new to stack overflow. Any help would be appreciated. Thank you
Probably the best way to do this is using Swift's powerful switch statements.
You can do this:
let x = 5
switch(x){
case 0..<4:
// Will match 0-3
print("one")
case 4..<10:
// will match 4-9
print("two")
case 10...:
// will match >= 10
print("three")
default:
print("other")
}
EDIT:
If that's too robust for your situation, you can also do this:
if (0..<4).contains(x){
print("yes")
}else {
print("no")
}
or even more simply:
if x >= 0 && x < 4{
print("yes")
}else {
print("no")
}
new python programmer, looking for a fix for this issue. I'm making an autofill rubric for a school project, how would I move to a different section of my code. For example, I want to be able to re-run this function, but that breaks my input because I cannot put it into the function itself.
#TODO...
#Add students names in IN the code, same with num of students
numberOfStudents = 4
rubrick = ["Preparedness", "Engagement", "Perseverance", "Problem Solving", "Progessionalism"]
students = ["ROBERT", "DEVIN", "SKYLER", "XAVIER"]
def pickStudent():
print('Please select your student...')
for x in range(len(students)):
print(students[x])
pickStudent()
userPicked = input().upper()
if userPicked == students[0]:
print("You picked... " + students[0])
elif userPicked == students [1]:
print("You picked... " + students[1])
elif userPicked == students [2]:
print("You picked... " + students[2])
elif userPicked == students [3]:
print("You picked... " + students[3])
else:
print("Invalid user... \n")
pickStudent()
userPicked = input().upper()
Any help would be apreciated.
A few things to pick out here.
You probably want to put the user picking in a while loop to ensure it keeps asking until a correct answer is given.
You also don't need to test the entry against each item in the list in turn - instead use the in operator to see if the inputted text is found ion the list.
Combining these gives you:
while userPicked not in students:
userPicked = input().upper()
Instead of looping over students to print them, you can write neater code using join - to join all the items in the students list into a string and print that:
print('\n'.join(students))
I'm stuck at a point where the computer has to check for all remainders of the number which has been given by the user. Am I supposed to use a For loop for this if yes then how?
Thank you.
yes, you need to use for loop, below function will give you how you can use for loop to check whether number is prime or not.
def prime(n):
flag = 0
for i in range(2,(n/2)+2):
if n%i==0:
flag = 1
return "composite"
if flag==0:
return "prime"
def prime_or_composite(num):
div = 2
while True:
if num == div:
print("It is a prime number!")
break
elif num % div = 0:
print("It is a composite number!")
break
else:
div += 1
This works if the input number is an integer bigger than 2.
I am new in Swift.
I am trying to make a budget application. This app have a Calculator like keyboard. My idea is when users enter the money app will automatically add a decimal place for users.
For example, if you type 1230 it will give you 12.30 and type 123 it will display 1.23
I wrote a couple lines of code down below. The problem is it only can add decimal point after first digit it won't go backwards when you give more digits. It only can display as X.XXXXX
I tried solve this problem with String.index(maybe increase index?) and NSNumber/NSString format. But I don't know this is the right direction or not.
let number = sender.currentTitle!
let i: String = displayPayment.text!
if (displayPayment.text?.contains("."))!{
displayPayment.text = i == "0" ? number : displayPayment.text! + number
}
else {
displayPayment.text = i == "0" ? number : displayPayment.text! + "." + number
}
Indexing Strings in Swift is not as "straightforward" as many would like, simply due to how Strings are represented internally. If you just want to add a . at before the second to last position of the user input you could do it like this:
let amount = "1230"
var result = amount
if amount.characters.count >= 2 {
let index = amount.index(amount.endIndex, offsetBy: -2)
result = amount[amount.startIndex..<index] + "." + amount[index..<amount.endIndex]
} else {
result = "0.0\(amount)"
}
So for the input of 1230 result will be 12.30. Now You might want to adjust this depending on your specific needs. For example, if the user inputs 30 this code would result in .30 (this might or might not be what you want).
So I have a very simple game going here..., right now the AI is nearly perfect and I want it to make mistakes every now and then. The only way the player can win is if I slow the computer down to a mind numbingly easy level.
My logic is having a switch case statement like this:
int number = randomNumber
case 1:
computer moves the complete opposite way its supposed to
case 2:
computer moves the correct way
How can I have it select case 2 68% (random percentage, just an example) of the time, but still allow for some chance to make the computer fail? Is a switch case the right way to go? This way the difficulty and speed can stay high but the player can still win when the computer makes a mistake.
I'm on the iPhone. If there's a better/different way, I'm open to it.
Generating Random Numbers in Objective-C
int randNumber = 1 + rand() % 100;
if( randNumber < 68 )
{
//68% path
}
else
{
//32% path
}
int randomNumber = GeneraRandomNumberBetweenZeroAndHundred()
if (randomNumber < 68) {
computer moves the complete opposite way its supposed to
} else {
computer moves the correct way
}
Many PRNGs will offer a random number in the range [0,1). You can use an if-statement instead:
n = randomFromZeroToOne()
if n <= 0.68:
PlaySmart()
else:
PlayStupid()
If you're going to generate an integer from 1 to N, instead of a float, beware of modulo bias in your results.