Using random library to guess number (Python) - loops

#This program generates random number
#user enters guess
#progam tells user higher, lower or correct based on user input.
import random
def main():
# Get a random number.
number = random.randint(1, 101)
user_guess = int(input("Pick a number between 1 and 100: "))
userguess = guess(user_guess, number)
print(userguess)
def guess(num1, num2):
if num1 > num2:
return("Lower")
elif num1 < num2:
return("Higher")
else:
return("Correct")
main()
I can get the program to generate a random number, then display higher or lower, but not as again. It is supposed to ask again until it hits the random and then displays 'correct'

You need a loop to keep prompting until the correct answer is guessed, while(True) keeps going until a break; is reached. Try something like this.
def guess(num):
while(True):
user_guess = int(input("Pick a number between 1 and 100: "))
if user_guess > num:
print("Lower\n")
elif user_guess < num:
print("Higher\n")
else:
print("Correct")
break;
This will repeatedly ask user for numbers untill they are correct replace your main method with the following
def main():
# Get a random number.
number = random.randint(1, 101)
guess(number)
Edit: replaced true with True

Related

Making a collatz program and end it after 500 runs

This is my script. How do i add so the loop ends if it has to run 500 times or more?
x=0
while x<=500:
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
elif number % 2 == 1:
result = 3 * number + 1
print(result)
return result
n = input("Give me a number: ")
while n != 1:
n = collatz(int(n))
x=x+1
else:
print('Loop ended)
break
This is the collatz equation but it is not always sure that it ends up on 1. So I need to rewrite my program so that the loop ends if the number series will be longer than 500 numbers.

My output is not appearing properly

I apologize if I'm not formatting my question correctly. I am new to this site and new to programming.
I'm currently working on a C assignment and I believe I have most of the code done, but there is some tuning I can't seem to figure out. I would appreciate any feedback. Here is my code
#include <stdio.h>
#include <stdlib.h>
#define SENTINAL -1
double sumOfScores = 0;
double examScore = 0;
double sumOfExams = 0;
double average = 0;
double calculateAverage();
double main(void)
{
int i;
for (i = 1; i <= 4; ++i)
{
calculateAverage();
}
return 0;
}
double calculateAverage()
{
printf("Enter %d to terminate program. \n", SENTINAL);
while(examScore != SENTINAL)
{
printf("Enter test score: \n");
scanf("%lf", &examScore);
sumOfScores += examScore;
sumOfExams++;
average = sumOfScores / sumOfExams;
}
printf("The average of the test scores entered thus far is %.2lf \n\n", average);
return 0;
}
Here is my output
Enter -1 to terminate program.
Enter test score:
99
Enter test score:
98
Enter test score:
97
Enter test score:
96
Enter test score:
-1
The average of the test scores entered thus far is 77.80
Enter -1 to terminate program.
The average of the test scores entered thus far is 77.80
Enter -1 to terminate program.
The average of the test scores entered thus far is 77.80
Enter -1 to terminate program.
The average of the test scores entered thus far is 77.80
Here is what I would like it to look like
Enter -1 to terminate program.
Enter test score:
99
Enter test score:
98
Enter test score:
97
Enter test score:
96
Enter test score:
-1
The average of the test scores entered thus far is 77.80
Enter -1 to terminate program.
Enter test score:
95
Enter test score:
94
Enter test score:
93
Enter test score:
92
Enter test score:
-1
The average of the test scores entered thus far is (avg goes here)
I did not include an additional two sets of numbers in the output I am going for, but I would like to be able to do this with four sets of numbers. As soon as I enter (-1) to terminate the first set of numbers, it automatically spits me out the average of the first set for the remaining 3 sets before i can even input the numbers I would like to enter for those. Also, why is it giving me an avg of 77.8 for the first set of values when it should be up in the 90s?
I would recommend using local variables rather than global ones. That is to say, move these lines:
double sumOfScores = 0;
double examScore = 0;
double sumOfExams = 0;
double average = 0;
Here:
double calculateAverage()
{
double sumOfScores = 0;
double examScore = 0;
double sumOfExams = 0;
double average = 0;
// ...
This will cause the variables to be reset to 0 every time the function starts rather than leaving the garbage from the last time the function ran.
I think that the reason that you are getting the wrong average is that you are including -1 as one of the test scores. You read the value, then add it to the average BEFORE you check if the value is -1.
printf("Enter test score: \n");
scanf("%lf", &examScore);
// Is examScore equal to -1 here? It might be.
// Don't add it to sumOfScores without checking!
sumOfScores += examScore;
sumOfExams++;
average = sumOfScores / sumOfExams;
You either need to test if the value is -1 before you recalculate the average, or you need to restructure your loop such that the examScore != SENTINAL check is done between reading and recalculating the average.
Also, strictly speaking, there is no need to make all the averaging calculations while the loop is still running. You can save the average = sumOfScores / sumOfExams; line until after the loop has finished. Just a thought.
As Paul R said, you also have the incorrect function prototype for your main function. Valid prototypes for the main function can be found here

Couldn't convert C program to Ruby

This code in C language works perfectly, I will explain what it does:
Given a positive integer "n" and a sequence of "n" integers, the sum will determine a sequence of positive integers.
Examples of inputs:
4 9 -1 4 -2
expected output: 13 / input: 3 3 0 -2 output: 3/
#include <stdio.h>
int main(){
int cont=0,n,num,sum;
scanf("%i",&n);
while(n>cont){
cont++;
scanf("%i",&num);
if(num>0){
sum=num+sum;
}
}
printf("%i",sum);
}
and this was my attempt to convert it to Ruby
cont=0
n=gets.to_i
while n>cont do
cont=cont+1
num=gets.to_i
if num>0
sum=num+sum
end
puts"#{sum}"
and this is what im getting:
ruby test.rb
test.rb:10: syntax error, unexpected end-of-input, expecting keyword_end
puts"#{sum}"
^
. Can anyone help?
Thank you, so this is the right code that works
cont=0
sum=0
n=gets.to_i
while n>cont do
cont=cont+1
num=gets.to_i
sum=num+sum if num>0
end
puts"#{sum}"
You were not far off. The syntax of the if-statement needs a then and an end. Also, sum needs to be zero at the start.
cont=0
sum=0 # sum needs an initial value
n=gets.to_i
while n>cont do
cont=cont+1
num=gets.to_i
sum=num+sum
# num = num+sum if num >0
# #or
# if num >0 then
# sum=num+sum
# end
# #But both "if's" serve no purpose
end
puts"#{sum}"
Another way of writing this is:
sum = 0
gets.to_i.times{sum += gets.to_i} # no bookkeeping with cont
puts sum # more simple then puts"#{sum}"

Python: Using def in a factorial program

So i am trying to make a program that finds the factorial using def.
changing this:
print ("Please enter a number greater than or equal to 0: ")
x = int(input())
f = 1
for n in range(2, x + 1):
f = f * n
print(x,' factorial is ',f)
to
something that uses def.
maybe
def intro()
blah blah
def main()
blah
main()
Not entirely sure what you are asking. As I understand your question, you want to refactor your script so that the calculation of the factorial is a function. If so, just try this:
def factorial(x): # define factorial as a function
f = 1
for n in range(2, x + 1):
f = f * n
return f
def main(): # define another function for user input
x = int(input("Please enter a number greater than or equal to 0: "))
f = factorial(x) # call your factorial function
print(x,'factorial is',f)
if __name__ == "__main__": # not executed when imported in another script
main() # call your main function
This will define a factorial function and a main function. The if block at the bottom will execute the main function, but only if the script is interpreted directly:
~> python3 test.py
Please enter a number greater than or equal to 0: 4
4 factorial is 24
Alternatively, you can import your script into another script or an interactive session. This way it will not execute the main function, but you can call both functions as you like.
~> python3
>>> import test
>>> test.factorial(4)
24
def factorial(n): # Define a function and passing a parameter
fact = 1 # Declare a variable fact and set the initial value=1
for i in range(1,n+1,1): # Using loop for iteration
fact = fact*i
print(fact) # Print the value of fact(You can also use "return")
factorial(n) // Calling the function and passing the parameter
You can pass any number to n for getting factorial

Getting Sytax error using the While Loop in Python 3.3.2

Here is my code:
import random
secret = random.randint (1, 99)
guess = 0
tries = 0
print ("Ahoy! I'm the Dread Pirate Roberts, and I have a secret!")
print ("It is a number from 1 to 99. I'll give you 6 tries. "
while tries < 6 and guess != secret:
guess = input ("What's yer guess? ")
if guess < secret:
print ("Too low, ye scurvy dog!")
elif guess > secret:
print ("Too High, landlubber!")
tries = tries + 1
if (guess == secret):
print ("AVAST! Ye got it! Found my secret, ye did it!"
else:
print ("No more guesses! Better luck next time, matey!)
print ("The secret number was"), secret
For some reason I am getting an invalid syntax on "while". I cannot seem to find out why as this used work for some reason.
You're missing a closing parenthesis at the end of this line:
print ("It is a number from 1 to 99. I'll give you 6 tries. "
^
This line isn't indented properly:
while tries < 6 and guess != secret:
guess = input ("What's yer guess? ")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
guess will be a string, so you should convert it into an integer before treating it like one:
guess = int(input("What's yer guess? "))
Finally, this line is missing a closing double quote:
print ("No more guesses! Better luck next time, matey! )
^

Resources