2017-01-27 15 views
-1

私はPython(および一般的にはコーディング)を使ってプログラミングするのが初めてで、小さな "helloworld"プロジェクトに関する助けをしたいと思います。ここで Python 3の別の数値変数(入力)から数値変数(入力)を引く方法

は私の現在の進行状況です:

#meet and greet program in python 
print('Hello, nice to meet you') 
username = input('Please enter your name: ') 
print('Nice to meet you', username) 
byear = input('What year were you born? :') 
print('So you were born in the year', byear, '?') 
information = input('Is this information is correct? :') 
if information == ('Yes') : 
    print('Ok') 
currentyr = input('Please enter the current year:') 
print('So that means you are', currentyr - byear,'years old. Right?') 

私がいるトラブルは、私が(入力による)、ユーザの誕生年を減算することにより、ユーザの現在のおおよその年齢を見つけたい最後の行であります(今年の入力から - 今年の詳細のインポート方法がわからない)。

これが最後の行の途中で見つけることができます:

、currentyr - byear、

誰かが、私は他の入力からこの入力変数(currentyr)を引くことができますどのように私に説明してください可能性がある場合ユーザーのおおよその年齢を達成するための変数(バイアール)。

ありがとうございます。 int

答えて

0

は、文字列を整数値に変換するためのPython標準組み込み関数です。あなたは、引数として数値を含む文字列でそれを呼び出し、それが実際の整数に変換された数値を返します。

print (int("1")+1) 

上記プリントここ2

は年齢を計算するための簡単なコードです:

from datetime import date 

year = input("Please enter your year of birth : ") 
now = date.today().year 
age = now-int(year) 

print ("Your age is %s" % age) 
+3

あなたのコードはPython 3と互換性がありません。 – fpietka

+0

残念ですが、あなたが編集して以来、 'input()'はpython3です(しかしpython2ではありません)が、あなたの 'print'文はあなたのせいではありません。今あなたの例はどのバージョンでも動作していません。私はその質問がpython3を求めていると付け加えるべきです。 – fpietka

+0

あなたの返信のために@fpietkaありがとう、私の#!私のシステムはMacOSなので、https://repl.it/languages/python3経由でチェックして、うまくいっているので、今度は私の#!を削除しました。 – Freeman

0

使用変換:

print('So that means you are', int(currentyr) - int(byear),'years old. Right?') 

あなたがinput()を使って、コマンドラインから変数を取得するとき、あなたは文字列を取得します。値を文字列として減算することはできません。 int()は、文字列から整数を作成します。

+0

意味変換? – fpietka

+0

@fpietkaはい、それは – Dmitry

0

2つの文字列内で減算を行うことはできません。変数を整数に明示的にキャストする必要があります。文字列を整数にキャストするには、このフォームint(variable)を使用します。

このコードは機能します。

#meet and greet program in python 
print('Hello, nice to meet you') 
username = input('Please enter your name: ') 
print('Nice to meet you', username) 
byear = int(input('What year were you born? :')) 
print('So you were born in the year', byear, '?') 
information = input('Is this information is correct? :') 
if information == ('Yes') : 
    print('Ok') 
currentyr = int(input('Please enter the current year:')) 
print('So that means you are', currentyr - byear,'years old. Right?') 
関連する問題