Python psychic guessing game repeats 10 times - python

I want it so it will randomly generate a number between 1-10 and the user will input their guess. It will then output if it is right or wrong, after 10 rounds it will tell them how psychic they are. I have done most of it but I cannot get it to randomly generate 10 numbers instead it generates 1 number and you can just input that number and get it correct every time if you find that number
import random
score=0
random=(random.randint(1,10))
for index in range(10):
guess=int(input("Choose a number between 1 and 10:"))
if random==guess:
score+=1
print ("Correct, Next")
else:
print ("Incorrect, Next")
if score==10:
print("Final score:Super mystic")
elif score>=7:
print("Final score:Good")
elif score>=5:
print ("Final score:You need more practice")
else:
print ("Final score:Dont become a psychic")

You need to put the random=(random.randint(1,10)) inside the for loop for it to change with every loop:
for index in range(10):
random=(random.randint(1,10))
guess=int(input("Choose a number between 1 and 10:"))
Then the rest of the code

Related

Issue with the code in finding even or odd number using for loop [duplicate]

This question already has answers here:
Check if a number is odd or even in Python [duplicate]
(6 answers)
Closed 1 year ago.
number = int(input("Type your number to check even or odd :"))
for number in range (1,100):
if(number%2) == 0:
print("This is even number")
elif number > 100:
print("Enter the valid number from 1 to 100")
else:
print("This is ODD number")
i am a beginner in python language , I have written code to read the number as EVEN or ODD in for loop condition between (1,100). correct me if making any mistakes in my code .
Why are you using for loop, just check the condition like if number > 100;the number is invalid.Check this example
nos=int(input())
if(nos>100):
print("Enter the valid number from 1 to 100 ")
else:
if(nos % 2 ==0):
print("Number is Even")
else:
print("Number is Odd")
There are mistakes in your code.
1.Indentation error at the 2nd line.(Remove whitespace before for loop.)
2.The name of the input variable and the iterator name in for loop is same. So your intended logic would run on the numbers from 1 ,2, 3 ..... 99. It never runs on the user entered value. So change the name of any variable. Both cant be 'number'.
3.Although you change the name of the variable, you initialised for loop with 100 iterations so you see output 100 times.
so if you want to check the numbers between given range which are even or odd you can try this..
num = int(input(" Please Enter the Maximum Number : "))
for number in range(1, num+1):
if(number % 2 == 0):
print("{0} is Even".format(number))
print("{0} is Odd".format(number))

(Python) while loop is breaking my random_number

so I'm doing a project where it basically chooses a random number from 1 - 6 as a mini project.
On the most part, it works. But when it loops back up, it seems to keep on rolling the same number.
Here's a screenshot of what I mean
As you can see, the dice number keeps on rolling the same. Can you see what is wrong in my code?
# Useful module for selecting random numbers
import random
# Loop program back to here once user presses anything
loop = 1
#Chooses random number between 1 - 6
Random_Number = (random.choice([1,2,3,4,5,6]))
while (loop < 10):
#Printing what the user sees
print ("===============================")
print ("Your random dice number is:", Random_Number)
input("Press any key to roll again")
print ("===============================")
#looping back to "loop = 1"
loop = loop + 1
You are generating Random_Number one time, outside of the loop.
Try something like this
while (loop < 10):
Random_Number = (random.choice([1,2,3,4,5,6]))
#Printing what the user sees
print ("===============================")
print ("Your random dice number is:", Random_Number)
input("Press any key to roll again")
print ("===============================")
loop = loop + 1
This code chooses the random number once, and then just prints it 10 times. If you want a different random number each time, you should move the random selection inside the loop:
while (loop < 10):
#Chooses random number between 1 - 6
Random_Number = (random.choice([1,2,3,4,5,6]))
#Printing what the user sees
print ("===============================")
print ("Your random dice number is:", Random_Number)
input("Press any key to roll again")
print ("===============================")
#looping back to "loop = 1"
loop = loop + 1
You need to understand that Python (and similar languages) stores values, not expressions. If you write a = 2 + 2, there is no addition and no 2 in the variable a; there's just the number 4.
Your situation is exactly the same: You thought you defined Random_Number as an alias for the expression next to it, where in reality you only store a number.
You can of course fix the problem by calling random.choice() inside the loop-- as about 10 answers have already suggested. But to do what you meant to do, define a function that selects a number in the way you specified. Function bodies are executed every time you call the function.
def random_number():
return random.choice([1,2,3,4,5,6])
while (loop < 10):
print("you rolled", random_number())
loop += 1
You set the value of Random_Number only once, and then show that on every loop.
Fixed
# Useful module for selecting random numbers
import random
# Loop program back to here once user presses anything
loop = 1
#Chooses random number between 1 - 6
#Random_Number = (random.choice([1,2,3,4,5,6]))
while (loop < 10):
#Printing what the user sees
print ("===============================")
print ("Your random dice number is:", (random.choice([1,2,3,4,5,6])))
#input("Press any key to roll again")
print ("===============================")
#looping back to "loop = 1"
Because you generate random number only once.
It should be
...
while (loop < 10):
Random_Number = (random.choice([1,2,3,4,5,6]))
....
Also dont name variables with upper letters instead Random_Number use random_number
If you don't want to redefine a random number at every iteration:
# Useful module for selecting random numbers
import random
# Loop program back to here once user presses anything
loop = 1
#Chooses random number between 1 - 6
Random_Number = lambda : random.choice([1,2,3,4,5,6])
while (loop < 10):
#Printing what the user sees
print ("===============================")
print ("Your random dice number is:", Random_Number())
print ("===============================")
#looping back to "loop = 1"
loop = loop + 1

Loop printing output multiple times

I created a random lottery number generator for COP1000 that passes a random number 0-9 to an array of 7 integers. However, when I print the array, I get the same output 7 times. It may be a problem with one of the loops but I am unsure of where it is coming from. Any help would be greatly appreciated.
Here is the code:
import random
print("Seven lucky numbers; are you ready?")
numbers = [0,0,0,0,0,0,0]
index = 0
while index<len(numbers):
numbers[index] = random.randint(0,9)
index = index + 1
for n in numbers:
print("\nYour random lottery number is:")
print(numbers[0],numbers[1],numbers[2],numbers[3],numbers[4],numbers[5],numbers[6])
With this:
for n in numbers:
print("\nYour random lottery number is:")
print(numbers[0],numbers[1],numbers[2],numbers[3],numbers[4],numbers[5],numbers[6])
You are printing the entire list in a loop. Either loop over the list or print the whole thing, but don't do both. The easiest way to solve this and produce your desired output is to replace the above code with the following:
print("\nYour random lottery number is:")
print(*numbers)
As stated by TigerhawkT3 it seems you are confused with how to print out the values once you have pushed them into your array. (Also you would not want to put the initial print statement inside the loop unless you want it to print for every item in the list)
This link shows how to use for loops in different capacities. One way to solve your problem would be:
print("\nYour random lottery numbers are:")
for n in numbers:
print n
If you want to loop through and print out each value with some kind of string in front of all or 1 item you can use:
print("\nYour random lottery numbers are:")
for index in range(len(numbers)):
if index == len(numbers) - 1:
print "power number: ", numbers[index]
else:
print index, ' : ', numbers[index]
Lastly if you are just trying to print all the numbers with a delimiter in one print statement then seems like this maybe a duplicate of this question or this one where the solution was:
print("\nYour random lottery numbers are:")
print ', '.join(map(str, numbers))

How to compare inputted numbers without storing them in list

Note: This is not my homework. Python is not taught in my college so i am doing it my myself from MITOCW.
So far i have covered while loop, input & print
Q) Write a program that asks the to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered it should print a message to the effect
How can i compare those 10 number without storing them in some list or something else? Coz i haven't covered that as if yet.
print "Enter 10 numbers: "
countingnumber=10
while countingnumber<=10:
number=raw_input():
if number % 2 == 0:
print "This is odd"
countingnumber=countingnumber+1
else:
print "This is even. Enter the odd number again"
i think the program will look something like this. But this has some unknown error & How can i compare all the numbers to get the largest odd number without storing those 10 numbers in the list.
print "Enter 10 numbers: "
countingNumber = 1
maxNumber = 0
while countingNumber<=10:
number=int(raw_input())
if (number % 2 == 0):
countingNumber = countingNumber+1
if (maxNumber < number):
maxNumber = number
else:
print "This is even. Enter the odd number again"
print "The max odd number is:", maxNumber
you can just define a maxnum variable and save the max in it! also you must use int(raw_input()) instead raw_input()
print "Enter 10 numbers: "
maxnum=0
for i in range(10):
number=int(raw_input())
if number%2 == 0:
print "This is odd"
if number>maxnum:
maxnum=number
else:
print "This is even. Enter the odd number again"
print "max odd is :{0}".format(maxnum)
DEMO:
Enter 10 numbers:
2
This is odd
4
This is odd
6
This is odd
8
This is odd
12
This is odd
14
This is odd
16
This is odd
100
This is odd
2
This is odd
4
This is odd
max odd is :100
Whenever I do input, I like to make sure I don't leave room for human error giving me bugs.
Because I put in extra checks I break code into a lot of separate function. This also gives code the quality of being non-coupled. ie) You can reuse it in other programs!!
def input_number():
while true:
input = raw_input("Enter Value: ")
if not input.isdigit():
print("Please enter numbers only!")
else:
return int(input)
Designing the input function in this fashion gives the code no opportunity to crash. We can now use it in a function to get odd numbers!
def input_odd_number():
while true:
input = input_number()
if input % 2 == 0:
print("Please enter odd numbers only!")
else:
return input
Now we can finally move onto the main code. We know we need ten numbers so lets make a for loop. We also now we need to hold onto the largest odd number, so lets make a variable to hold that value
def largest_odd(count = 10): // its always nice to make variables dynamic. The default is 10, but you can change it when calling!
max_odd = input_odd_number() // get the first odd number
for i in range(count - 1): // we already found the first one, so we need 1 less
new_odd = input_odd_number()
if new_odd > max_odd:
max_odd = new_odd
print("The largest odd value in '{}' inputs was: {}".format(count, max_odd)
In your solution are multiple flaws.
A syntax error: The colon in number=raw_input():.
raw_input returns a string and you have to cast it to an int.
Your while loop just runs one time, because you start with 10 and compare 10 <= 10. On the next iteration it will be 11 <= 10 and finishes.
Also you have mixed odd an even. even_number % 2 gives 0 and odd_number % 2 gives 1.
To get the biggest value you only need a additional variable to store it (See biggest_number in my solution). Just test if this variable is smaller then the entered.
You ask again if the number is odd, but you should take every number and test only against odd numbers.
A working solution is:
print "Enter 10 numbers"
count = 0
max_numbers = 10
biggest_number = None
while count < max_numbers:
number=int(raw_input("Enter number {0}/{1}: ".format(count + 1, max_numbers)))
if number % 2 == 1:
if biggest_number is None or number > biggest_number:
biggest_number = number
count += 1
if biggest_number is None:
print "You don't entered a odd number"
else:
print "The biggest odd number is {0}".format(biggest_number)
If you wonder what the format is doing after the string take a look in the docs. In short: It replaces {0} with the first statement in format, {1} with the second and so on.
here is the correct code for that:
print "Enter 10 numbers: "
countingnumber=1
MAX=-1
while countingnumber<=10:
number=int(raw_input())
if number%2==1:
if number>MAX:
MAX=number
if MAX==-1:
print "There Weren't Any Odd Numbers"
else:
print MAX
here are some notes about your errors:
1- you should cast the raw input into integer using int() function and the column after calling a function is not needed and therefor a syntax error
2- your while loop only iterates once because you initial counting number is 10 and after one iteration it would be bigger than 10 and the while body will be skipped.
3-an even number is a number that has no reminder when divided by 2 but you wrote it exactly opposite.
4- you don't need to print anything in the while loop, you should either print the biggest odd number or print "There Weren't Any Odd Numbers".
5- an additional variable is needed for saving the maximum odd number which is MAX.
Last note: in the code provided above you can combine the two ifs in the while loop in to one loop using 'and' but since you said you are a beginner I wrote it that way.

Adding Sums in Python

I have to make a code where user inputs numbers of which the sum will add up to 1001. But it can't go over that amount or it resets back to zero. The only issue I'm having is getting it so the code will print a "Congratulations" message when the user gets to 1001. This is my code so far.
I'm new to Python and would appreciate any help offered!
EDIT
So far I have this and it's working for adding the sums.
print ("Want to play a game? Add numbers until you reach 1001!")
print ("Current total is 0!")
total=0
while total < 1001:
store=raw_input("Enter a number!")
num=int(store)
total=total+num
print total
print ("Congratulations! You won!")
The only problem I've having now is that the user can enter numbers over 1001 and still get the congratulations message.
should I put something like
if total > 1001:
print ("Oops! Too Far! Start Again!")
In your case, you have while 1001 > 0, which is always true, so you get an infinite loop. Additionally, while 1001 == sum will also produce an infinite loop, considering that once you get there, you are never changing sum. The following is a simplified and fixed version of your code:
#sum is a function, so name it something else, I chose sum_ for simplicity's sake
while sum_ != 1001:
#instead of using an intermediate, I just combined the two lines
num=int(raw_input("Enter a number!"))
#This is equivalent to sum = sum + num
sum_ += num
print sum_
#Need to reset if sum_ goes above 1001
if sum_ > 1001:
sum_ = 0
#By the time you get here, you know that _sum is equal to 1001
print ("Congratulations! You won!")
Both of your while-loops will run forever since their conditions will always evaluate to True (actually, you will never even get to the second because the first will run forever).
Here is a fixed version of your script:
print "Want to play a game? Add numbers until you reach 1001!"
print "Current total is 0!"
# Don't name a variable `sum` -- it overrides the built-in
total = 0
# This will loop until `total` equals 1001
while total != 1001:
store = raw_input("Enter a number!")
num = int(store)
# This is the same as `total=total+num`
total += num
print total
# If we have gone over 1001, reset `total` to 0
if total > 1001:
print "Oops! Too Far! Start Again!"
total = 0
# When we get here, the total will be 1001
print "Congratulations! You won!"

Categories