Question regarding a self made number guessing game - loops

I am trying to learn python since 2 days now and I am challenging myself with this little python projects from this website: https://www.upgrad.com/blog/python-projects-ideas-topics-beginners/#1_Mad_Libs_Generator
I am at the second game now (number guessing game).
The instruction is as follows:
'''Make a program in which the computer randomly chooses a number between 1 to 10, 1 to 100, or
any range. Then give users a hint to guess the number. Every time the user guesses wrong,
he gets another clue, and his score gets reduced. The clue can be multiples, divisible,
greater or smaller, or a combination of all.
You will also need functions to compare the inputted number with the guessed number, to compute
the difference between the two, and to check whether an actual number was inputted or not in this python project.'''
import random
print("Welcome to the number game. A random number will be generated and you can guess which one it is.")
print("You got three tries.")
number = random.randint(1, 99)
guess = "" # var to store users guess
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != number and not out_of_guesses:
if guess_count < guess_limit:
guess = int(input("Enter a guess: "))
guess_count += 1
if guess < number:
print("Your guess is too small. Try again.")
elif guess > number:
print("Your guess is too high. Try again.")
else:
out_of_guesses = True
if out_of_guesses:
print("You are out of guesses. You loose!")
else:
print("Your guess is correct. You Won!")
The output looks like this:
Welcome to the number game. A random number will be generated and you can guess which one it is.
You got three tries.
Enter a guess: 78
Your guess is too high. Try again.
Enter a guess: 28
Your guess is too small. Try again.
Enter a guess: 29
**Your guess is too small. Try again.**
You are out of guesses. You loose!
My problem is the line marked in strong. Actually, after the user entered the third try and did not guess the correct answer, I don't want the line "your guess is too ..." to be displayed. However, before the user is out of tries, I do want it to be displayed.
Do you got any hints on how to adjust the code?
Also, I did understand the concept of try and except, but don't really know where exactly to add it to make the game more "smooth" with regard to entering a wrong input type.
Kind Regards

Given the current code structure, you can avoid printing the hints on the last guess by adding an additional check in the guess and number comparison.
Regarding exception handling, the crash points of the program involve the comparison between user input and the number. Adding exception handling around the integer conversion of user input seems appropriate. Doing this before incrementing guess_count and a continue to allow for another user input will allow the game to run for 3 valid inputs.
The _ variable being used to refer to the exception is a 'throwaway' variable - this is just a conventional name. In an interpreted session, however, _ would store the return value of the previously executed statement.
import random
print("Welcome to the number game. A random number will be generated and you can guess which one it is.")
print("You got three tries.")
number = random.randint(1, 99)
guess = "" # var to store users guess
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != number and not out_of_guesses:
if guess_count < guess_limit:
try:
guess = int(input("Enter a guess: "))
except ValueError as _:
print('Wrong input type')
continue
guess_count += 1
if guess < number and guess_count != guess_limit:
print("Your guess is too small. Try again.")
elif guess > number and guess_count != guess_limit:
print("Your guess is too high. Try again.")
else:
out_of_guesses = True
if out_of_guesses:
print("You are out of guesses. You lose!")
else:
print("Your guess is correct. You Won!")

Related

User input it iterate list and continue loop

I am writing a program in python3 to keep score of N number of players and am having trouble getting the score to be input correctly from each player. the code in bold is where I am having an issue. The loop closes after I enter the score for the first contestant and i for some reason equals 3 instead of increasing from 0 to 1. I would like 'i' to update as the loop continues so that the code to get scores continues until each player has been scored.
I don't know how to get the result I want. Am I using the wrong loop statement?
I have tried while, if and for statements.
I just started coding Tuesday so any help is greatly appreciated.
import csv
from array import *
names = []
con = int(input("Number of Contestants: "))
maxSurfers = con #number of surfers
while len(names) < maxSurfers:
name = input(" Enter your Name: ")
names.append(name)
print("Contestants")
print(names)
else:
print("Thank You for Participating!\n")
print("Sign up is now closed")
**score = array('f', [])
i = 0
n = int(input("Number of Waves for "+names[i]+": "))
while i != n:
x=float(input("Enter score for each wave: "))
score.append(x)
i = i + 1
print(i)
print("Winner being decided.")**
outputs:
Number of Contestants: 2
Enter your Name: frank
Contestants
['frank']
Enter your Name: bart
Contestants
['frank', 'bart']
Thank You for Participating!
Sign up is now closed
Number of Waves for frank: 3
Enter score for each wave: 9.6
Enter score for each wave: 7.8
Enter score for each wave: 7.2
3
Winner being decided.
The issue is that you have a loop for each wave but not an outer loop for each name. You also only have one score list so if you did have an outer loop you'd just have a score list with a bunch of numbers and no way to connect them to each player. You should look into python dictionaries they will likely make your life a lot easier. Also when you want a python loop for a range of numbers the standard way is with something like for counter in range(10): which counts from 0 to 9.
try something like:
scores = {}
for name in names:
numWaves = int(input("Number of Waves for "+name+": "))
newScores = []
for i in range(numWaves):
newScores.append(float(input("Enter score for each wave: ")))
scores[name] = newScores

Designing pseudocode for loop assignment

I'm in an intro to java class (first exposure to programming ever). My professor assigned this
"Input positive numbers and display how many are in between 10 and 20"
We've learned loops and if else statements so far and can use both, either or neither of those.
My pseudocode looks like this so far. Please let me know if I'm on the right track.
BEGIN
Input number from user
WHILE number is positive
IF (number >=10 && number >= 20)
Add 1 to count
END IF
Input another number if user wants
Display amount of numbers between 10 and 20
END WHILE
END
Am I on the right track? I've been wrestling with this for a couple hours
If you are trying to count numbers between 10 and 20 then.
This statement is wrong
IF (number >=10 && number >= 20)
Correct statement is
IF (number >=10 && number <= 20)
I would say you're on the right track for sure. Here are my few suggestions:
BEGIN / END may or may not be necessary. Honestly, I wouldn't use them. But some people do. Pseudocode is kind of - different for everybody.
Use variables consistently, and use assigment operations still in your code.
By this I mean, number = input from user instead of Input number from user or Input another number if user wants.
You should define counter = 0 before the while loop starts. Otherwise, you're incrementing a variable that isn't there.
IF / END IF might be a way to do it, but you could also use brackets or indentation to make the code more readable and mean the same thing.
Finally, about code correctness:
Did you want >= 10 and >= 20? You probably meant <= 20 because otherwise only values greater or equal to 20 would work. But aside from just the one sign, do you want them to be greater/less than or equal to the number? "In between" is vague, and might mean 11-19 or 10-20. It depends on how you frame the problem.
My final bit of input is, do you want to display the number every time the loop runs through? Or just after you enter a negative number and end the loop. If you want to display it only once, move it a line down. Otherwise, no big deal.
You're definitely on the right track and I wouldn't sweat it so much. Think of pseudocode as logical instructions. Flow through it very literally when you read it and when you write it, it's not about how it looks as to how it works.
I wish you a lot of luck, all the best :)
Pseudocode is always hard to correct but I think this would be much better
1) is positive is not a reasonable command, given that whether the input is numeric is unknown
2) initialize count to 0 before the while loop.
3) number <= 20 not number >= 20
4) Move display out of the while loop
5) Display count because your current statement is literally the problem
6) count += 1 is shorter and easier to read
7) we should get number in the while loop to ensure we stop when there is no input. something along the lines of while input number from user would stop in some languages once the input is blank. It will throw an error if the input cannot be coerced into a double. And it will stop when a negative is entered.
BEGIN
Initialize count = 0
WHILE number = input from user as double && number > 0
IF (number >=10 && number >= 20)
count += 1
END IF
END WHILE
Display count
END

Ruby partner pairing program not working?

I am new to ruby and have this program that takes in a number of names and sorting them into pairs of two, and throwing the odd person in a random group. Sometimes it works perfect, sometimes it throws the extra person into an array of their own, and im not sure why. I know there is a cleaner way to do this but Im just trying to understand how the code works. For example it should return "Apple" "Banana" "Orange" as ["Banana", "Orange", "Apple"] and will most of the time, but sometimes it give me ["Banana","Orange",] ["Apple"] Any advice?
def randomArray
classNames = []
puts "Please enter a list of names to sort"
while true
input = gets.chomp
break if input.empty?
classNames << input
end
classRandom = classNames.shuffle
splitNames = classRandom.each_slice(2).to_a
arrayPos = 0
splitNames.length.times do
if splitNames[arrayPos].length == 2
arrayPos+=1
else splitNames[arrayPos].length == 1
splitNames.sample << splitNames[arrayPos].pop
arrayPos+=1
end
end
x = 0
splitNames.length.times do
break if splitNames[x].empty?
puts "Group number #{x+1} is #{splitNames[x]}"
x+=1
end
end
randomArray
Your problem is this: splitNames.sample << splitNames[arrayPos].pop
sample can return any element of the array, including the element that has the odd person you're trying to assign! So if it samples that person, it removes them from their group of 1 and then adds them right back in.
To fix it, take advantage of the fact that either all groups will be pairs, or the last group will have a single person. Don't iterate over the array, just check splitNames[-1]. If they are alone, add them to splitNames[0...-1].sample.

Can't assign to operator?

Several questions have the same error, but I'm just starting Python and don't understand it.
I'm trying to create a program which generates two random numbers, nicknames these numbers, asks the user what the answer is, multiplies the two numbers and gives a nickname to THAT number, then it reads the user's answer and sees if the user's answer is the same as the one it got. I started with a simpler program that asks the same question three times.
My program is the following:
def math ():
for f in range (3):
x=10
c=5
x*c=p
print x,'times',c,'.'
v=read_number('What is the answer?')
if p==v:
print 'You got it right!'
else:
print 'You got it wrong.'
And now that I look at it line 6 it is unnecessary. But when I finish it Python says 'SyntaxError: can't assign to operator.'
It also highlights after c=5. Why does this happen and how can I fix it?
The
x*c=p
should read
p=x*c
This multiplies x by c and assigns the result to p.
you use randint() from the random module to generate random numbers, for example:
from random import randint
x = randint(0,10) # random between 0 and 10
c = randint(0,10)
p = x * c
print p

list in python, loop for, array

as a green hand python programmer, I have a little problem, I'll appreciate if somebody can help!!
I have two lists
a list of random repeated numbers(unknow size) like:
number = [44,198,57,48,658,24,7,44,44,44..]
for n in number
I want to give these numbers to a list of people in order, one number for one person. If a number repeat, the program will find out the person whom got this number when the first time it shows up. It means I want to print a list like
people = [1,2,3,4,5,6,7,1,1,1...]
print people
Store the mapping from numbers to indexes in a dict, and update it as you go.
numbers = [44,198,57,48,658,24,7,44,44,44.]
index_mapping = {}
indexes = []
next_index = 1
for number in numbers:
if number in index_mapping:
# already seen
indexes.append(index_mapping[number])
else:
# a new one
indexes.append(next_index)
index_mapping[number] = next_index
next_index += 1
print indexes

Resources