简体   繁体   中英

Write a program that accepts a positive integer from the user and prints the first four multiples of that integer. Use a while loop

I am trying to write as the question is stated, Write a program that accepts a positive integer from the user and print the first four multiples of that integer; Use while loop (Python)

total = 0

number = int(input("Enter integer: "))
while number <= 15:
     total = total + number 
print(number)

SAMPLE

Enter integer: 5
0
5
10
15

this is the example my professor wanted

This is what i have so far, but i'm a bit lost...

You should loop over a counter variable instead of a hard coded limit

counter = 1
while counter <= 4:
    counter += 1
    total = total + number 
    print(number)

The loop condition should be set on total , not number , and total should be incremented by 1 , not number (assuming total is used as a loop counter):

total = 0
number = int(input("Enter integer: "))
while total <= 3:
     print(total * number)
     total = total + 1

Sample:

Enter integer: 5
0
5
10
15

A normal while loop that counts upto 4:

count, total = 0, 0

number = int(input("Enter integer: "))
while count < 4:
     print(total)
     total = total + number     
     count += 1

Python for loop is more pythonic than while :

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

for i in range(4):
    print(number * i)

Although you have the right idea from the example there's still a couple of things the sample is missing. 1. You don't check whether the input is positive or not 2. The while loop is dependent on knowing the input

Try the following:

# Get Input and check if it's positive
number = int(input('Enter positive integer: '))
if number <= 0:
    number = int(input('Not positive integer, enter positive integer: '))

# This increments i by one each time it goes through it, until it reaches 5
i=1
while i < 5:
    new_number = number*i
    i = i + 1
    print(new_number)

Note: This does not take into account if the input is a letter or string. If so, it'll throw an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM