Cùrsaichean python

Tha Python na chànan prògramaidh sìmplidh, ach fìor adhartach.

Tha sinn air grunn artaigilean a sgrìobhadh mu Python, agus tha an t-àm ann beagan cleachdaidh a dhèanamh.

San artaigil seo chì sinn cuid de eacarsaichean Python, a ’mìneachadh am fuasgladh ceum air cheum.

Ùine leughaidh tuairmseach: 4 minuti

Chì sinn còmhla teacsa cuid de eacarsaichean agus am fuasgladh.

Eacarsaich air ais

Sgrìobh gnìomh ris an tèid thu seachad sreang mar pharamadair, agus a bheir a-mach, air an sgrion, tionndadh neo-dhruim (air ais) den aon sreang. Mar eisimpleir bidh “abcd” gu bhith na “dcba”.

Gliocas: gus an eacarsaich seo fhuasgladh ann an dòigh chruaidh dh'fhaodadh tu slicing a chleachdadh.

Fuasgladh
# Solution for this exercise

def reverser(string):
    ind = (len(string) -1)
    new_string = ""
    while ind >= 0:
        new_string += string[ind]
        ind -= 1
    print(new_string)

def reverser_pro(string):
    reverse = string[::-1]
    print(reverse)

Eacarsaich rann

Sgrìobh gnìomh rhyme, a thèid seachad air liosta fhaclan mar pharamadair agus a gheibh facal a chuir an neach-cleachdaidh a-steach tron ​​​​ghnìomh cuir a-steach.

An gnìomh rhyme feumaidh tu coimeas a dhèanamh eadar am facal a chuir an neach-cleachdaidh a-steach agus an fheadhainn a bha an làthair air an liosta roimhe, a’ coimhead airson rannan, air an tuigsinn mar fhaclan aig a bheil na 3 litrichean mu dheireadh co-ionann ris an fhacal a chuir an cleachdaiche a-steach.

Feumaidh na rannan an uairsin a bhith air an cur a-mach a’ cleachdadh an dòigh ceangail.

Fuasgladh
# Two solutions for this exercise, rhyme and rhyme_pro

def rhyme(listx):
    rime = []
    word = input("Enter the word you want to find rhymes for: ")
    for element in listx:
        if element[-3:] == word[-3:]:
          rime.append(element)

    if not rime:
        print("No rhymes corresponding to the past word were found!")
    else:
        output = ", ".join(el for el in rime)
        print(f"The rhymes corresponding to the word {word} are as follows: {output}")

def rhyme_pro(listx):
    rime = []
    parola = input("Enter the word you want to find rhymes for: ")
    rime = [el for el in listx if el[-3:] == word[-3:]]
    if not rime:
        print("No rhymes corresponding to the past word were found!")
    else:
        output = ", ".join(el for el in rime)
        print(f"The rhymes corresponding to the word {word} are as follows: {output}")

Eacarsaich factaraidh

Sgrìobh aon gnìomh ath-chuairteach a tha a 'cunntadh an factaraidh de àireamh ainmichte.

Fuasgladh
def factorial(n):
    if n == 1:
        return n
    else:
        result = n * factorial(n-1)
        return result

Eacarsaich Fibonacci

Nella Sreath Fibonacci saor an asgaidh, is e gach àireamh suim an dà àireamh air thoiseach oirre, mar eisimpleir:

1, 1, 2, 3, 5, 8, 13 (…)

Sgrìobh gnìomh ath-chuairteach a bheir a-mach àireamhan an t-sreath Fibonacci, taobh a-staigh stairsneach sònraichte a shuidhich an neach-cleachdaidh.

Fuasgladh
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

limit = int(input("Enter the number of values ​​in the series you want to see: "))

for num in range(1, limit+1):
    print(fibonacci(num))

Eacarsaich Dèan tomhas air an àireamh

Dèan an geama “Guess the Number” a’ cleachdadh Python. Bidh an geama a’ gineadh àireamh air thuaiream agus feumaidh an neach-cleachdaidh a thomhas, a’ faighinn sanasan ma tha an àireamh airson tomhas nas àirde no nas ìsle na an tomhas.

Riatanasan
  1. Gineadh àireamh air thuaiream: Cleachd an leabharlann random gus àireamh air thuaiream a chruthachadh eadar 1 agus 100.
  2. Eadar-aghaidh cleachdaiche: Cruthaich eadar-aghaidh cleachdaiche loidhne-àithne sìmplidh a leigeas leis an neach-cleachdaidh oidhirpean a chuir a-steach.
  3. Molaidhean: Leig fios don neach-cleachdaidh ma tha an àireamh tuairmseach nas àirde no nas ìsle na an tomhas.
  4. Cunnt oidhirp: Cum sùil air an àireamh oidhirpean a rinn an neach-cleachdaidh.
  5. Deireadh a' Gheam: Cuir crìoch air a’ gheama nuair a bhios an neach-cleachdaidh a’ tomhas an àireamh no a’ co-dhùnadh stad.
Fuasgladh
import random

def main():
    print("I thought of a number between 1 and 100. Can you guess it ?")

    number_to = random.randint(1, 100)
    numbers = 0

    while True:
        number_one = input("Enter your attempt (or 'exit' to finish): ")

        if number_one.lower() == 'exit':
            print("You have decided to finish the game. Until next time!")
            break

        try:
            number_one = int(number_one)
            numbers += 1

            if number_one < number_to
                print("Too short. Try again!")
            elif tentativo > number_to:
                print("Too high. Try again!")
            else:
                print(f"Congratulations! You guessed the number {number_to} in {numbers} attempts.")
                break
        except ValueError:
            print("Enter a valid number.")

if __name__ == "__main__":
    main()

Eacarsaich roiligeadh dìsnean

Dèan simuladair rollaidh dìsnean a’ cleachdadh Python. Leigidh am prògram leat atharrais a dhèanamh air rolla aon dìsnean no barrachd agus na toraidhean fhaicinn.

Riatanasan
  1. Leabharlannan Python: Cleachd an leabharlann random gus àireamhan air thuaiream a chruthachadh.
  2. Eadar-aghaidh cleachdaiche: Cruthaich eadar-aghaidh cleachdaiche loidhne-àithne sìmplidh a leigeas leis an neach-cleachdaidh an àireamh de dhìsnean a shònrachadh airson an roiligeadh agus na toraidhean fhaicinn.
  3. Cuir air bhog atharrais:
    • Cruthaich àireamh air thuaiream eadar 1 agus 6 airson gach bàs.
    • Thoir sùil air toraidhean tòiseachaidh.
Fuasgladh
import random

def roll_dice(num_dice):
    results = [random.randint(1, 6) for _ in range(num_dice)]
    return results

def main():
    print("Dice Rolling Simulator")

    while True:
        try:
            num_dice = int(input("Enter the number of dice to roll: "))
            if num_dice <= 0:
                print("The number of dice must be greater than zero.")
                continue

            results = roll_dice(num_dice)
            print(f"Launch results: {', '.join(map(str, results))}")

        except ValueError:
            print("Please enter a valid number.")

        another = input("Do you want to launch again? (y/n): ").lower()
        if another != 's':
            break

if __name__ == "__main__":
    main()

Eacarsaich Obraich a-mach Cìse Code

Cruthaich gineadair còd cìse Eadailteach a 'cleachdadh Python. Cruinnichidh am prògram dàta an neach-cleachdaidh (ainm, sloinneadh, ceann-latha breith, gnè agus àite-breith) agus cruthaichidh e an còd cìse stèidhichte air an dàta seo.

Riatanasan
  1. Leabharlannan Python: Cleachd na leabharlannan àbhaisteach de Python.
  2. Eadar-aghaidh cleachdaiche: Cruthaich eadar-aghaidh cleachdaiche loidhne-àithne sìmplidh a leigeas leis an neach-cleachdaidh an dàta aca fhèin a chuir a-steach.
  3. Ginealach den Chòd Cìse:
    • Obraich a-mach connragan agus fuaimreagan a' chiad ainm agus an ainm mu dheireadh.
    • Obraich a-mach an ceann-latha breith agus an còd gnè.
    • Obraich a-mach an còd àite breith a’ cleachdadh faclair.
    • Obraich a-mach caractar an t-seic.
Fuasgladh
import datetime

def cod_lastname(lastname):
    cons = ''.join([c for c in lastname if c.isalpha() and c not in 'AEIOU'])
    vocs = ''.join([c for c in lastname if c.isalpha() and c in 'AEIOU'])
    cod = (cons + vocs + 'XXX')[:3].upper()
    return cod

def cod_name(name):
    cons = ''.join([c for c in name if c.isalpha() and c not in 'AEIOU'])
    vocs = ''.join([c for c in name if c.isalpha() and c in 'AEIOU'])
    if len(cons) >= 4:
        cons = cons[0] + cons[2] + cons[3]
    cod = (cons + vocs + 'XXX')[:3].upper()
    return cod

def cod_date_birth(date_birth, gender):
    cod_month = 'ABCDEHLMPRST'
    data = datetime.datetime.strptime(date_birth, '%d/%m/%Y')
    year = str(data.year)[-2:]
    month = cod_month[data.month - 1]
    day = data.day + 40 if gender == 'F' else data.day
    day = f'{day:02d}'
    return year + month + day

towms = {
    'ROMA': 'H501',
    'MILANO': 'F205',
    'NAPOLI': 'F839',
    # Add towns here
}

def cod_town(towm):
    return towns.get(town.upper(), 'XXXX')

def check_char(cf_partial):
    values = {
        **{chr(i): i - 48 for i in range(48, 58)},
        **{chr(i): i - 55 for i in range(65, 91)}
    }
    odd = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
               1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 1, 0, 5, 7, 9, 13, 15, 17, 19, 21,
               1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 1, 0, 5, 7, 9, 13, 15, 17, 19, 21]
    even = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
            1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 1, 0, 5, 7, 9, 13, 15, 17, 19, 21,
            1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 1, 0, 5, 7, 9, 13, 15, 17, 19, 21]

    total = sum(odd[values[cf_partial[i]]] if i % 2 == 0 else even[values[cf_partial[i]]] for i in range(15))
    return chr((total % 26) + 65)

def get_fiscal_code(name, surname, date_birth, gender, town):
    cf = cod_lastname(cognome)
    cf += cod_name(nome)
    cf += cod_date_birth(date_birth, sesso)
    cf += cod_town(comune)
    cf += check_char(cf)
    return cf

def main():
    print("Tax Code Generator")

    lastname = input("Insert lastname: ")
    name = input("Insert name: ")
    date_birth = input("Insert date of birth (dd/mm/yyyy): ")
    gender = input("Insert Gender (M/F): ").upper()
    town = input("Insert Birth Town: ")

    tax_code = get_fiscal_code(name, lastname, date_birth, gender, town)
    print(f"Your tax code: {tax_code}")

if __name__ == "__main__":
    main()

Eacarsaich Currency Converter

Anns an eacarsaich seo, nì thu inneal-tionndaidh airgead a ’cleachdadh Python. Leigidh am prògram leat suimean a thionndadh eadar diofar airgeadan a’ cleachdadh API gus ìrean iomlaid ùraichte fhaighinn.

Riatanasan
  1. Leabharlannan Python: Cleachd an leabharlann requests gus iarrtasan HTTP a dhèanamh chun an ìre iomlaid API.
  2. API reataichean iomlaid: Cleachd mar API an-asgaidh ExchangeRate-API o Ìrean iomlaid fosgailte.
  3. Eadar-aghaidh cleachdaiche: Cruthaich eadar-aghaidh cleachdaiche loidhne-àithne sìmplidh a leigeas leis an neach-cleachdaidh an t-suim, an t-airgead stòr, agus an t-airgead ceann-uidhe a shònrachadh.
  4. Tionndadh airgead: Faigh ìrean iomlaid bhon API agus obraich a-mach an t-suim a chaidh atharrachadh.
Fuasgladh
import requests

# Function to get exchange rates from API
def get_exchange_rate(api_key, base_currency, target_currency):
    url = f"https://v6.exchangerate-api.com/v6/{api_key}/latest/{base_currency}"
    response = requests.get(url)
    data = response.json()
    if response.status_code == 200:
        rates = data['conversion_rates']
        return rates[target_currency]
    else:
        raise Exception(f"Error getting exchange rates: {data['error-type']}")

# Function to convert the amount between two currencies
def convert_currency(amount, base_currency, target_currency, api_key):
    rate = get_exchange_rate(api_key, base_currency, target_currency)
    converted_amount = amount * rate
    return converted_amount

def main():
    api_key = "your_api_key_here"
    print("Currency Converter")

    while True:
        try:
            amount = float(input("Enter the amount to convert: "))
            base_currency = input("Enter your source currency (i.e. USD, EUR): ").upper()
            target_currency = input("Enter the destination currency (i.e. USD, EUR): ").upper()

            converted_amount = convert_currency(amount, base_currency, target_currency, api_key)
            print(f"{amount} {base_currency} are {converted_amount:.2f} {target_currency}")

        except Exception as e:
            print(f"Errore: {e}")

        another = input("You want to make another conversion ? (y/n): ").lower()
        if another != 's':
            break

if __name__ == "__main__":
    main()

Autore