218k views
4 votes
Write a function that takes an integer, val, as an argument. The function asks the user to enter a number. If the number is greater than val, the function displays Too high. and returns 1; if the number is less than val, the function displays Too low. and returns –1; if the number equals val, the function displays Got it! and returns 0. Call the function repeatedly until the user enters the right number.

2 Answers

6 votes

Answer:

def high_low(val):

number = int(input("Enter a number: "))

if number > val:

print("Too high")

return 1

elif number < val:

print("Too low")

return -1

elif number == val:

print("Got it!")

return 0

val = 7

while True:

if high_low(val) == 0:

break

Step-by-step explanation:

The code is in Python.

Create a function called high_low that takes one parameter, var

Ask the user for a number. Check the number. If the number is greater than 1, smaller than 1 or equal to 1. Depending on the number, print the required output and return the value.

Set the value to a number. Create a while loop iterates until the user enters the correct number, when the return value of the function is equal to 0, that means the user entered the correct number. Otherwise, it keeps asking the number and prints the appropriate message.

User YMMD
by
5.5k points
5 votes

Answer:

import java.util.*;

public class num2 {

public static void main(String[] args) {

//Set the Value of the argument

int val = 5;

//Call the method

int returnedNum = testInteger(val);

//Use a While to continously call the method as long as the returned value is not 0

while(returnedNum != 0){

int rt = testInteger(val);

//Break out of loop when the user enters correct value and the return is 0

if(rt == 0){

break;

}

}

}

//The Method definition

public static int testInteger(int val){

//Prompt and receive user input

System.out.println("Enter a number");

Scanner in = new Scanner(System.in);

int userNum = in.nextInt();

//Check different values using if and else statements

if(userNum > val){

System.out.println("Too High");

return 1;

}

else if(userNum < val){

System.out.println("Too Low");

return -1;

}

else{

System.out.println("Got it");

return 0;

}

}

}

Step-by-step explanation:

This is solved with Java Programing Language

Pay close attention to the comments provided in the code

The logic is using a while loop to countinually prompt the user to enter a new number as long as the number entered by the user is not equal to the value of the argument already set to 5.

User Krdln
by
5.2k points