Tässä artikkelissa opit etsimään luvun faktorialan ja näyttämään sen.
Tämän esimerkin ymmärtämiseksi sinulla on oltava tieto seuraavista Python-ohjelmointiaiheista:
- Python jos… muuten Lausunto
- Python for Loop
Luvun kerroin on kaikkien kokonaislukujen tulo yhdestä numeroon.
Esimerkiksi 6: n kerroin on 1*2*3*4*5*6 = 720
. Kertoma ei ole määritelty negatiivisten lukujen, ja kertoma nolla on yksi, 0! = 1
.
Lähdekoodi
# Python program to find the factorial of a number provided by the user. # change the value for a different result num = 7 # To take input from the user #num = int(input("Enter a number: ")) factorial = 1 # check if the number is negative, positive or zero if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial)
Tuotos
7: n kerroin on 5040
Huomaa: Jos haluat testata ohjelmaa eri numerolle, muuta arvoa num
.
Tällöin numero, jonka kerroin on löydettävissä, on tallennettu num
, ja tarkistamme, onko luku negatiivinen, nolla vai positiivinen if… elif… else
lauseen avulla. Jos luku on positiivinen, käytämme for
silmukkaa ja range()
funktiota laskettaessa kerroin.